extra/tiles; eda/drivers/sqlite;sqlitecipher: Fixed warnings
[sdk] / eda / drivers / sqliteCipher / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.15.2.  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.
19 */
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 ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
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.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
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.
50 **
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.
54 **
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.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
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
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
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.
92 **
93 *************************************************************************
94 **
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
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.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
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
119 **
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.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
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.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
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.
146 **
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.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
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.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
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
185 */
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
192
193 /*
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200
201 /*
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.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209
210
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217
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.
220 **
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.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233
234
235 /*
236 ** The default size of a database page.
237 */
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
245
246 /*
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.
252 */
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
260
261
262 /*
263 ** Maximum number of pages in one database file.
264 **
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.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
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.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294
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
303
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318
319 /*
320 ** The following macros are used to cast pointers to integers and
321 ** integers to pointers.  The way you do this varies from one compiler
322 ** to the next, so we have developed the following set of #if statements
323 ** to generate appropriate macros for a wide range of compilers.
324 **
325 ** The correct "ANSI" way to do this is to use the intptr_t type.
326 ** Unfortunately, that typedef is not available on all compilers, or
327 ** if it is available, it requires an #include of specific headers
328 ** that vary from one machine to the next.
329 **
330 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
331 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
332 ** So we have to define the macros in different ways depending on the
333 ** compiler.
334 */
335 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
336 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
337 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
338 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
339 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
340 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
341 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
342 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
343 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
344 #else                          /* Generates a warning - but it always works */
345 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
346 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
347 #endif
348
349 /*
350 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
351 ** 0 means mutexes are permanently disable and the library is never
352 ** threadsafe.  1 means the library is serialized which is the highest
353 ** level of threadsafety.  2 means the libary is multithreaded - multiple
354 ** threads can use SQLite as long as no two threads try to use the same
355 ** database connection at the same time.
356 **
357 ** Older versions of SQLite used an optional THREADSAFE macro.
358 ** We support that for legacy.
359 */
360 #if !defined(SQLITE_THREADSAFE)
361 #if defined(THREADSAFE)
362 # define SQLITE_THREADSAFE THREADSAFE
363 #else
364 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
365 #endif
366 #endif
367
368 /*
369 ** Powersafe overwrite is on by default.  But can be turned off using
370 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
371 */
372 #ifndef SQLITE_POWERSAFE_OVERWRITE
373 # define SQLITE_POWERSAFE_OVERWRITE 1
374 #endif
375
376 /*
377 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
378 ** It determines whether or not the features related to
379 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
380 ** be overridden at runtime using the sqlite3_config() API.
381 */
382 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
383 # define SQLITE_DEFAULT_MEMSTATUS 1
384 #endif
385
386 /*
387 ** Exactly one of the following macros must be defined in order to
388 ** specify which memory allocation subsystem to use.
389 **
390 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
391 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
392 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
393 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
394 **
395 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
396 ** assert() macro is enabled, each call into the Win32 native heap subsystem
397 ** will cause HeapValidate to be called.  If heap validation should fail, an
398 ** assertion will be triggered.
399 **
400 ** (Historical note:  There used to be several other options, but we've
401 ** pared it down to just these three.)
402 **
403 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
404 ** the default.
405 */
406 #if defined(SQLITE_SYSTEM_MALLOC) \
407   + defined(SQLITE_WIN32_MALLOC) \
408   + defined(SQLITE_ZERO_MALLOC) \
409   + defined(SQLITE_MEMDEBUG)>1
410 # error "Two or more of the following compile-time configuration options\
411  are defined but at most one is allowed:\
412  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
413  SQLITE_ZERO_MALLOC"
414 #endif
415 #if defined(SQLITE_SYSTEM_MALLOC) \
416   + defined(SQLITE_WIN32_MALLOC) \
417   + defined(SQLITE_ZERO_MALLOC) \
418   + defined(SQLITE_MEMDEBUG)==0
419 # define SQLITE_SYSTEM_MALLOC 1
420 #endif
421
422 /*
423 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
424 ** sizes of memory allocations below this value where possible.
425 */
426 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
427 # define SQLITE_MALLOC_SOFT_LIMIT 1024
428 #endif
429
430 /*
431 ** We need to define _XOPEN_SOURCE as follows in order to enable
432 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
433 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
434 ** so it is omitted there.  See ticket #2673.
435 **
436 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
437 ** implemented on some systems.  So we avoid defining it at all
438 ** if it is already defined or if it is unneeded because we are
439 ** not doing a threadsafe build.  Ticket #2681.
440 **
441 ** See also ticket #2741.
442 */
443 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
444 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
445 #endif
446
447 /*
448 ** The TCL headers are only needed when compiling the TCL bindings.
449 */
450 #if defined(SQLITE_TCL) || defined(TCLSH)
451 # include <tcl.h>
452 #endif
453
454 /*
455 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
456 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
457 ** make it true by defining or undefining NDEBUG.
458 **
459 ** Setting NDEBUG makes the code smaller and run faster by disabling the
460 ** number assert() statements in the code.  So we want the default action
461 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
462 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
463 ** feature.
464 */
465 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
466 # define NDEBUG 1
467 #endif
468 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
469 # undef NDEBUG
470 #endif
471
472 /*
473 ** The testcase() macro is used to aid in coverage testing.  When
474 ** doing coverage testing, the condition inside the argument to
475 ** testcase() must be evaluated both true and false in order to
476 ** get full branch coverage.  The testcase() macro is inserted
477 ** to help ensure adequate test coverage in places where simple
478 ** condition/decision coverage is inadequate.  For example, testcase()
479 ** can be used to make sure boundary values are tested.  For
480 ** bitmask tests, testcase() can be used to make sure each bit
481 ** is significant and used at least once.  On switch statements
482 ** where multiple cases go to the same block of code, testcase()
483 ** can insure that all cases are evaluated.
484 **
485 */
486 #ifdef SQLITE_COVERAGE_TEST
487 SQLITE_PRIVATE   void sqlite3Coverage(int);
488 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
489 #else
490 # define testcase(X)
491 #endif
492
493 /*
494 ** The TESTONLY macro is used to enclose variable declarations or
495 ** other bits of code that are needed to support the arguments
496 ** within testcase() and assert() macros.
497 */
498 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
499 # define TESTONLY(X)  X
500 #else
501 # define TESTONLY(X)
502 #endif
503
504 /*
505 ** Sometimes we need a small amount of code such as a variable initialization
506 ** to setup for a later assert() statement.  We do not want this code to
507 ** appear when assert() is disabled.  The following macro is therefore
508 ** used to contain that setup code.  The "VVA" acronym stands for
509 ** "Verification, Validation, and Accreditation".  In other words, the
510 ** code within VVA_ONLY() will only run during verification processes.
511 */
512 #ifndef NDEBUG
513 # define VVA_ONLY(X)  X
514 #else
515 # define VVA_ONLY(X)
516 #endif
517
518 /*
519 ** The ALWAYS and NEVER macros surround boolean expressions which
520 ** are intended to always be true or false, respectively.  Such
521 ** expressions could be omitted from the code completely.  But they
522 ** are included in a few cases in order to enhance the resilience
523 ** of SQLite to unexpected behavior - to make the code "self-healing"
524 ** or "ductile" rather than being "brittle" and crashing at the first
525 ** hint of unplanned behavior.
526 **
527 ** In other words, ALWAYS and NEVER are added for defensive code.
528 **
529 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
530 ** be true and false so that the unreachable code then specify will
531 ** not be counted as untested code.
532 */
533 #if defined(SQLITE_COVERAGE_TEST)
534 # define ALWAYS(X)      (1)
535 # define NEVER(X)       (0)
536 #elif !defined(NDEBUG)
537 # define ALWAYS(X)      ((X)?1:(assert(0),0))
538 # define NEVER(X)       ((X)?(assert(0),1):0)
539 #else
540 # define ALWAYS(X)      (X)
541 # define NEVER(X)       (X)
542 #endif
543
544 /*
545 ** Return true (non-zero) if the input is a integer that is too large
546 ** to fit in 32-bits.  This macro is used inside of various testcase()
547 ** macros to verify that we have tested SQLite for large-file support.
548 */
549 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
550
551 /*
552 ** The macro unlikely() is a hint that surrounds a boolean
553 ** expression that is usually false.  Macro likely() surrounds
554 ** a boolean expression that is usually true.  GCC is able to
555 ** use these hints to generate better code, sometimes.
556 */
557 #if defined(__GNUC__) && 0
558 # define likely(X)    __builtin_expect((X),1)
559 # define unlikely(X)  __builtin_expect((X),0)
560 #else
561 # define likely(X)    !!(X)
562 # define unlikely(X)  !!(X)
563 #endif
564
565 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
566 /************** Begin file sqlite3.h *****************************************/
567 /*
568 ** 2001 September 15
569 **
570 ** The author disclaims copyright to this source code.  In place of
571 ** a legal notice, here is a blessing:
572 **
573 **    May you do good and not evil.
574 **    May you find forgiveness for yourself and forgive others.
575 **    May you share freely, never taking more than you give.
576 **
577 *************************************************************************
578 ** This header file defines the interface that the SQLite library
579 ** presents to client programs.  If a C-function, structure, datatype,
580 ** or constant definition does not appear in this file, then it is
581 ** not a published API of SQLite, is subject to change without
582 ** notice, and should not be referenced by programs that use SQLite.
583 **
584 ** Some of the definitions that are in this file are marked as
585 ** "experimental".  Experimental interfaces are normally new
586 ** features recently added to SQLite.  We do not anticipate changes
587 ** to experimental interfaces but reserve the right to make minor changes
588 ** if experience from use "in the wild" suggest such changes are prudent.
589 **
590 ** The official C-language API documentation for SQLite is derived
591 ** from comments in this file.  This file is the authoritative source
592 ** on how SQLite interfaces are suppose to operate.
593 **
594 ** The name of this file under configuration management is "sqlite.h.in".
595 ** The makefile makes some minor changes to this file (such as inserting
596 ** the version number) and changes its name to "sqlite3.h" as
597 ** part of the build process.
598 */
599 #ifndef _SQLITE3_H_
600 #define _SQLITE3_H_
601 #include <stdarg.h>     /* Needed for the definition of va_list */
602
603 /*
604 ** Make sure we can call this stuff from C++.
605 */
606 #if 0
607 extern "C" {
608 #endif
609
610
611 /*
612 ** Add the ability to override 'extern'
613 */
614 #ifndef SQLITE_EXTERN
615 # define SQLITE_EXTERN extern
616 #endif
617
618 #ifndef SQLITE_API
619 # define SQLITE_API
620 #endif
621
622
623 /*
624 ** These no-op macros are used in front of interfaces to mark those
625 ** interfaces as either deprecated or experimental.  New applications
626 ** should not use deprecated interfaces - they are support for backwards
627 ** compatibility only.  Application writers should be aware that
628 ** experimental interfaces are subject to change in point releases.
629 **
630 ** These macros used to resolve to various kinds of compiler magic that
631 ** would generate warning messages when they were used.  But that
632 ** compiler magic ended up generating such a flurry of bug reports
633 ** that we have taken it all out and gone back to using simple
634 ** noop macros.
635 */
636 #define SQLITE_DEPRECATED
637 #define SQLITE_EXPERIMENTAL
638
639 /*
640 ** Ensure these symbols were not defined by some previous header file.
641 */
642 #ifdef SQLITE_VERSION
643 # undef SQLITE_VERSION
644 #endif
645 #ifdef SQLITE_VERSION_NUMBER
646 # undef SQLITE_VERSION_NUMBER
647 #endif
648
649 /*
650 ** CAPI3REF: Compile-Time Library Version Numbers
651 **
652 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
653 ** evaluates to a string literal that is the SQLite version in the
654 ** format "X.Y.Z" where X is the major version number (always 3 for
655 ** SQLite3) and Y is the minor version number and Z is the release number.)^
656 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
657 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
658 ** numbers used in [SQLITE_VERSION].)^
659 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
660 ** be larger than the release from which it is derived.  Either Y will
661 ** be held constant and Z will be incremented or else Y will be incremented
662 ** and Z will be reset to zero.
663 **
664 ** Since version 3.6.18, SQLite source code has been stored in the
665 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
666 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
667 ** a string which identifies a particular check-in of SQLite
668 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
669 ** string contains the date and time of the check-in (UTC) and an SHA1
670 ** hash of the entire source tree.
671 **
672 ** See also: [sqlite3_libversion()],
673 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
674 ** [sqlite_version()] and [sqlite_source_id()].
675 */
676 #define SQLITE_VERSION        "3.7.15.2"
677 #define SQLITE_VERSION_NUMBER 3007015
678 #define SQLITE_SOURCE_ID      "2013-01-09 11:53:05 c0e09560d26f0a6456be9dd3447f5311eb4f238f"
679
680 /*
681 ** CAPI3REF: Run-Time Library Version Numbers
682 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
683 **
684 ** These interfaces provide the same information as the [SQLITE_VERSION],
685 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
686 ** but are associated with the library instead of the header file.  ^(Cautious
687 ** programmers might include assert() statements in their application to
688 ** verify that values returned by these interfaces match the macros in
689 ** the header, and thus insure that the application is
690 ** compiled with matching library and header files.
691 **
692 ** <blockquote><pre>
693 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
694 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
695 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
696 ** </pre></blockquote>)^
697 **
698 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
699 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
700 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
701 ** function is provided for use in DLLs since DLL users usually do not have
702 ** direct access to string constants within the DLL.  ^The
703 ** sqlite3_libversion_number() function returns an integer equal to
704 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
705 ** a pointer to a string constant whose value is the same as the
706 ** [SQLITE_SOURCE_ID] C preprocessor macro.
707 **
708 ** See also: [sqlite_version()] and [sqlite_source_id()].
709 */
710 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
711 SQLITE_API const char *sqlite3_libversion(void);
712 SQLITE_API const char *sqlite3_sourceid(void);
713 SQLITE_API int sqlite3_libversion_number(void);
714
715 /*
716 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
717 **
718 ** ^The sqlite3_compileoption_used() function returns 0 or 1
719 ** indicating whether the specified option was defined at
720 ** compile time.  ^The SQLITE_ prefix may be omitted from the
721 ** option name passed to sqlite3_compileoption_used().
722 **
723 ** ^The sqlite3_compileoption_get() function allows iterating
724 ** over the list of options that were defined at compile time by
725 ** returning the N-th compile time option string.  ^If N is out of range,
726 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
727 ** prefix is omitted from any strings returned by
728 ** sqlite3_compileoption_get().
729 **
730 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
731 ** and sqlite3_compileoption_get() may be omitted by specifying the
732 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
733 **
734 ** See also: SQL functions [sqlite_compileoption_used()] and
735 ** [sqlite_compileoption_get()] and the [compile_options pragma].
736 */
737 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
738 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
739 SQLITE_API const char *sqlite3_compileoption_get(int N);
740 #endif
741
742 /*
743 ** CAPI3REF: Test To See If The Library Is Threadsafe
744 **
745 ** ^The sqlite3_threadsafe() function returns zero if and only if
746 ** SQLite was compiled with mutexing code omitted due to the
747 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
748 **
749 ** SQLite can be compiled with or without mutexes.  When
750 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
751 ** are enabled and SQLite is threadsafe.  When the
752 ** [SQLITE_THREADSAFE] macro is 0,
753 ** the mutexes are omitted.  Without the mutexes, it is not safe
754 ** to use SQLite concurrently from more than one thread.
755 **
756 ** Enabling mutexes incurs a measurable performance penalty.
757 ** So if speed is of utmost importance, it makes sense to disable
758 ** the mutexes.  But for maximum safety, mutexes should be enabled.
759 ** ^The default behavior is for mutexes to be enabled.
760 **
761 ** This interface can be used by an application to make sure that the
762 ** version of SQLite that it is linking against was compiled with
763 ** the desired setting of the [SQLITE_THREADSAFE] macro.
764 **
765 ** This interface only reports on the compile-time mutex setting
766 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
767 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
768 ** can be fully or partially disabled using a call to [sqlite3_config()]
769 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
770 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
771 ** sqlite3_threadsafe() function shows only the compile-time setting of
772 ** thread safety, not any run-time changes to that setting made by
773 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
774 ** is unchanged by calls to sqlite3_config().)^
775 **
776 ** See the [threading mode] documentation for additional information.
777 */
778 SQLITE_API int sqlite3_threadsafe(void);
779
780 /*
781 ** CAPI3REF: Database Connection Handle
782 ** KEYWORDS: {database connection} {database connections}
783 **
784 ** Each open SQLite database is represented by a pointer to an instance of
785 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
786 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
787 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
788 ** and [sqlite3_close_v2()] are its destructors.  There are many other
789 ** interfaces (such as
790 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
791 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
792 ** sqlite3 object.
793 */
794 typedef struct sqlite3 sqlite3;
795
796 /*
797 ** CAPI3REF: 64-Bit Integer Types
798 ** KEYWORDS: sqlite_int64 sqlite_uint64
799 **
800 ** Because there is no cross-platform way to specify 64-bit integer types
801 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
802 **
803 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
804 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
805 ** compatibility only.
806 **
807 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
808 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
809 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
810 ** between 0 and +18446744073709551615 inclusive.
811 */
812 #ifdef SQLITE_INT64_TYPE
813   typedef SQLITE_INT64_TYPE sqlite_int64;
814   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
815 #elif defined(_MSC_VER) || defined(__BORLANDC__)
816   typedef __int64 sqlite_int64;
817   typedef unsigned __int64 sqlite_uint64;
818 #else
819   typedef long long int sqlite_int64;
820   typedef unsigned long long int sqlite_uint64;
821 #endif
822 typedef sqlite_int64 sqlite3_int64;
823 typedef sqlite_uint64 sqlite3_uint64;
824
825 /*
826 ** If compiling for a processor that lacks floating point support,
827 ** substitute integer for floating-point.
828 */
829 #ifdef SQLITE_OMIT_FLOATING_POINT
830 # define double sqlite3_int64
831 #endif
832
833 /*
834 ** CAPI3REF: Closing A Database Connection
835 **
836 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
837 ** for the [sqlite3] object.
838 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
839 ** the [sqlite3] object is successfully destroyed and all associated
840 ** resources are deallocated.
841 **
842 ** ^If the database connection is associated with unfinalized prepared
843 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
844 ** will leave the database connection open and return [SQLITE_BUSY].
845 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
846 ** and unfinished sqlite3_backups, then the database connection becomes
847 ** an unusable "zombie" which will automatically be deallocated when the
848 ** last prepared statement is finalized or the last sqlite3_backup is
849 ** finished.  The sqlite3_close_v2() interface is intended for use with
850 ** host languages that are garbage collected, and where the order in which
851 ** destructors are called is arbitrary.
852 **
853 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
854 ** [sqlite3_blob_close | close] all [BLOB handles], and
855 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
856 ** with the [sqlite3] object prior to attempting to close the object.  ^If
857 ** sqlite3_close() is called on a [database connection] that still has
858 ** outstanding [prepared statements], [BLOB handles], and/or
859 ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
860 ** of resources is deferred until all [prepared statements], [BLOB handles],
861 ** and [sqlite3_backup] objects are also destroyed.
862 **
863 ** ^If an [sqlite3] object is destroyed while a transaction is open,
864 ** the transaction is automatically rolled back.
865 **
866 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
867 ** must be either a NULL
868 ** pointer or an [sqlite3] object pointer obtained
869 ** from [sqlite3_open()], [sqlite3_open16()], or
870 ** [sqlite3_open_v2()], and not previously closed.
871 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
872 ** argument is a harmless no-op.
873 */
874 SQLITE_API int sqlite3_close(sqlite3*);
875 SQLITE_API int sqlite3_close_v2(sqlite3*);
876
877 /*
878 ** The type for a callback function.
879 ** This is legacy and deprecated.  It is included for historical
880 ** compatibility and is not documented.
881 */
882 typedef int (*sqlite3_callback)(void*,int,char**, char**);
883
884 /*
885 ** CAPI3REF: One-Step Query Execution Interface
886 **
887 ** The sqlite3_exec() interface is a convenience wrapper around
888 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
889 ** that allows an application to run multiple statements of SQL
890 ** without having to use a lot of C code.
891 **
892 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
893 ** semicolon-separate SQL statements passed into its 2nd argument,
894 ** in the context of the [database connection] passed in as its 1st
895 ** argument.  ^If the callback function of the 3rd argument to
896 ** sqlite3_exec() is not NULL, then it is invoked for each result row
897 ** coming out of the evaluated SQL statements.  ^The 4th argument to
898 ** sqlite3_exec() is relayed through to the 1st argument of each
899 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
900 ** is NULL, then no callback is ever invoked and result rows are
901 ** ignored.
902 **
903 ** ^If an error occurs while evaluating the SQL statements passed into
904 ** sqlite3_exec(), then execution of the current statement stops and
905 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
906 ** is not NULL then any error message is written into memory obtained
907 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
908 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
909 ** on error message strings returned through the 5th parameter of
910 ** of sqlite3_exec() after the error message string is no longer needed.
911 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
912 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
913 ** NULL before returning.
914 **
915 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
916 ** routine returns SQLITE_ABORT without invoking the callback again and
917 ** without running any subsequent SQL statements.
918 **
919 ** ^The 2nd argument to the sqlite3_exec() callback function is the
920 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
921 ** callback is an array of pointers to strings obtained as if from
922 ** [sqlite3_column_text()], one for each column.  ^If an element of a
923 ** result row is NULL then the corresponding string pointer for the
924 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
925 ** sqlite3_exec() callback is an array of pointers to strings where each
926 ** entry represents the name of corresponding result column as obtained
927 ** from [sqlite3_column_name()].
928 **
929 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
930 ** to an empty string, or a pointer that contains only whitespace and/or
931 ** SQL comments, then no SQL statements are evaluated and the database
932 ** is not changed.
933 **
934 ** Restrictions:
935 **
936 ** <ul>
937 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
938 **      is a valid and open [database connection].
939 ** <li> The application must not close [database connection] specified by
940 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
941 ** <li> The application must not modify the SQL statement text passed into
942 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
943 ** </ul>
944 */
945 SQLITE_API int sqlite3_exec(
946   sqlite3*,                                  /* An open database */
947   const char *sql,                           /* SQL to be evaluated */
948   int (*callback)(void*,int,char**,char**),  /* Callback function */
949   void *,                                    /* 1st argument to callback */
950   char **errmsg                              /* Error msg written here */
951 );
952
953 /*
954 ** CAPI3REF: Result Codes
955 ** KEYWORDS: SQLITE_OK {error code} {error codes}
956 ** KEYWORDS: {result code} {result codes}
957 **
958 ** Many SQLite functions return an integer result code from the set shown
959 ** here in order to indicate success or failure.
960 **
961 ** New error codes may be added in future versions of SQLite.
962 **
963 ** See also: [SQLITE_IOERR_READ | extended result codes],
964 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
965 */
966 #define SQLITE_OK           0   /* Successful result */
967 /* beginning-of-error-codes */
968 #define SQLITE_ERROR        1   /* SQL error or missing database */
969 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
970 #define SQLITE_PERM         3   /* Access permission denied */
971 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
972 #define SQLITE_BUSY         5   /* The database file is locked */
973 #define SQLITE_LOCKED       6   /* A table in the database is locked */
974 #define SQLITE_NOMEM        7   /* A malloc() failed */
975 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
976 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
977 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
978 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
979 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
980 #define SQLITE_FULL        13   /* Insertion failed because database is full */
981 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
982 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
983 #define SQLITE_EMPTY       16   /* Database is empty */
984 #define SQLITE_SCHEMA      17   /* The database schema changed */
985 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
986 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
987 #define SQLITE_MISMATCH    20   /* Data type mismatch */
988 #define SQLITE_MISUSE      21   /* Library used incorrectly */
989 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
990 #define SQLITE_AUTH        23   /* Authorization denied */
991 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
992 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
993 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
994 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
995 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
996 /* end-of-error-codes */
997
998 /*
999 ** CAPI3REF: Extended Result Codes
1000 ** KEYWORDS: {extended error code} {extended error codes}
1001 ** KEYWORDS: {extended result code} {extended result codes}
1002 **
1003 ** In its default configuration, SQLite API routines return one of 26 integer
1004 ** [SQLITE_OK | result codes].  However, experience has shown that many of
1005 ** these result codes are too coarse-grained.  They do not provide as
1006 ** much information about problems as programmers might like.  In an effort to
1007 ** address this, newer versions of SQLite (version 3.3.8 and later) include
1008 ** support for additional result codes that provide more detailed information
1009 ** about errors. The extended result codes are enabled or disabled
1010 ** on a per database connection basis using the
1011 ** [sqlite3_extended_result_codes()] API.
1012 **
1013 ** Some of the available extended result codes are listed here.
1014 ** One may expect the number of extended result codes will be expand
1015 ** over time.  Software that uses extended result codes should expect
1016 ** to see new result codes in future releases of SQLite.
1017 **
1018 ** The SQLITE_OK result code will never be extended.  It will always
1019 ** be exactly zero.
1020 */
1021 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
1022 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
1023 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1024 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1025 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1026 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1027 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1028 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1029 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1030 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1031 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1032 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1033 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1034 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1035 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1036 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1037 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1038 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1039 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1040 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1041 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1042 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1043 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
1044 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1045 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1046 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1047 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1048 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
1049 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1050 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1051 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1052 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1053
1054 /*
1055 ** CAPI3REF: Flags For File Open Operations
1056 **
1057 ** These bit values are intended for use in the
1058 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1059 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1060 */
1061 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1062 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1063 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1064 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1065 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1066 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1067 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1068 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1069 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1070 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1071 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1072 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1073 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1074 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1075 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1076 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1077 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1078 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1079 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1080 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1081
1082 /* Reserved:                         0x00F00000 */
1083
1084 /*
1085 ** CAPI3REF: Device Characteristics
1086 **
1087 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1088 ** object returns an integer which is a vector of these
1089 ** bit values expressing I/O characteristics of the mass storage
1090 ** device that holds the file that the [sqlite3_io_methods]
1091 ** refers to.
1092 **
1093 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1094 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1095 ** mean that writes of blocks that are nnn bytes in size and
1096 ** are aligned to an address which is an integer multiple of
1097 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1098 ** that when data is appended to a file, the data is appended
1099 ** first then the size of the file is extended, never the other
1100 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1101 ** information is written to disk in the same order as calls
1102 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1103 ** after reboot following a crash or power loss, the only bytes in a
1104 ** file that were written at the application level might have changed
1105 ** and that adjacent bytes, even bytes within the same sector are
1106 ** guaranteed to be unchanged.
1107 */
1108 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1109 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1110 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1111 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1112 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1113 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1114 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1115 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1116 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1117 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1118 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1119 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1120 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1121
1122 /*
1123 ** CAPI3REF: File Locking Levels
1124 **
1125 ** SQLite uses one of these integer values as the second
1126 ** argument to calls it makes to the xLock() and xUnlock() methods
1127 ** of an [sqlite3_io_methods] object.
1128 */
1129 #define SQLITE_LOCK_NONE          0
1130 #define SQLITE_LOCK_SHARED        1
1131 #define SQLITE_LOCK_RESERVED      2
1132 #define SQLITE_LOCK_PENDING       3
1133 #define SQLITE_LOCK_EXCLUSIVE     4
1134
1135 /*
1136 ** CAPI3REF: Synchronization Type Flags
1137 **
1138 ** When SQLite invokes the xSync() method of an
1139 ** [sqlite3_io_methods] object it uses a combination of
1140 ** these integer values as the second argument.
1141 **
1142 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1143 ** sync operation only needs to flush data to mass storage.  Inode
1144 ** information need not be flushed. If the lower four bits of the flag
1145 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1146 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1147 ** to use Mac OS X style fullsync instead of fsync().
1148 **
1149 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1150 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1151 ** settings.  The [synchronous pragma] determines when calls to the
1152 ** xSync VFS method occur and applies uniformly across all platforms.
1153 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1154 ** energetic or rigorous or forceful the sync operations are and
1155 ** only make a difference on Mac OSX for the default SQLite code.
1156 ** (Third-party VFS implementations might also make the distinction
1157 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1158 ** operating systems natively supported by SQLite, only Mac OSX
1159 ** cares about the difference.)
1160 */
1161 #define SQLITE_SYNC_NORMAL        0x00002
1162 #define SQLITE_SYNC_FULL          0x00003
1163 #define SQLITE_SYNC_DATAONLY      0x00010
1164
1165 /*
1166 ** CAPI3REF: OS Interface Open File Handle
1167 **
1168 ** An [sqlite3_file] object represents an open file in the
1169 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1170 ** implementations will
1171 ** want to subclass this object by appending additional fields
1172 ** for their own use.  The pMethods entry is a pointer to an
1173 ** [sqlite3_io_methods] object that defines methods for performing
1174 ** I/O operations on the open file.
1175 */
1176 typedef struct sqlite3_file sqlite3_file;
1177 struct sqlite3_file {
1178   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1179 };
1180
1181 /*
1182 ** CAPI3REF: OS Interface File Virtual Methods Object
1183 **
1184 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1185 ** [sqlite3_file] object (or, more commonly, a subclass of the
1186 ** [sqlite3_file] object) with a pointer to an instance of this object.
1187 ** This object defines the methods used to perform various operations
1188 ** against the open file represented by the [sqlite3_file] object.
1189 **
1190 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1191 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1192 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1193 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1194 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1195 ** to NULL.
1196 **
1197 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1198 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1199 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1200 ** flag may be ORed in to indicate that only the data of the file
1201 ** and not its inode needs to be synced.
1202 **
1203 ** The integer values to xLock() and xUnlock() are one of
1204 ** <ul>
1205 ** <li> [SQLITE_LOCK_NONE],
1206 ** <li> [SQLITE_LOCK_SHARED],
1207 ** <li> [SQLITE_LOCK_RESERVED],
1208 ** <li> [SQLITE_LOCK_PENDING], or
1209 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1210 ** </ul>
1211 ** xLock() increases the lock. xUnlock() decreases the lock.
1212 ** The xCheckReservedLock() method checks whether any database connection,
1213 ** either in this process or in some other process, is holding a RESERVED,
1214 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1215 ** if such a lock exists and false otherwise.
1216 **
1217 ** The xFileControl() method is a generic interface that allows custom
1218 ** VFS implementations to directly control an open file using the
1219 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1220 ** integer opcode.  The third argument is a generic pointer intended to
1221 ** point to a structure that may contain arguments or space in which to
1222 ** write return values.  Potential uses for xFileControl() might be
1223 ** functions to enable blocking locks with timeouts, to change the
1224 ** locking strategy (for example to use dot-file locks), to inquire
1225 ** about the status of a lock, or to break stale locks.  The SQLite
1226 ** core reserves all opcodes less than 100 for its own use.
1227 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1228 ** Applications that define a custom xFileControl method should use opcodes
1229 ** greater than 100 to avoid conflicts.  VFS implementations should
1230 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1231 ** recognize.
1232 **
1233 ** The xSectorSize() method returns the sector size of the
1234 ** device that underlies the file.  The sector size is the
1235 ** minimum write that can be performed without disturbing
1236 ** other bytes in the file.  The xDeviceCharacteristics()
1237 ** method returns a bit vector describing behaviors of the
1238 ** underlying device:
1239 **
1240 ** <ul>
1241 ** <li> [SQLITE_IOCAP_ATOMIC]
1242 ** <li> [SQLITE_IOCAP_ATOMIC512]
1243 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1244 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1245 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1246 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1247 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1248 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1249 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1250 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1251 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1252 ** </ul>
1253 **
1254 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1255 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1256 ** mean that writes of blocks that are nnn bytes in size and
1257 ** are aligned to an address which is an integer multiple of
1258 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1259 ** that when data is appended to a file, the data is appended
1260 ** first then the size of the file is extended, never the other
1261 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1262 ** information is written to disk in the same order as calls
1263 ** to xWrite().
1264 **
1265 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1266 ** in the unread portions of the buffer with zeros.  A VFS that
1267 ** fails to zero-fill short reads might seem to work.  However,
1268 ** failure to zero-fill short reads will eventually lead to
1269 ** database corruption.
1270 */
1271 typedef struct sqlite3_io_methods sqlite3_io_methods;
1272 struct sqlite3_io_methods {
1273   int iVersion;
1274   int (*xClose)(sqlite3_file*);
1275   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1276   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1277   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1278   int (*xSync)(sqlite3_file*, int flags);
1279   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1280   int (*xLock)(sqlite3_file*, int);
1281   int (*xUnlock)(sqlite3_file*, int);
1282   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1283   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1284   int (*xSectorSize)(sqlite3_file*);
1285   int (*xDeviceCharacteristics)(sqlite3_file*);
1286   /* Methods above are valid for version 1 */
1287   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1288   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1289   void (*xShmBarrier)(sqlite3_file*);
1290   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1291   /* Methods above are valid for version 2 */
1292   /* Additional methods may be added in future releases */
1293 };
1294
1295 /*
1296 ** CAPI3REF: Standard File Control Opcodes
1297 **
1298 ** These integer constants are opcodes for the xFileControl method
1299 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1300 ** interface.
1301 **
1302 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1303 ** opcode causes the xFileControl method to write the current state of
1304 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1305 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1306 ** into an integer that the pArg argument points to. This capability
1307 ** is used during testing and only needs to be supported when SQLITE_TEST
1308 ** is defined.
1309 ** <ul>
1310 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1311 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1312 ** layer a hint of how large the database file will grow to be during the
1313 ** current transaction.  This hint is not guaranteed to be accurate but it
1314 ** is often close.  The underlying VFS might choose to preallocate database
1315 ** file space based on this hint in order to help writes to the database
1316 ** file run faster.
1317 **
1318 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1319 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1320 ** extends and truncates the database file in chunks of a size specified
1321 ** by the user. The fourth argument to [sqlite3_file_control()] should
1322 ** point to an integer (type int) containing the new chunk-size to use
1323 ** for the nominated database. Allocating database file space in large
1324 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1325 ** improve performance on some systems.
1326 **
1327 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1328 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1329 ** to the [sqlite3_file] object associated with a particular database
1330 ** connection.  See the [sqlite3_file_control()] documentation for
1331 ** additional information.
1332 **
1333 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1334 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1335 ** SQLite and sent to all VFSes in place of a call to the xSync method
1336 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1337 ** Some specialized VFSes need this signal in order to operate correctly
1338 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1339 ** VFSes do not need this signal and should silently ignore this opcode.
1340 ** Applications should not call [sqlite3_file_control()] with this
1341 ** opcode as doing so may disrupt the operation of the specialized VFSes
1342 ** that do require it.
1343 **
1344 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1345 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1346 ** retry counts and intervals for certain disk I/O operations for the
1347 ** windows [VFS] in order to provide robustness in the presence of
1348 ** anti-virus programs.  By default, the windows VFS will retry file read,
1349 ** file write, and file delete operations up to 10 times, with a delay
1350 ** of 25 milliseconds before the first retry and with the delay increasing
1351 ** by an additional 25 milliseconds with each subsequent retry.  This
1352 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1353 ** to be adjusted.  The values are changed for all database connections
1354 ** within the same process.  The argument is a pointer to an array of two
1355 ** integers where the first integer i the new retry count and the second
1356 ** integer is the delay.  If either integer is negative, then the setting
1357 ** is not changed but instead the prior value of that setting is written
1358 ** into the array entry, allowing the current retry settings to be
1359 ** interrogated.  The zDbName parameter is ignored.
1360 **
1361 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1362 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1363 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1364 ** write ahead log and shared memory files used for transaction control
1365 ** are automatically deleted when the latest connection to the database
1366 ** closes.  Setting persistent WAL mode causes those files to persist after
1367 ** close.  Persisting the files is useful when other processes that do not
1368 ** have write permission on the directory containing the database file want
1369 ** to read the database file, as the WAL and shared memory files must exist
1370 ** in order for the database to be readable.  The fourth parameter to
1371 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1372 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1373 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1374 ** WAL persistence setting.
1375 **
1376 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1377 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1378 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1379 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1380 ** xDeviceCharacteristics methods. The fourth parameter to
1381 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1382 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1383 ** mode.  If the integer is -1, then it is overwritten with the current
1384 ** zero-damage mode setting.
1385 **
1386 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1387 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1388 ** a write transaction to indicate that, unless it is rolled back for some
1389 ** reason, the entire database file will be overwritten by the current
1390 ** transaction. This is used by VACUUM operations.
1391 **
1392 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1393 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1394 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1395 ** final bottom-level VFS are written into memory obtained from
1396 ** [sqlite3_malloc()] and the result is stored in the char* variable
1397 ** that the fourth parameter of [sqlite3_file_control()] points to.
1398 ** The caller is responsible for freeing the memory when done.  As with
1399 ** all file-control actions, there is no guarantee that this will actually
1400 ** do anything.  Callers should initialize the char* variable to a NULL
1401 ** pointer in case this file-control is not implemented.  This file-control
1402 ** is intended for diagnostic use only.
1403 **
1404 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1405 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1406 ** file control is sent to the open [sqlite3_file] object corresponding
1407 ** to the database file to which the pragma statement refers. ^The argument
1408 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1409 ** pointers to strings (char**) in which the second element of the array
1410 ** is the name of the pragma and the third element is the argument to the
1411 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1412 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1413 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1414 ** or the equivalent and that string will become the result of the pragma or
1415 ** the error message if the pragma fails. ^If the
1416 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1417 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1418 ** file control returns [SQLITE_OK], then the parser assumes that the
1419 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1420 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1421 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1422 ** that the VFS encountered an error while handling the [PRAGMA] and the
1423 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1424 ** file control occurs at the beginning of pragma statement analysis and so
1425 ** it is able to override built-in [PRAGMA] statements.
1426 **
1427 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1428 ** ^This file-control may be invoked by SQLite on the database file handle
1429 ** shortly after it is opened in order to provide a custom VFS with access
1430 ** to the connections busy-handler callback. The argument is of type (void **)
1431 ** - an array of two (void *) values. The first (void *) actually points
1432 ** to a function of type (int (*)(void *)). In order to invoke the connections
1433 ** busy-handler, this function should be invoked with the second (void *) in
1434 ** the array as the only argument. If it returns non-zero, then the operation
1435 ** should be retried. If it returns zero, the custom VFS should abandon the
1436 ** current operation.
1437 **
1438 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1439 ** ^Application can invoke this file-control to have SQLite generate a
1440 ** temporary filename using the same algorithm that is followed to generate
1441 ** temporary filenames for TEMP tables and other internal uses.  The
1442 ** argument should be a char** which will be filled with the filename
1443 ** written into memory obtained from [sqlite3_malloc()].  The caller should
1444 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1445 **
1446 ** </ul>
1447 */
1448 #define SQLITE_FCNTL_LOCKSTATE               1
1449 #define SQLITE_GET_LOCKPROXYFILE             2
1450 #define SQLITE_SET_LOCKPROXYFILE             3
1451 #define SQLITE_LAST_ERRNO                    4
1452 #define SQLITE_FCNTL_SIZE_HINT               5
1453 #define SQLITE_FCNTL_CHUNK_SIZE              6
1454 #define SQLITE_FCNTL_FILE_POINTER            7
1455 #define SQLITE_FCNTL_SYNC_OMITTED            8
1456 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1457 #define SQLITE_FCNTL_PERSIST_WAL            10
1458 #define SQLITE_FCNTL_OVERWRITE              11
1459 #define SQLITE_FCNTL_VFSNAME                12
1460 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1461 #define SQLITE_FCNTL_PRAGMA                 14
1462 #define SQLITE_FCNTL_BUSYHANDLER            15
1463 #define SQLITE_FCNTL_TEMPFILENAME           16
1464
1465 /*
1466 ** CAPI3REF: Mutex Handle
1467 **
1468 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1469 ** abstract type for a mutex object.  The SQLite core never looks
1470 ** at the internal representation of an [sqlite3_mutex].  It only
1471 ** deals with pointers to the [sqlite3_mutex] object.
1472 **
1473 ** Mutexes are created using [sqlite3_mutex_alloc()].
1474 */
1475 typedef struct sqlite3_mutex sqlite3_mutex;
1476
1477 /*
1478 ** CAPI3REF: OS Interface Object
1479 **
1480 ** An instance of the sqlite3_vfs object defines the interface between
1481 ** the SQLite core and the underlying operating system.  The "vfs"
1482 ** in the name of the object stands for "virtual file system".  See
1483 ** the [VFS | VFS documentation] for further information.
1484 **
1485 ** The value of the iVersion field is initially 1 but may be larger in
1486 ** future versions of SQLite.  Additional fields may be appended to this
1487 ** object when the iVersion value is increased.  Note that the structure
1488 ** of the sqlite3_vfs object changes in the transaction between
1489 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1490 ** modified.
1491 **
1492 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1493 ** structure used by this VFS.  mxPathname is the maximum length of
1494 ** a pathname in this VFS.
1495 **
1496 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1497 ** the pNext pointer.  The [sqlite3_vfs_register()]
1498 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1499 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1500 ** searches the list.  Neither the application code nor the VFS
1501 ** implementation should use the pNext pointer.
1502 **
1503 ** The pNext field is the only field in the sqlite3_vfs
1504 ** structure that SQLite will ever modify.  SQLite will only access
1505 ** or modify this field while holding a particular static mutex.
1506 ** The application should never modify anything within the sqlite3_vfs
1507 ** object once the object has been registered.
1508 **
1509 ** The zName field holds the name of the VFS module.  The name must
1510 ** be unique across all VFS modules.
1511 **
1512 ** [[sqlite3_vfs.xOpen]]
1513 ** ^SQLite guarantees that the zFilename parameter to xOpen
1514 ** is either a NULL pointer or string obtained
1515 ** from xFullPathname() with an optional suffix added.
1516 ** ^If a suffix is added to the zFilename parameter, it will
1517 ** consist of a single "-" character followed by no more than
1518 ** 11 alphanumeric and/or "-" characters.
1519 ** ^SQLite further guarantees that
1520 ** the string will be valid and unchanged until xClose() is
1521 ** called. Because of the previous sentence,
1522 ** the [sqlite3_file] can safely store a pointer to the
1523 ** filename if it needs to remember the filename for some reason.
1524 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1525 ** must invent its own temporary name for the file.  ^Whenever the
1526 ** xFilename parameter is NULL it will also be the case that the
1527 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1528 **
1529 ** The flags argument to xOpen() includes all bits set in
1530 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1531 ** or [sqlite3_open16()] is used, then flags includes at least
1532 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1533 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1534 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1535 **
1536 ** ^(SQLite will also add one of the following flags to the xOpen()
1537 ** call, depending on the object being opened:
1538 **
1539 ** <ul>
1540 ** <li>  [SQLITE_OPEN_MAIN_DB]
1541 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1542 ** <li>  [SQLITE_OPEN_TEMP_DB]
1543 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1544 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1545 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1546 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1547 ** <li>  [SQLITE_OPEN_WAL]
1548 ** </ul>)^
1549 **
1550 ** The file I/O implementation can use the object type flags to
1551 ** change the way it deals with files.  For example, an application
1552 ** that does not care about crash recovery or rollback might make
1553 ** the open of a journal file a no-op.  Writes to this journal would
1554 ** also be no-ops, and any attempt to read the journal would return
1555 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1556 ** file will be doing page-aligned sector reads and writes in a random
1557 ** order and set up its I/O subsystem accordingly.
1558 **
1559 ** SQLite might also add one of the following flags to the xOpen method:
1560 **
1561 ** <ul>
1562 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1563 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1564 ** </ul>
1565 **
1566 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1567 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1568 ** will be set for TEMP databases and their journals, transient
1569 ** databases, and subjournals.
1570 **
1571 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1572 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1573 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1574 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1575 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1576 ** be created, and that it is an error if it already exists.
1577 ** It is <i>not</i> used to indicate the file should be opened
1578 ** for exclusive access.
1579 **
1580 ** ^At least szOsFile bytes of memory are allocated by SQLite
1581 ** to hold the  [sqlite3_file] structure passed as the third
1582 ** argument to xOpen.  The xOpen method does not have to
1583 ** allocate the structure; it should just fill it in.  Note that
1584 ** the xOpen method must set the sqlite3_file.pMethods to either
1585 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1586 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1587 ** element will be valid after xOpen returns regardless of the success
1588 ** or failure of the xOpen call.
1589 **
1590 ** [[sqlite3_vfs.xAccess]]
1591 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1592 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1593 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1594 ** to test whether a file is at least readable.   The file can be a
1595 ** directory.
1596 **
1597 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1598 ** output buffer xFullPathname.  The exact size of the output buffer
1599 ** is also passed as a parameter to both  methods. If the output buffer
1600 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1601 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1602 ** to prevent this by setting mxPathname to a sufficiently large value.
1603 **
1604 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1605 ** interfaces are not strictly a part of the filesystem, but they are
1606 ** included in the VFS structure for completeness.
1607 ** The xRandomness() function attempts to return nBytes bytes
1608 ** of good-quality randomness into zOut.  The return value is
1609 ** the actual number of bytes of randomness obtained.
1610 ** The xSleep() method causes the calling thread to sleep for at
1611 ** least the number of microseconds given.  ^The xCurrentTime()
1612 ** method returns a Julian Day Number for the current date and time as
1613 ** a floating point value.
1614 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1615 ** Day Number multiplied by 86400000 (the number of milliseconds in
1616 ** a 24-hour day).
1617 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1618 ** date and time if that method is available (if iVersion is 2 or
1619 ** greater and the function pointer is not NULL) and will fall back
1620 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1621 **
1622 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1623 ** are not used by the SQLite core.  These optional interfaces are provided
1624 ** by some VFSes to facilitate testing of the VFS code. By overriding
1625 ** system calls with functions under its control, a test program can
1626 ** simulate faults and error conditions that would otherwise be difficult
1627 ** or impossible to induce.  The set of system calls that can be overridden
1628 ** varies from one VFS to another, and from one version of the same VFS to the
1629 ** next.  Applications that use these interfaces must be prepared for any
1630 ** or all of these interfaces to be NULL or for their behavior to change
1631 ** from one release to the next.  Applications must not attempt to access
1632 ** any of these methods if the iVersion of the VFS is less than 3.
1633 */
1634 typedef struct sqlite3_vfs sqlite3_vfs;
1635 typedef void (*sqlite3_syscall_ptr)(void);
1636 struct sqlite3_vfs {
1637   int iVersion;            /* Structure version number (currently 3) */
1638   int szOsFile;            /* Size of subclassed sqlite3_file */
1639   int mxPathname;          /* Maximum file pathname length */
1640   sqlite3_vfs *pNext;      /* Next registered VFS */
1641   const char *zName;       /* Name of this virtual file system */
1642   void *pAppData;          /* Pointer to application-specific data */
1643   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1644                int flags, int *pOutFlags);
1645   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1646   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1647   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1648   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1649   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1650   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1651   void (*xDlClose)(sqlite3_vfs*, void*);
1652   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1653   int (*xSleep)(sqlite3_vfs*, int microseconds);
1654   int (*xCurrentTime)(sqlite3_vfs*, double*);
1655   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1656   /*
1657   ** The methods above are in version 1 of the sqlite_vfs object
1658   ** definition.  Those that follow are added in version 2 or later
1659   */
1660   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1661   /*
1662   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1663   ** Those below are for version 3 and greater.
1664   */
1665   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1666   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1667   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1668   /*
1669   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1670   ** New fields may be appended in figure versions.  The iVersion
1671   ** value will increment whenever this happens.
1672   */
1673 };
1674
1675 /*
1676 ** CAPI3REF: Flags for the xAccess VFS method
1677 **
1678 ** These integer constants can be used as the third parameter to
1679 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1680 ** what kind of permissions the xAccess method is looking for.
1681 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1682 ** simply checks whether the file exists.
1683 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1684 ** checks whether the named directory is both readable and writable
1685 ** (in other words, if files can be added, removed, and renamed within
1686 ** the directory).
1687 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1688 ** [temp_store_directory pragma], though this could change in a future
1689 ** release of SQLite.
1690 ** With SQLITE_ACCESS_READ, the xAccess method
1691 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1692 ** currently unused, though it might be used in a future release of
1693 ** SQLite.
1694 */
1695 #define SQLITE_ACCESS_EXISTS    0
1696 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1697 #define SQLITE_ACCESS_READ      2   /* Unused */
1698
1699 /*
1700 ** CAPI3REF: Flags for the xShmLock VFS method
1701 **
1702 ** These integer constants define the various locking operations
1703 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1704 ** following are the only legal combinations of flags to the
1705 ** xShmLock method:
1706 **
1707 ** <ul>
1708 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1709 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1710 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1711 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1712 ** </ul>
1713 **
1714 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1715 ** was given no the corresponding lock.
1716 **
1717 ** The xShmLock method can transition between unlocked and SHARED or
1718 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1719 ** and EXCLUSIVE.
1720 */
1721 #define SQLITE_SHM_UNLOCK       1
1722 #define SQLITE_SHM_LOCK         2
1723 #define SQLITE_SHM_SHARED       4
1724 #define SQLITE_SHM_EXCLUSIVE    8
1725
1726 /*
1727 ** CAPI3REF: Maximum xShmLock index
1728 **
1729 ** The xShmLock method on [sqlite3_io_methods] may use values
1730 ** between 0 and this upper bound as its "offset" argument.
1731 ** The SQLite core will never attempt to acquire or release a
1732 ** lock outside of this range
1733 */
1734 #define SQLITE_SHM_NLOCK        8
1735
1736
1737 /*
1738 ** CAPI3REF: Initialize The SQLite Library
1739 **
1740 ** ^The sqlite3_initialize() routine initializes the
1741 ** SQLite library.  ^The sqlite3_shutdown() routine
1742 ** deallocates any resources that were allocated by sqlite3_initialize().
1743 ** These routines are designed to aid in process initialization and
1744 ** shutdown on embedded systems.  Workstation applications using
1745 ** SQLite normally do not need to invoke either of these routines.
1746 **
1747 ** A call to sqlite3_initialize() is an "effective" call if it is
1748 ** the first time sqlite3_initialize() is invoked during the lifetime of
1749 ** the process, or if it is the first time sqlite3_initialize() is invoked
1750 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1751 ** of sqlite3_initialize() does any initialization.  All other calls
1752 ** are harmless no-ops.)^
1753 **
1754 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1755 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1756 ** an effective call to sqlite3_shutdown() does any deinitialization.
1757 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1758 **
1759 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1760 ** is not.  The sqlite3_shutdown() interface must only be called from a
1761 ** single thread.  All open [database connections] must be closed and all
1762 ** other SQLite resources must be deallocated prior to invoking
1763 ** sqlite3_shutdown().
1764 **
1765 ** Among other things, ^sqlite3_initialize() will invoke
1766 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1767 ** will invoke sqlite3_os_end().
1768 **
1769 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1770 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1771 ** the library (perhaps it is unable to allocate a needed resource such
1772 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1773 **
1774 ** ^The sqlite3_initialize() routine is called internally by many other
1775 ** SQLite interfaces so that an application usually does not need to
1776 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1777 ** calls sqlite3_initialize() so the SQLite library will be automatically
1778 ** initialized when [sqlite3_open()] is called if it has not be initialized
1779 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1780 ** compile-time option, then the automatic calls to sqlite3_initialize()
1781 ** are omitted and the application must call sqlite3_initialize() directly
1782 ** prior to using any other SQLite interface.  For maximum portability,
1783 ** it is recommended that applications always invoke sqlite3_initialize()
1784 ** directly prior to using any other SQLite interface.  Future releases
1785 ** of SQLite may require this.  In other words, the behavior exhibited
1786 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1787 ** default behavior in some future release of SQLite.
1788 **
1789 ** The sqlite3_os_init() routine does operating-system specific
1790 ** initialization of the SQLite library.  The sqlite3_os_end()
1791 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1792 ** performed by these routines include allocation or deallocation
1793 ** of static resources, initialization of global variables,
1794 ** setting up a default [sqlite3_vfs] module, or setting up
1795 ** a default configuration using [sqlite3_config()].
1796 **
1797 ** The application should never invoke either sqlite3_os_init()
1798 ** or sqlite3_os_end() directly.  The application should only invoke
1799 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1800 ** interface is called automatically by sqlite3_initialize() and
1801 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1802 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1803 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1804 ** When [custom builds | built for other platforms]
1805 ** (using the [SQLITE_OS_OTHER=1] compile-time
1806 ** option) the application must supply a suitable implementation for
1807 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1808 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1809 ** must return [SQLITE_OK] on success and some other [error code] upon
1810 ** failure.
1811 */
1812 SQLITE_API int sqlite3_initialize(void);
1813 SQLITE_API int sqlite3_shutdown(void);
1814 SQLITE_API int sqlite3_os_init(void);
1815 SQLITE_API int sqlite3_os_end(void);
1816
1817 /*
1818 ** CAPI3REF: Configuring The SQLite Library
1819 **
1820 ** The sqlite3_config() interface is used to make global configuration
1821 ** changes to SQLite in order to tune SQLite to the specific needs of
1822 ** the application.  The default configuration is recommended for most
1823 ** applications and so this routine is usually not necessary.  It is
1824 ** provided to support rare applications with unusual needs.
1825 **
1826 ** The sqlite3_config() interface is not threadsafe.  The application
1827 ** must insure that no other SQLite interfaces are invoked by other
1828 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1829 ** may only be invoked prior to library initialization using
1830 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1831 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1832 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1833 ** Note, however, that ^sqlite3_config() can be called as part of the
1834 ** implementation of an application-defined [sqlite3_os_init()].
1835 **
1836 ** The first argument to sqlite3_config() is an integer
1837 ** [configuration option] that determines
1838 ** what property of SQLite is to be configured.  Subsequent arguments
1839 ** vary depending on the [configuration option]
1840 ** in the first argument.
1841 **
1842 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1843 ** ^If the option is unknown or SQLite is unable to set the option
1844 ** then this routine returns a non-zero [error code].
1845 */
1846 SQLITE_API int sqlite3_config(int, ...);
1847
1848 /*
1849 ** CAPI3REF: Configure database connections
1850 **
1851 ** The sqlite3_db_config() interface is used to make configuration
1852 ** changes to a [database connection].  The interface is similar to
1853 ** [sqlite3_config()] except that the changes apply to a single
1854 ** [database connection] (specified in the first argument).
1855 **
1856 ** The second argument to sqlite3_db_config(D,V,...)  is the
1857 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1858 ** that indicates what aspect of the [database connection] is being configured.
1859 ** Subsequent arguments vary depending on the configuration verb.
1860 **
1861 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1862 ** the call is considered successful.
1863 */
1864 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1865
1866 /*
1867 ** CAPI3REF: Memory Allocation Routines
1868 **
1869 ** An instance of this object defines the interface between SQLite
1870 ** and low-level memory allocation routines.
1871 **
1872 ** This object is used in only one place in the SQLite interface.
1873 ** A pointer to an instance of this object is the argument to
1874 ** [sqlite3_config()] when the configuration option is
1875 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1876 ** By creating an instance of this object
1877 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1878 ** during configuration, an application can specify an alternative
1879 ** memory allocation subsystem for SQLite to use for all of its
1880 ** dynamic memory needs.
1881 **
1882 ** Note that SQLite comes with several [built-in memory allocators]
1883 ** that are perfectly adequate for the overwhelming majority of applications
1884 ** and that this object is only useful to a tiny minority of applications
1885 ** with specialized memory allocation requirements.  This object is
1886 ** also used during testing of SQLite in order to specify an alternative
1887 ** memory allocator that simulates memory out-of-memory conditions in
1888 ** order to verify that SQLite recovers gracefully from such
1889 ** conditions.
1890 **
1891 ** The xMalloc, xRealloc, and xFree methods must work like the
1892 ** malloc(), realloc() and free() functions from the standard C library.
1893 ** ^SQLite guarantees that the second argument to
1894 ** xRealloc is always a value returned by a prior call to xRoundup.
1895 **
1896 ** xSize should return the allocated size of a memory allocation
1897 ** previously obtained from xMalloc or xRealloc.  The allocated size
1898 ** is always at least as big as the requested size but may be larger.
1899 **
1900 ** The xRoundup method returns what would be the allocated size of
1901 ** a memory allocation given a particular requested size.  Most memory
1902 ** allocators round up memory allocations at least to the next multiple
1903 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1904 ** Every memory allocation request coming in through [sqlite3_malloc()]
1905 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1906 ** that causes the corresponding memory allocation to fail.
1907 **
1908 ** The xInit method initializes the memory allocator.  (For example,
1909 ** it might allocate any require mutexes or initialize internal data
1910 ** structures.  The xShutdown method is invoked (indirectly) by
1911 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1912 ** by xInit.  The pAppData pointer is used as the only parameter to
1913 ** xInit and xShutdown.
1914 **
1915 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1916 ** the xInit method, so the xInit method need not be threadsafe.  The
1917 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1918 ** not need to be threadsafe either.  For all other methods, SQLite
1919 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1920 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1921 ** it is by default) and so the methods are automatically serialized.
1922 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1923 ** methods must be threadsafe or else make their own arrangements for
1924 ** serialization.
1925 **
1926 ** SQLite will never invoke xInit() more than once without an intervening
1927 ** call to xShutdown().
1928 */
1929 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1930 struct sqlite3_mem_methods {
1931   void *(*xMalloc)(int);         /* Memory allocation function */
1932   void (*xFree)(void*);          /* Free a prior allocation */
1933   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1934   int (*xSize)(void*);           /* Return the size of an allocation */
1935   int (*xRoundup)(int);          /* Round up request size to allocation size */
1936   int (*xInit)(void*);           /* Initialize the memory allocator */
1937   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1938   void *pAppData;                /* Argument to xInit() and xShutdown() */
1939 };
1940
1941 /*
1942 ** CAPI3REF: Configuration Options
1943 ** KEYWORDS: {configuration option}
1944 **
1945 ** These constants are the available integer configuration options that
1946 ** can be passed as the first argument to the [sqlite3_config()] interface.
1947 **
1948 ** New configuration options may be added in future releases of SQLite.
1949 ** Existing configuration options might be discontinued.  Applications
1950 ** should check the return code from [sqlite3_config()] to make sure that
1951 ** the call worked.  The [sqlite3_config()] interface will return a
1952 ** non-zero [error code] if a discontinued or unsupported configuration option
1953 ** is invoked.
1954 **
1955 ** <dl>
1956 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1957 ** <dd>There are no arguments to this option.  ^This option sets the
1958 ** [threading mode] to Single-thread.  In other words, it disables
1959 ** all mutexing and puts SQLite into a mode where it can only be used
1960 ** by a single thread.   ^If SQLite is compiled with
1961 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1962 ** it is not possible to change the [threading mode] from its default
1963 ** value of Single-thread and so [sqlite3_config()] will return
1964 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1965 ** configuration option.</dd>
1966 **
1967 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1968 ** <dd>There are no arguments to this option.  ^This option sets the
1969 ** [threading mode] to Multi-thread.  In other words, it disables
1970 ** mutexing on [database connection] and [prepared statement] objects.
1971 ** The application is responsible for serializing access to
1972 ** [database connections] and [prepared statements].  But other mutexes
1973 ** are enabled so that SQLite will be safe to use in a multi-threaded
1974 ** environment as long as no two threads attempt to use the same
1975 ** [database connection] at the same time.  ^If SQLite is compiled with
1976 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1977 ** it is not possible to set the Multi-thread [threading mode] and
1978 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1979 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1980 **
1981 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1982 ** <dd>There are no arguments to this option.  ^This option sets the
1983 ** [threading mode] to Serialized. In other words, this option enables
1984 ** all mutexes including the recursive
1985 ** mutexes on [database connection] and [prepared statement] objects.
1986 ** In this mode (which is the default when SQLite is compiled with
1987 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1988 ** to [database connections] and [prepared statements] so that the
1989 ** application is free to use the same [database connection] or the
1990 ** same [prepared statement] in different threads at the same time.
1991 ** ^If SQLite is compiled with
1992 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1993 ** it is not possible to set the Serialized [threading mode] and
1994 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1995 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1996 **
1997 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1998 ** <dd> ^(This option takes a single argument which is a pointer to an
1999 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
2000 ** alternative low-level memory allocation routines to be used in place of
2001 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
2002 ** its own private copy of the content of the [sqlite3_mem_methods] structure
2003 ** before the [sqlite3_config()] call returns.</dd>
2004 **
2005 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2006 ** <dd> ^(This option takes a single argument which is a pointer to an
2007 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
2008 ** structure is filled with the currently defined memory allocation routines.)^
2009 ** This option can be used to overload the default memory allocation
2010 ** routines with a wrapper that simulations memory allocation failure or
2011 ** tracks memory usage, for example. </dd>
2012 **
2013 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2014 ** <dd> ^This option takes single argument of type int, interpreted as a
2015 ** boolean, which enables or disables the collection of memory allocation
2016 ** statistics. ^(When memory allocation statistics are disabled, the
2017 ** following SQLite interfaces become non-operational:
2018 **   <ul>
2019 **   <li> [sqlite3_memory_used()]
2020 **   <li> [sqlite3_memory_highwater()]
2021 **   <li> [sqlite3_soft_heap_limit64()]
2022 **   <li> [sqlite3_status()]
2023 **   </ul>)^
2024 ** ^Memory allocation statistics are enabled by default unless SQLite is
2025 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2026 ** allocation statistics are disabled by default.
2027 ** </dd>
2028 **
2029 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2030 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2031 ** scratch memory.  There are three arguments:  A pointer an 8-byte
2032 ** aligned memory buffer from which the scratch allocations will be
2033 ** drawn, the size of each scratch allocation (sz),
2034 ** and the maximum number of scratch allocations (N).  The sz
2035 ** argument must be a multiple of 16.
2036 ** The first argument must be a pointer to an 8-byte aligned buffer
2037 ** of at least sz*N bytes of memory.
2038 ** ^SQLite will use no more than two scratch buffers per thread.  So
2039 ** N should be set to twice the expected maximum number of threads.
2040 ** ^SQLite will never require a scratch buffer that is more than 6
2041 ** times the database page size. ^If SQLite needs needs additional
2042 ** scratch memory beyond what is provided by this configuration option, then
2043 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
2044 **
2045 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2046 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2047 ** the database page cache with the default page cache implementation.
2048 ** This configuration should not be used if an application-define page
2049 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
2050 ** There are three arguments to this option: A pointer to 8-byte aligned
2051 ** memory, the size of each page buffer (sz), and the number of pages (N).
2052 ** The sz argument should be the size of the largest database page
2053 ** (a power of two between 512 and 32768) plus a little extra for each
2054 ** page header.  ^The page header size is 20 to 40 bytes depending on
2055 ** the host architecture.  ^It is harmless, apart from the wasted memory,
2056 ** to make sz a little too large.  The first
2057 ** argument should point to an allocation of at least sz*N bytes of memory.
2058 ** ^SQLite will use the memory provided by the first argument to satisfy its
2059 ** memory needs for the first N pages that it adds to cache.  ^If additional
2060 ** page cache memory is needed beyond what is provided by this option, then
2061 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2062 ** The pointer in the first argument must
2063 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2064 ** will be undefined.</dd>
2065 **
2066 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2067 ** <dd> ^This option specifies a static memory buffer that SQLite will use
2068 ** for all of its dynamic memory allocation needs beyond those provided
2069 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2070 ** There are three arguments: An 8-byte aligned pointer to the memory,
2071 ** the number of bytes in the memory buffer, and the minimum allocation size.
2072 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2073 ** to using its default memory allocator (the system malloc() implementation),
2074 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2075 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2076 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2077 ** allocator is engaged to handle all of SQLites memory allocation needs.
2078 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2079 ** boundary or subsequent behavior of SQLite will be undefined.
2080 ** The minimum allocation size is capped at 2**12. Reasonable values
2081 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2082 **
2083 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2084 ** <dd> ^(This option takes a single argument which is a pointer to an
2085 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2086 ** alternative low-level mutex routines to be used in place
2087 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2088 ** content of the [sqlite3_mutex_methods] structure before the call to
2089 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2090 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2091 ** the entire mutexing subsystem is omitted from the build and hence calls to
2092 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2093 ** return [SQLITE_ERROR].</dd>
2094 **
2095 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2096 ** <dd> ^(This option takes a single argument which is a pointer to an
2097 ** instance of the [sqlite3_mutex_methods] structure.  The
2098 ** [sqlite3_mutex_methods]
2099 ** structure is filled with the currently defined mutex routines.)^
2100 ** This option can be used to overload the default mutex allocation
2101 ** routines with a wrapper used to track mutex usage for performance
2102 ** profiling or testing, for example.   ^If SQLite is compiled with
2103 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2104 ** the entire mutexing subsystem is omitted from the build and hence calls to
2105 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2106 ** return [SQLITE_ERROR].</dd>
2107 **
2108 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2109 ** <dd> ^(This option takes two arguments that determine the default
2110 ** memory allocation for the lookaside memory allocator on each
2111 ** [database connection].  The first argument is the
2112 ** size of each lookaside buffer slot and the second is the number of
2113 ** slots allocated to each database connection.)^  ^(This option sets the
2114 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2115 ** verb to [sqlite3_db_config()] can be used to change the lookaside
2116 ** configuration on individual connections.)^ </dd>
2117 **
2118 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2119 ** <dd> ^(This option takes a single argument which is a pointer to
2120 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2121 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2122 ** object and uses it for page cache memory allocations.</dd>
2123 **
2124 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2125 ** <dd> ^(This option takes a single argument which is a pointer to an
2126 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2127 ** page cache implementation into that object.)^ </dd>
2128 **
2129 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2130 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2131 ** function with a call signature of void(*)(void*,int,const char*),
2132 ** and a pointer to void. ^If the function pointer is not NULL, it is
2133 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
2134 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2135 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2136 ** passed through as the first parameter to the application-defined logger
2137 ** function whenever that function is invoked.  ^The second parameter to
2138 ** the logger function is a copy of the first parameter to the corresponding
2139 ** [sqlite3_log()] call and is intended to be a [result code] or an
2140 ** [extended result code].  ^The third parameter passed to the logger is
2141 ** log message after formatting via [sqlite3_snprintf()].
2142 ** The SQLite logging interface is not reentrant; the logger function
2143 ** supplied by the application must not invoke any SQLite interface.
2144 ** In a multi-threaded application, the application-defined logger
2145 ** function must be threadsafe. </dd>
2146 **
2147 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2148 ** <dd> This option takes a single argument of type int. If non-zero, then
2149 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2150 ** is globally disabled. If URI handling is globally enabled, all filenames
2151 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2152 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2153 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2154 ** connection is opened. If it is globally disabled, filenames are
2155 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2156 ** database connection is opened. By default, URI handling is globally
2157 ** disabled. The default value may be changed by compiling with the
2158 ** [SQLITE_USE_URI] symbol defined.
2159 **
2160 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2161 ** <dd> This option takes a single integer argument which is interpreted as
2162 ** a boolean in order to enable or disable the use of covering indices for
2163 ** full table scans in the query optimizer.  The default setting is determined
2164 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2165 ** if that compile-time option is omitted.
2166 ** The ability to disable the use of covering indices for full table scans
2167 ** is because some incorrectly coded legacy applications might malfunction
2168 ** malfunction when the optimization is enabled.  Providing the ability to
2169 ** disable the optimization allows the older, buggy application code to work
2170 ** without change even with newer versions of SQLite.
2171 **
2172 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2173 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2174 ** <dd> These options are obsolete and should not be used by new code.
2175 ** They are retained for backwards compatibility but are now no-ops.
2176 ** </dl>
2177 **
2178 ** [[SQLITE_CONFIG_SQLLOG]]
2179 ** <dt>SQLITE_CONFIG_SQLLOG
2180 ** <dd>This option is only available if sqlite is compiled with the
2181 ** SQLITE_ENABLE_SQLLOG pre-processor macro defined. The first argument should
2182 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2183 ** The second should be of type (void*). The callback is invoked by the library
2184 ** in three separate circumstances, identified by the value passed as the
2185 ** fourth parameter. If the fourth parameter is 0, then the database connection
2186 ** passed as the second argument has just been opened. The third argument
2187 ** points to a buffer containing the name of the main database file. If the
2188 ** fourth parameter is 1, then the SQL statement that the third parameter
2189 ** points to has just been executed. Or, if the fourth parameter is 2, then
2190 ** the connection being passed as the second parameter is being closed. The
2191 ** third parameter is passed NULL In this case.
2192 ** </dl>
2193 */
2194 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2195 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2196 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2197 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2198 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2199 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2200 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2201 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2202 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2203 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2204 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2205 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2206 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2207 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2208 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2209 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2210 #define SQLITE_CONFIG_URI          17  /* int */
2211 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2212 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2213 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2214 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2215
2216 /*
2217 ** CAPI3REF: Database Connection Configuration Options
2218 **
2219 ** These constants are the available integer configuration options that
2220 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2221 **
2222 ** New configuration options may be added in future releases of SQLite.
2223 ** Existing configuration options might be discontinued.  Applications
2224 ** should check the return code from [sqlite3_db_config()] to make sure that
2225 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2226 ** non-zero [error code] if a discontinued or unsupported configuration option
2227 ** is invoked.
2228 **
2229 ** <dl>
2230 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2231 ** <dd> ^This option takes three additional arguments that determine the
2232 ** [lookaside memory allocator] configuration for the [database connection].
2233 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2234 ** pointer to a memory buffer to use for lookaside memory.
2235 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2236 ** may be NULL in which case SQLite will allocate the
2237 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2238 ** size of each lookaside buffer slot.  ^The third argument is the number of
2239 ** slots.  The size of the buffer in the first argument must be greater than
2240 ** or equal to the product of the second and third arguments.  The buffer
2241 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2242 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2243 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2244 ** configuration for a database connection can only be changed when that
2245 ** connection is not currently using lookaside memory, or in other words
2246 ** when the "current value" returned by
2247 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2248 ** Any attempt to change the lookaside memory configuration when lookaside
2249 ** memory is in use leaves the configuration unchanged and returns
2250 ** [SQLITE_BUSY].)^</dd>
2251 **
2252 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2253 ** <dd> ^This option is used to enable or disable the enforcement of
2254 ** [foreign key constraints].  There should be two additional arguments.
2255 ** The first argument is an integer which is 0 to disable FK enforcement,
2256 ** positive to enable FK enforcement or negative to leave FK enforcement
2257 ** unchanged.  The second parameter is a pointer to an integer into which
2258 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2259 ** following this call.  The second parameter may be a NULL pointer, in
2260 ** which case the FK enforcement setting is not reported back. </dd>
2261 **
2262 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2263 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2264 ** There should be two additional arguments.
2265 ** The first argument is an integer which is 0 to disable triggers,
2266 ** positive to enable triggers or negative to leave the setting unchanged.
2267 ** The second parameter is a pointer to an integer into which
2268 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2269 ** following this call.  The second parameter may be a NULL pointer, in
2270 ** which case the trigger setting is not reported back. </dd>
2271 **
2272 ** </dl>
2273 */
2274 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2275 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2276 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2277
2278
2279 /*
2280 ** CAPI3REF: Enable Or Disable Extended Result Codes
2281 **
2282 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2283 ** [extended result codes] feature of SQLite. ^The extended result
2284 ** codes are disabled by default for historical compatibility.
2285 */
2286 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2287
2288 /*
2289 ** CAPI3REF: Last Insert Rowid
2290 **
2291 ** ^Each entry in an SQLite table has a unique 64-bit signed
2292 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2293 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2294 ** names are not also used by explicitly declared columns. ^If
2295 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2296 ** is another alias for the rowid.
2297 **
2298 ** ^This routine returns the [rowid] of the most recent
2299 ** successful [INSERT] into the database from the [database connection]
2300 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2301 ** records the last insert rowid of both ordinary tables and [virtual tables].
2302 ** ^If no successful [INSERT]s
2303 ** have ever occurred on that database connection, zero is returned.
2304 **
2305 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2306 ** method, then this routine will return the [rowid] of the inserted
2307 ** row as long as the trigger or virtual table method is running.
2308 ** But once the trigger or virtual table method ends, the value returned
2309 ** by this routine reverts to what it was before the trigger or virtual
2310 ** table method began.)^
2311 **
2312 ** ^An [INSERT] that fails due to a constraint violation is not a
2313 ** successful [INSERT] and does not change the value returned by this
2314 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2315 ** and INSERT OR ABORT make no changes to the return value of this
2316 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2317 ** encounters a constraint violation, it does not fail.  The
2318 ** INSERT continues to completion after deleting rows that caused
2319 ** the constraint problem so INSERT OR REPLACE will always change
2320 ** the return value of this interface.)^
2321 **
2322 ** ^For the purposes of this routine, an [INSERT] is considered to
2323 ** be successful even if it is subsequently rolled back.
2324 **
2325 ** This function is accessible to SQL statements via the
2326 ** [last_insert_rowid() SQL function].
2327 **
2328 ** If a separate thread performs a new [INSERT] on the same
2329 ** database connection while the [sqlite3_last_insert_rowid()]
2330 ** function is running and thus changes the last insert [rowid],
2331 ** then the value returned by [sqlite3_last_insert_rowid()] is
2332 ** unpredictable and might not equal either the old or the new
2333 ** last insert [rowid].
2334 */
2335 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2336
2337 /*
2338 ** CAPI3REF: Count The Number Of Rows Modified
2339 **
2340 ** ^This function returns the number of database rows that were changed
2341 ** or inserted or deleted by the most recently completed SQL statement
2342 ** on the [database connection] specified by the first parameter.
2343 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2344 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2345 ** triggers or [foreign key actions] are not counted.)^ Use the
2346 ** [sqlite3_total_changes()] function to find the total number of changes
2347 ** including changes caused by triggers and foreign key actions.
2348 **
2349 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2350 ** are not counted.  Only real table changes are counted.
2351 **
2352 ** ^(A "row change" is a change to a single row of a single table
2353 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2354 ** are changed as side effects of [REPLACE] constraint resolution,
2355 ** rollback, ABORT processing, [DROP TABLE], or by any other
2356 ** mechanisms do not count as direct row changes.)^
2357 **
2358 ** A "trigger context" is a scope of execution that begins and
2359 ** ends with the script of a [CREATE TRIGGER | trigger].
2360 ** Most SQL statements are
2361 ** evaluated outside of any trigger.  This is the "top level"
2362 ** trigger context.  If a trigger fires from the top level, a
2363 ** new trigger context is entered for the duration of that one
2364 ** trigger.  Subtriggers create subcontexts for their duration.
2365 **
2366 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2367 ** not create a new trigger context.
2368 **
2369 ** ^This function returns the number of direct row changes in the
2370 ** most recent INSERT, UPDATE, or DELETE statement within the same
2371 ** trigger context.
2372 **
2373 ** ^Thus, when called from the top level, this function returns the
2374 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2375 ** that also occurred at the top level.  ^(Within the body of a trigger,
2376 ** the sqlite3_changes() interface can be called to find the number of
2377 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2378 ** statement within the body of the same trigger.
2379 ** However, the number returned does not include changes
2380 ** caused by subtriggers since those have their own context.)^
2381 **
2382 ** See also the [sqlite3_total_changes()] interface, the
2383 ** [count_changes pragma], and the [changes() SQL function].
2384 **
2385 ** If a separate thread makes changes on the same database connection
2386 ** while [sqlite3_changes()] is running then the value returned
2387 ** is unpredictable and not meaningful.
2388 */
2389 SQLITE_API int sqlite3_changes(sqlite3*);
2390
2391 /*
2392 ** CAPI3REF: Total Number Of Rows Modified
2393 **
2394 ** ^This function returns the number of row changes caused by [INSERT],
2395 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2396 ** ^(The count returned by sqlite3_total_changes() includes all changes
2397 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2398 ** [foreign key actions]. However,
2399 ** the count does not include changes used to implement [REPLACE] constraints,
2400 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2401 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2402 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2403 ** are counted.)^
2404 ** ^The sqlite3_total_changes() function counts the changes as soon as
2405 ** the statement that makes them is completed (when the statement handle
2406 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2407 **
2408 ** See also the [sqlite3_changes()] interface, the
2409 ** [count_changes pragma], and the [total_changes() SQL function].
2410 **
2411 ** If a separate thread makes changes on the same database connection
2412 ** while [sqlite3_total_changes()] is running then the value
2413 ** returned is unpredictable and not meaningful.
2414 */
2415 SQLITE_API int sqlite3_total_changes(sqlite3*);
2416
2417 /*
2418 ** CAPI3REF: Interrupt A Long-Running Query
2419 **
2420 ** ^This function causes any pending database operation to abort and
2421 ** return at its earliest opportunity. This routine is typically
2422 ** called in response to a user action such as pressing "Cancel"
2423 ** or Ctrl-C where the user wants a long query operation to halt
2424 ** immediately.
2425 **
2426 ** ^It is safe to call this routine from a thread different from the
2427 ** thread that is currently running the database operation.  But it
2428 ** is not safe to call this routine with a [database connection] that
2429 ** is closed or might close before sqlite3_interrupt() returns.
2430 **
2431 ** ^If an SQL operation is very nearly finished at the time when
2432 ** sqlite3_interrupt() is called, then it might not have an opportunity
2433 ** to be interrupted and might continue to completion.
2434 **
2435 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2436 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2437 ** that is inside an explicit transaction, then the entire transaction
2438 ** will be rolled back automatically.
2439 **
2440 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2441 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2442 ** that are started after the sqlite3_interrupt() call and before the
2443 ** running statements reaches zero are interrupted as if they had been
2444 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2445 ** that are started after the running statement count reaches zero are
2446 ** not effected by the sqlite3_interrupt().
2447 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2448 ** SQL statements is a no-op and has no effect on SQL statements
2449 ** that are started after the sqlite3_interrupt() call returns.
2450 **
2451 ** If the database connection closes while [sqlite3_interrupt()]
2452 ** is running then bad things will likely happen.
2453 */
2454 SQLITE_API void sqlite3_interrupt(sqlite3*);
2455
2456 /*
2457 ** CAPI3REF: Determine If An SQL Statement Is Complete
2458 **
2459 ** These routines are useful during command-line input to determine if the
2460 ** currently entered text seems to form a complete SQL statement or
2461 ** if additional input is needed before sending the text into
2462 ** SQLite for parsing.  ^These routines return 1 if the input string
2463 ** appears to be a complete SQL statement.  ^A statement is judged to be
2464 ** complete if it ends with a semicolon token and is not a prefix of a
2465 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2466 ** string literals or quoted identifier names or comments are not
2467 ** independent tokens (they are part of the token in which they are
2468 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2469 ** and comments that follow the final semicolon are ignored.
2470 **
2471 ** ^These routines return 0 if the statement is incomplete.  ^If a
2472 ** memory allocation fails, then SQLITE_NOMEM is returned.
2473 **
2474 ** ^These routines do not parse the SQL statements thus
2475 ** will not detect syntactically incorrect SQL.
2476 **
2477 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2478 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2479 ** automatically by sqlite3_complete16().  If that initialization fails,
2480 ** then the return value from sqlite3_complete16() will be non-zero
2481 ** regardless of whether or not the input SQL is complete.)^
2482 **
2483 ** The input to [sqlite3_complete()] must be a zero-terminated
2484 ** UTF-8 string.
2485 **
2486 ** The input to [sqlite3_complete16()] must be a zero-terminated
2487 ** UTF-16 string in native byte order.
2488 */
2489 SQLITE_API int sqlite3_complete(const char *sql);
2490 SQLITE_API int sqlite3_complete16(const void *sql);
2491
2492 /*
2493 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2494 **
2495 ** ^This routine sets a callback function that might be invoked whenever
2496 ** an attempt is made to open a database table that another thread
2497 ** or process has locked.
2498 **
2499 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2500 ** is returned immediately upon encountering the lock.  ^If the busy callback
2501 ** is not NULL, then the callback might be invoked with two arguments.
2502 **
2503 ** ^The first argument to the busy handler is a copy of the void* pointer which
2504 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2505 ** the busy handler callback is the number of times that the busy handler has
2506 ** been invoked for this locking event.  ^If the
2507 ** busy callback returns 0, then no additional attempts are made to
2508 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2509 ** ^If the callback returns non-zero, then another attempt
2510 ** is made to open the database for reading and the cycle repeats.
2511 **
2512 ** The presence of a busy handler does not guarantee that it will be invoked
2513 ** when there is lock contention. ^If SQLite determines that invoking the busy
2514 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2515 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2516 ** Consider a scenario where one process is holding a read lock that
2517 ** it is trying to promote to a reserved lock and
2518 ** a second process is holding a reserved lock that it is trying
2519 ** to promote to an exclusive lock.  The first process cannot proceed
2520 ** because it is blocked by the second and the second process cannot
2521 ** proceed because it is blocked by the first.  If both processes
2522 ** invoke the busy handlers, neither will make any progress.  Therefore,
2523 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2524 ** will induce the first process to release its read lock and allow
2525 ** the second process to proceed.
2526 **
2527 ** ^The default busy callback is NULL.
2528 **
2529 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2530 ** when SQLite is in the middle of a large transaction where all the
2531 ** changes will not fit into the in-memory cache.  SQLite will
2532 ** already hold a RESERVED lock on the database file, but it needs
2533 ** to promote this lock to EXCLUSIVE so that it can spill cache
2534 ** pages into the database file without harm to concurrent
2535 ** readers.  ^If it is unable to promote the lock, then the in-memory
2536 ** cache will be left in an inconsistent state and so the error
2537 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2538 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2539 ** forces an automatic rollback of the changes.  See the
2540 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2541 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2542 ** this is important.
2543 **
2544 ** ^(There can only be a single busy handler defined for each
2545 ** [database connection].  Setting a new busy handler clears any
2546 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2547 ** will also set or clear the busy handler.
2548 **
2549 ** The busy callback should not take any actions which modify the
2550 ** database connection that invoked the busy handler.  Any such actions
2551 ** result in undefined behavior.
2552 **
2553 ** A busy handler must not close the database connection
2554 ** or [prepared statement] that invoked the busy handler.
2555 */
2556 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2557
2558 /*
2559 ** CAPI3REF: Set A Busy Timeout
2560 **
2561 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2562 ** for a specified amount of time when a table is locked.  ^The handler
2563 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2564 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2565 ** the handler returns 0 which causes [sqlite3_step()] to return
2566 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2567 **
2568 ** ^Calling this routine with an argument less than or equal to zero
2569 ** turns off all busy handlers.
2570 **
2571 ** ^(There can only be a single busy handler for a particular
2572 ** [database connection] any any given moment.  If another busy handler
2573 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2574 ** this routine, that other busy handler is cleared.)^
2575 */
2576 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2577
2578 /*
2579 ** CAPI3REF: Convenience Routines For Running Queries
2580 **
2581 ** This is a legacy interface that is preserved for backwards compatibility.
2582 ** Use of this interface is not recommended.
2583 **
2584 ** Definition: A <b>result table</b> is memory data structure created by the
2585 ** [sqlite3_get_table()] interface.  A result table records the
2586 ** complete query results from one or more queries.
2587 **
2588 ** The table conceptually has a number of rows and columns.  But
2589 ** these numbers are not part of the result table itself.  These
2590 ** numbers are obtained separately.  Let N be the number of rows
2591 ** and M be the number of columns.
2592 **
2593 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2594 ** There are (N+1)*M elements in the array.  The first M pointers point
2595 ** to zero-terminated strings that  contain the names of the columns.
2596 ** The remaining entries all point to query results.  NULL values result
2597 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2598 ** string representation as returned by [sqlite3_column_text()].
2599 **
2600 ** A result table might consist of one or more memory allocations.
2601 ** It is not safe to pass a result table directly to [sqlite3_free()].
2602 ** A result table should be deallocated using [sqlite3_free_table()].
2603 **
2604 ** ^(As an example of the result table format, suppose a query result
2605 ** is as follows:
2606 **
2607 ** <blockquote><pre>
2608 **        Name        | Age
2609 **        -----------------------
2610 **        Alice       | 43
2611 **        Bob         | 28
2612 **        Cindy       | 21
2613 ** </pre></blockquote>
2614 **
2615 ** There are two column (M==2) and three rows (N==3).  Thus the
2616 ** result table has 8 entries.  Suppose the result table is stored
2617 ** in an array names azResult.  Then azResult holds this content:
2618 **
2619 ** <blockquote><pre>
2620 **        azResult&#91;0] = "Name";
2621 **        azResult&#91;1] = "Age";
2622 **        azResult&#91;2] = "Alice";
2623 **        azResult&#91;3] = "43";
2624 **        azResult&#91;4] = "Bob";
2625 **        azResult&#91;5] = "28";
2626 **        azResult&#91;6] = "Cindy";
2627 **        azResult&#91;7] = "21";
2628 ** </pre></blockquote>)^
2629 **
2630 ** ^The sqlite3_get_table() function evaluates one or more
2631 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2632 ** string of its 2nd parameter and returns a result table to the
2633 ** pointer given in its 3rd parameter.
2634 **
2635 ** After the application has finished with the result from sqlite3_get_table(),
2636 ** it must pass the result table pointer to sqlite3_free_table() in order to
2637 ** release the memory that was malloced.  Because of the way the
2638 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2639 ** function must not try to call [sqlite3_free()] directly.  Only
2640 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2641 **
2642 ** The sqlite3_get_table() interface is implemented as a wrapper around
2643 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2644 ** to any internal data structures of SQLite.  It uses only the public
2645 ** interface defined here.  As a consequence, errors that occur in the
2646 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2647 ** reflected in subsequent calls to [sqlite3_errcode()] or
2648 ** [sqlite3_errmsg()].
2649 */
2650 SQLITE_API int sqlite3_get_table(
2651   sqlite3 *db,          /* An open database */
2652   const char *zSql,     /* SQL to be evaluated */
2653   char ***pazResult,    /* Results of the query */
2654   int *pnRow,           /* Number of result rows written here */
2655   int *pnColumn,        /* Number of result columns written here */
2656   char **pzErrmsg       /* Error msg written here */
2657 );
2658 SQLITE_API void sqlite3_free_table(char **result);
2659
2660 /*
2661 ** CAPI3REF: Formatted String Printing Functions
2662 **
2663 ** These routines are work-alikes of the "printf()" family of functions
2664 ** from the standard C library.
2665 **
2666 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2667 ** results into memory obtained from [sqlite3_malloc()].
2668 ** The strings returned by these two routines should be
2669 ** released by [sqlite3_free()].  ^Both routines return a
2670 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2671 ** memory to hold the resulting string.
2672 **
2673 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2674 ** the standard C library.  The result is written into the
2675 ** buffer supplied as the second parameter whose size is given by
2676 ** the first parameter. Note that the order of the
2677 ** first two parameters is reversed from snprintf().)^  This is an
2678 ** historical accident that cannot be fixed without breaking
2679 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2680 ** returns a pointer to its buffer instead of the number of
2681 ** characters actually written into the buffer.)^  We admit that
2682 ** the number of characters written would be a more useful return
2683 ** value but we cannot change the implementation of sqlite3_snprintf()
2684 ** now without breaking compatibility.
2685 **
2686 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2687 ** guarantees that the buffer is always zero-terminated.  ^The first
2688 ** parameter "n" is the total size of the buffer, including space for
2689 ** the zero terminator.  So the longest string that can be completely
2690 ** written will be n-1 characters.
2691 **
2692 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2693 **
2694 ** These routines all implement some additional formatting
2695 ** options that are useful for constructing SQL statements.
2696 ** All of the usual printf() formatting options apply.  In addition, there
2697 ** is are "%q", "%Q", and "%z" options.
2698 **
2699 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2700 ** string from the argument list.  But %q also doubles every '\'' character.
2701 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2702 ** character it escapes that character and allows it to be inserted into
2703 ** the string.
2704 **
2705 ** For example, assume the string variable zText contains text as follows:
2706 **
2707 ** <blockquote><pre>
2708 **  char *zText = "It's a happy day!";
2709 ** </pre></blockquote>
2710 **
2711 ** One can use this text in an SQL statement as follows:
2712 **
2713 ** <blockquote><pre>
2714 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2715 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2716 **  sqlite3_free(zSQL);
2717 ** </pre></blockquote>
2718 **
2719 ** Because the %q format string is used, the '\'' character in zText
2720 ** is escaped and the SQL generated is as follows:
2721 **
2722 ** <blockquote><pre>
2723 **  INSERT INTO table1 VALUES('It''s a happy day!')
2724 ** </pre></blockquote>
2725 **
2726 ** This is correct.  Had we used %s instead of %q, the generated SQL
2727 ** would have looked like this:
2728 **
2729 ** <blockquote><pre>
2730 **  INSERT INTO table1 VALUES('It's a happy day!');
2731 ** </pre></blockquote>
2732 **
2733 ** This second example is an SQL syntax error.  As a general rule you should
2734 ** always use %q instead of %s when inserting text into a string literal.
2735 **
2736 ** ^(The %Q option works like %q except it also adds single quotes around
2737 ** the outside of the total string.  Additionally, if the parameter in the
2738 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2739 ** single quotes).)^  So, for example, one could say:
2740 **
2741 ** <blockquote><pre>
2742 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2743 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2744 **  sqlite3_free(zSQL);
2745 ** </pre></blockquote>
2746 **
2747 ** The code above will render a correct SQL statement in the zSQL
2748 ** variable even if the zText variable is a NULL pointer.
2749 **
2750 ** ^(The "%z" formatting option works like "%s" but with the
2751 ** addition that after the string has been read and copied into
2752 ** the result, [sqlite3_free()] is called on the input string.)^
2753 */
2754 SQLITE_API char *sqlite3_mprintf(const char*,...);
2755 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2756 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2757 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2758
2759 /*
2760 ** CAPI3REF: Memory Allocation Subsystem
2761 **
2762 ** The SQLite core uses these three routines for all of its own
2763 ** internal memory allocation needs. "Core" in the previous sentence
2764 ** does not include operating-system specific VFS implementation.  The
2765 ** Windows VFS uses native malloc() and free() for some operations.
2766 **
2767 ** ^The sqlite3_malloc() routine returns a pointer to a block
2768 ** of memory at least N bytes in length, where N is the parameter.
2769 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2770 ** memory, it returns a NULL pointer.  ^If the parameter N to
2771 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2772 ** a NULL pointer.
2773 **
2774 ** ^Calling sqlite3_free() with a pointer previously returned
2775 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2776 ** that it might be reused.  ^The sqlite3_free() routine is
2777 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2778 ** to sqlite3_free() is harmless.  After being freed, memory
2779 ** should neither be read nor written.  Even reading previously freed
2780 ** memory might result in a segmentation fault or other severe error.
2781 ** Memory corruption, a segmentation fault, or other severe error
2782 ** might result if sqlite3_free() is called with a non-NULL pointer that
2783 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2784 **
2785 ** ^(The sqlite3_realloc() interface attempts to resize a
2786 ** prior memory allocation to be at least N bytes, where N is the
2787 ** second parameter.  The memory allocation to be resized is the first
2788 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2789 ** is a NULL pointer then its behavior is identical to calling
2790 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2791 ** ^If the second parameter to sqlite3_realloc() is zero or
2792 ** negative then the behavior is exactly the same as calling
2793 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2794 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2795 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2796 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2797 ** of the prior allocation are copied into the beginning of buffer returned
2798 ** by sqlite3_realloc() and the prior allocation is freed.
2799 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2800 ** is not freed.
2801 **
2802 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2803 ** is always aligned to at least an 8 byte boundary, or to a
2804 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2805 ** option is used.
2806 **
2807 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2808 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2809 ** implementation of these routines to be omitted.  That capability
2810 ** is no longer provided.  Only built-in memory allocators can be used.
2811 **
2812 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2813 ** the system malloc() and free() directly when converting
2814 ** filenames between the UTF-8 encoding used by SQLite
2815 ** and whatever filename encoding is used by the particular Windows
2816 ** installation.  Memory allocation errors were detected, but
2817 ** they were reported back as [SQLITE_CANTOPEN] or
2818 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2819 **
2820 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2821 ** must be either NULL or else pointers obtained from a prior
2822 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2823 ** not yet been released.
2824 **
2825 ** The application must not read or write any part of
2826 ** a block of memory after it has been released using
2827 ** [sqlite3_free()] or [sqlite3_realloc()].
2828 */
2829 SQLITE_API void *sqlite3_malloc(int);
2830 SQLITE_API void *sqlite3_realloc(void*, int);
2831 SQLITE_API void sqlite3_free(void*);
2832
2833 /*
2834 ** CAPI3REF: Memory Allocator Statistics
2835 **
2836 ** SQLite provides these two interfaces for reporting on the status
2837 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2838 ** routines, which form the built-in memory allocation subsystem.
2839 **
2840 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2841 ** of memory currently outstanding (malloced but not freed).
2842 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2843 ** value of [sqlite3_memory_used()] since the high-water mark
2844 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2845 ** [sqlite3_memory_highwater()] include any overhead
2846 ** added by SQLite in its implementation of [sqlite3_malloc()],
2847 ** but not overhead added by the any underlying system library
2848 ** routines that [sqlite3_malloc()] may call.
2849 **
2850 ** ^The memory high-water mark is reset to the current value of
2851 ** [sqlite3_memory_used()] if and only if the parameter to
2852 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2853 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2854 ** prior to the reset.
2855 */
2856 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2857 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2858
2859 /*
2860 ** CAPI3REF: Pseudo-Random Number Generator
2861 **
2862 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2863 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2864 ** already uses the largest possible [ROWID].  The PRNG is also used for
2865 ** the build-in random() and randomblob() SQL functions.  This interface allows
2866 ** applications to access the same PRNG for other purposes.
2867 **
2868 ** ^A call to this routine stores N bytes of randomness into buffer P.
2869 **
2870 ** ^The first time this routine is invoked (either internally or by
2871 ** the application) the PRNG is seeded using randomness obtained
2872 ** from the xRandomness method of the default [sqlite3_vfs] object.
2873 ** ^On all subsequent invocations, the pseudo-randomness is generated
2874 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2875 ** method.
2876 */
2877 SQLITE_API void sqlite3_randomness(int N, void *P);
2878
2879 /*
2880 ** CAPI3REF: Compile-Time Authorization Callbacks
2881 **
2882 ** ^This routine registers an authorizer callback with a particular
2883 ** [database connection], supplied in the first argument.
2884 ** ^The authorizer callback is invoked as SQL statements are being compiled
2885 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2886 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2887 ** points during the compilation process, as logic is being created
2888 ** to perform various actions, the authorizer callback is invoked to
2889 ** see if those actions are allowed.  ^The authorizer callback should
2890 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2891 ** specific action but allow the SQL statement to continue to be
2892 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2893 ** rejected with an error.  ^If the authorizer callback returns
2894 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2895 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2896 ** the authorizer will fail with an error message.
2897 **
2898 ** When the callback returns [SQLITE_OK], that means the operation
2899 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2900 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2901 ** authorizer will fail with an error message explaining that
2902 ** access is denied.
2903 **
2904 ** ^The first parameter to the authorizer callback is a copy of the third
2905 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2906 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2907 ** the particular action to be authorized. ^The third through sixth parameters
2908 ** to the callback are zero-terminated strings that contain additional
2909 ** details about the action to be authorized.
2910 **
2911 ** ^If the action code is [SQLITE_READ]
2912 ** and the callback returns [SQLITE_IGNORE] then the
2913 ** [prepared statement] statement is constructed to substitute
2914 ** a NULL value in place of the table column that would have
2915 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2916 ** return can be used to deny an untrusted user access to individual
2917 ** columns of a table.
2918 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2919 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2920 ** [truncate optimization] is disabled and all rows are deleted individually.
2921 **
2922 ** An authorizer is used when [sqlite3_prepare | preparing]
2923 ** SQL statements from an untrusted source, to ensure that the SQL statements
2924 ** do not try to access data they are not allowed to see, or that they do not
2925 ** try to execute malicious statements that damage the database.  For
2926 ** example, an application may allow a user to enter arbitrary
2927 ** SQL queries for evaluation by a database.  But the application does
2928 ** not want the user to be able to make arbitrary changes to the
2929 ** database.  An authorizer could then be put in place while the
2930 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2931 ** disallows everything except [SELECT] statements.
2932 **
2933 ** Applications that need to process SQL from untrusted sources
2934 ** might also consider lowering resource limits using [sqlite3_limit()]
2935 ** and limiting database size using the [max_page_count] [PRAGMA]
2936 ** in addition to using an authorizer.
2937 **
2938 ** ^(Only a single authorizer can be in place on a database connection
2939 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2940 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2941 ** The authorizer is disabled by default.
2942 **
2943 ** The authorizer callback must not do anything that will modify
2944 ** the database connection that invoked the authorizer callback.
2945 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2946 ** database connections for the meaning of "modify" in this paragraph.
2947 **
2948 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2949 ** statement might be re-prepared during [sqlite3_step()] due to a
2950 ** schema change.  Hence, the application should ensure that the
2951 ** correct authorizer callback remains in place during the [sqlite3_step()].
2952 **
2953 ** ^Note that the authorizer callback is invoked only during
2954 ** [sqlite3_prepare()] or its variants.  Authorization is not
2955 ** performed during statement evaluation in [sqlite3_step()], unless
2956 ** as stated in the previous paragraph, sqlite3_step() invokes
2957 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2958 */
2959 SQLITE_API int sqlite3_set_authorizer(
2960   sqlite3*,
2961   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2962   void *pUserData
2963 );
2964
2965 /*
2966 ** CAPI3REF: Authorizer Return Codes
2967 **
2968 ** The [sqlite3_set_authorizer | authorizer callback function] must
2969 ** return either [SQLITE_OK] or one of these two constants in order
2970 ** to signal SQLite whether or not the action is permitted.  See the
2971 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2972 ** information.
2973 **
2974 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2975 ** from the [sqlite3_vtab_on_conflict()] interface.
2976 */
2977 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2978 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2979
2980 /*
2981 ** CAPI3REF: Authorizer Action Codes
2982 **
2983 ** The [sqlite3_set_authorizer()] interface registers a callback function
2984 ** that is invoked to authorize certain SQL statement actions.  The
2985 ** second parameter to the callback is an integer code that specifies
2986 ** what action is being authorized.  These are the integer action codes that
2987 ** the authorizer callback may be passed.
2988 **
2989 ** These action code values signify what kind of operation is to be
2990 ** authorized.  The 3rd and 4th parameters to the authorization
2991 ** callback function will be parameters or NULL depending on which of these
2992 ** codes is used as the second parameter.  ^(The 5th parameter to the
2993 ** authorizer callback is the name of the database ("main", "temp",
2994 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2995 ** is the name of the inner-most trigger or view that is responsible for
2996 ** the access attempt or NULL if this access attempt is directly from
2997 ** top-level SQL code.
2998 */
2999 /******************************************* 3rd ************ 4th ***********/
3000 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3001 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3002 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3003 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3004 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3005 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3006 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3007 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3008 #define SQLITE_DELETE                9   /* Table Name      NULL            */
3009 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3010 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3011 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3012 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3013 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3014 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3015 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3016 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3017 #define SQLITE_INSERT               18   /* Table Name      NULL            */
3018 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3019 #define SQLITE_READ                 20   /* Table Name      Column Name     */
3020 #define SQLITE_SELECT               21   /* NULL            NULL            */
3021 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3022 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3023 #define SQLITE_ATTACH               24   /* Filename        NULL            */
3024 #define SQLITE_DETACH               25   /* Database Name   NULL            */
3025 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3026 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
3027 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3028 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3029 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3030 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3031 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3032 #define SQLITE_COPY                  0   /* No longer used */
3033
3034 /*
3035 ** CAPI3REF: Tracing And Profiling Functions
3036 **
3037 ** These routines register callback functions that can be used for
3038 ** tracing and profiling the execution of SQL statements.
3039 **
3040 ** ^The callback function registered by sqlite3_trace() is invoked at
3041 ** various times when an SQL statement is being run by [sqlite3_step()].
3042 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3043 ** SQL statement text as the statement first begins executing.
3044 ** ^(Additional sqlite3_trace() callbacks might occur
3045 ** as each triggered subprogram is entered.  The callbacks for triggers
3046 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3047 **
3048 ** ^The callback function registered by sqlite3_profile() is invoked
3049 ** as each SQL statement finishes.  ^The profile callback contains
3050 ** the original statement text and an estimate of wall-clock time
3051 ** of how long that statement took to run.  ^The profile callback
3052 ** time is in units of nanoseconds, however the current implementation
3053 ** is only capable of millisecond resolution so the six least significant
3054 ** digits in the time are meaningless.  Future versions of SQLite
3055 ** might provide greater resolution on the profiler callback.  The
3056 ** sqlite3_profile() function is considered experimental and is
3057 ** subject to change in future versions of SQLite.
3058 */
3059 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3060 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
3061    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3062
3063 /*
3064 ** CAPI3REF: Query Progress Callbacks
3065 **
3066 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3067 ** function X to be invoked periodically during long running calls to
3068 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3069 ** database connection D.  An example use for this
3070 ** interface is to keep a GUI updated during a large query.
3071 **
3072 ** ^The parameter P is passed through as the only parameter to the
3073 ** callback function X.  ^The parameter N is the number of
3074 ** [virtual machine instructions] that are evaluated between successive
3075 ** invocations of the callback X.
3076 **
3077 ** ^Only a single progress handler may be defined at one time per
3078 ** [database connection]; setting a new progress handler cancels the
3079 ** old one.  ^Setting parameter X to NULL disables the progress handler.
3080 ** ^The progress handler is also disabled by setting N to a value less
3081 ** than 1.
3082 **
3083 ** ^If the progress callback returns non-zero, the operation is
3084 ** interrupted.  This feature can be used to implement a
3085 ** "Cancel" button on a GUI progress dialog box.
3086 **
3087 ** The progress handler callback must not do anything that will modify
3088 ** the database connection that invoked the progress handler.
3089 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3090 ** database connections for the meaning of "modify" in this paragraph.
3091 **
3092 */
3093 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3094
3095 /*
3096 ** CAPI3REF: Opening A New Database Connection
3097 **
3098 ** ^These routines open an SQLite database file as specified by the
3099 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3100 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3101 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3102 ** returned in *ppDb, even if an error occurs.  The only exception is that
3103 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3104 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3105 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3106 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3107 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3108 ** an English language description of the error following a failure of any
3109 ** of the sqlite3_open() routines.
3110 **
3111 ** ^The default encoding for the database will be UTF-8 if
3112 ** sqlite3_open() or sqlite3_open_v2() is called and
3113 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3114 **
3115 ** Whether or not an error occurs when it is opened, resources
3116 ** associated with the [database connection] handle should be released by
3117 ** passing it to [sqlite3_close()] when it is no longer required.
3118 **
3119 ** The sqlite3_open_v2() interface works like sqlite3_open()
3120 ** except that it accepts two additional parameters for additional control
3121 ** over the new database connection.  ^(The flags parameter to
3122 ** sqlite3_open_v2() can take one of
3123 ** the following three values, optionally combined with the
3124 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3125 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3126 **
3127 ** <dl>
3128 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3129 ** <dd>The database is opened in read-only mode.  If the database does not
3130 ** already exist, an error is returned.</dd>)^
3131 **
3132 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3133 ** <dd>The database is opened for reading and writing if possible, or reading
3134 ** only if the file is write protected by the operating system.  In either
3135 ** case the database must already exist, otherwise an error is returned.</dd>)^
3136 **
3137 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3138 ** <dd>The database is opened for reading and writing, and is created if
3139 ** it does not already exist. This is the behavior that is always used for
3140 ** sqlite3_open() and sqlite3_open16().</dd>)^
3141 ** </dl>
3142 **
3143 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3144 ** combinations shown above optionally combined with other
3145 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3146 ** then the behavior is undefined.
3147 **
3148 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3149 ** opens in the multi-thread [threading mode] as long as the single-thread
3150 ** mode has not been set at compile-time or start-time.  ^If the
3151 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3152 ** in the serialized [threading mode] unless single-thread was
3153 ** previously selected at compile-time or start-time.
3154 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3155 ** eligible to use [shared cache mode], regardless of whether or not shared
3156 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3157 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3158 ** participate in [shared cache mode] even if it is enabled.
3159 **
3160 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3161 ** [sqlite3_vfs] object that defines the operating system interface that
3162 ** the new database connection should use.  ^If the fourth parameter is
3163 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3164 **
3165 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3166 ** is created for the connection.  ^This in-memory database will vanish when
3167 ** the database connection is closed.  Future versions of SQLite might
3168 ** make use of additional special filenames that begin with the ":" character.
3169 ** It is recommended that when a database filename actually does begin with
3170 ** a ":" character you should prefix the filename with a pathname such as
3171 ** "./" to avoid ambiguity.
3172 **
3173 ** ^If the filename is an empty string, then a private, temporary
3174 ** on-disk database will be created.  ^This private database will be
3175 ** automatically deleted as soon as the database connection is closed.
3176 **
3177 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3178 **
3179 ** ^If [URI filename] interpretation is enabled, and the filename argument
3180 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3181 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3182 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3183 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3184 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3185 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3186 ** by default, but future releases of SQLite might enable URI filename
3187 ** interpretation by default.  See "[URI filenames]" for additional
3188 ** information.
3189 **
3190 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3191 ** authority, then it must be either an empty string or the string
3192 ** "localhost". ^If the authority is not an empty string or "localhost", an
3193 ** error is returned to the caller. ^The fragment component of a URI, if
3194 ** present, is ignored.
3195 **
3196 ** ^SQLite uses the path component of the URI as the name of the disk file
3197 ** which contains the database. ^If the path begins with a '/' character,
3198 ** then it is interpreted as an absolute path. ^If the path does not begin
3199 ** with a '/' (meaning that the authority section is omitted from the URI)
3200 ** then the path is interpreted as a relative path.
3201 ** ^On windows, the first component of an absolute path
3202 ** is a drive specification (e.g. "C:").
3203 **
3204 ** [[core URI query parameters]]
3205 ** The query component of a URI may contain parameters that are interpreted
3206 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3207 ** SQLite interprets the following three query parameters:
3208 **
3209 ** <ul>
3210 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3211 **     a VFS object that provides the operating system interface that should
3212 **     be used to access the database file on disk. ^If this option is set to
3213 **     an empty string the default VFS object is used. ^Specifying an unknown
3214 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3215 **     present, then the VFS specified by the option takes precedence over
3216 **     the value passed as the fourth parameter to sqlite3_open_v2().
3217 **
3218 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3219 **     "rwc", or "memory". Attempting to set it to any other value is
3220 **     an error)^.
3221 **     ^If "ro" is specified, then the database is opened for read-only
3222 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3223 **     third argument to sqlite3_open_v2(). ^If the mode option is set to
3224 **     "rw", then the database is opened for read-write (but not create)
3225 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3226 **     been set. ^Value "rwc" is equivalent to setting both
3227 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3228 **     set to "memory" then a pure [in-memory database] that never reads
3229 **     or writes from disk is used. ^It is an error to specify a value for
3230 **     the mode parameter that is less restrictive than that specified by
3231 **     the flags passed in the third parameter to sqlite3_open_v2().
3232 **
3233 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3234 **     "private". ^Setting it to "shared" is equivalent to setting the
3235 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3236 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3237 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3238 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3239 **     a URI filename, its value overrides any behaviour requested by setting
3240 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3241 ** </ul>
3242 **
3243 ** ^Specifying an unknown parameter in the query component of a URI is not an
3244 ** error.  Future versions of SQLite might understand additional query
3245 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3246 ** additional information.
3247 **
3248 ** [[URI filename examples]] <h3>URI filename examples</h3>
3249 **
3250 ** <table border="1" align=center cellpadding=5>
3251 ** <tr><th> URI filenames <th> Results
3252 ** <tr><td> file:data.db <td>
3253 **          Open the file "data.db" in the current directory.
3254 ** <tr><td> file:/home/fred/data.db<br>
3255 **          file:///home/fred/data.db <br>
3256 **          file://localhost/home/fred/data.db <br> <td>
3257 **          Open the database file "/home/fred/data.db".
3258 ** <tr><td> file://darkstar/home/fred/data.db <td>
3259 **          An error. "darkstar" is not a recognized authority.
3260 ** <tr><td style="white-space:nowrap">
3261 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3262 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3263 **          C:. Note that the %20 escaping in this example is not strictly
3264 **          necessary - space characters can be used literally
3265 **          in URI filenames.
3266 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3267 **          Open file "data.db" in the current directory for read-only access.
3268 **          Regardless of whether or not shared-cache mode is enabled by
3269 **          default, use a private cache.
3270 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3271 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3272 ** <tr><td> file:data.db?mode=readonly <td>
3273 **          An error. "readonly" is not a valid option for the "mode" parameter.
3274 ** </table>
3275 **
3276 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3277 ** query components of a URI. A hexadecimal escape sequence consists of a
3278 ** percent sign - "%" - followed by exactly two hexadecimal digits
3279 ** specifying an octet value. ^Before the path or query components of a
3280 ** URI filename are interpreted, they are encoded using UTF-8 and all
3281 ** hexadecimal escape sequences replaced by a single byte containing the
3282 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3283 ** the results are undefined.
3284 **
3285 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3286 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3287 ** codepage is currently defined.  Filenames containing international
3288 ** characters must be converted to UTF-8 prior to passing them into
3289 ** sqlite3_open() or sqlite3_open_v2().
3290 **
3291 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3292 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3293 ** features that require the use of temporary files may fail.
3294 **
3295 ** See also: [sqlite3_temp_directory]
3296 */
3297 SQLITE_API int sqlite3_open(
3298   const char *filename,   /* Database filename (UTF-8) */
3299   sqlite3 **ppDb          /* OUT: SQLite db handle */
3300 );
3301 SQLITE_API int sqlite3_open16(
3302   const void *filename,   /* Database filename (UTF-16) */
3303   sqlite3 **ppDb          /* OUT: SQLite db handle */
3304 );
3305 SQLITE_API int sqlite3_open_v2(
3306   const char *filename,   /* Database filename (UTF-8) */
3307   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3308   int flags,              /* Flags */
3309   const char *zVfs        /* Name of VFS module to use */
3310 );
3311
3312 /*
3313 ** CAPI3REF: Obtain Values For URI Parameters
3314 **
3315 ** These are utility routines, useful to VFS implementations, that check
3316 ** to see if a database file was a URI that contained a specific query
3317 ** parameter, and if so obtains the value of that query parameter.
3318 **
3319 ** If F is the database filename pointer passed into the xOpen() method of
3320 ** a VFS implementation when the flags parameter to xOpen() has one or
3321 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3322 ** P is the name of the query parameter, then
3323 ** sqlite3_uri_parameter(F,P) returns the value of the P
3324 ** parameter if it exists or a NULL pointer if P does not appear as a
3325 ** query parameter on F.  If P is a query parameter of F
3326 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3327 ** a pointer to an empty string.
3328 **
3329 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3330 ** parameter and returns true (1) or false (0) according to the value
3331 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3332 ** value of query parameter P is one of "yes", "true", or "on" in any
3333 ** case or if the value begins with a non-zero number.  The
3334 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3335 ** query parameter P is one of "no", "false", or "off" in any case or
3336 ** if the value begins with a numeric zero.  If P is not a query
3337 ** parameter on F or if the value of P is does not match any of the
3338 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3339 **
3340 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3341 ** 64-bit signed integer and returns that integer, or D if P does not
3342 ** exist.  If the value of P is something other than an integer, then
3343 ** zero is returned.
3344 **
3345 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3346 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3347 ** is not a database file pathname pointer that SQLite passed into the xOpen
3348 ** VFS method, then the behavior of this routine is undefined and probably
3349 ** undesirable.
3350 */
3351 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3352 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3353 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3354
3355
3356 /*
3357 ** CAPI3REF: Error Codes And Messages
3358 **
3359 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3360 ** [extended result code] for the most recent failed sqlite3_* API call
3361 ** associated with a [database connection]. If a prior API call failed
3362 ** but the most recent API call succeeded, the return value from
3363 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3364 ** interface is the same except that it always returns the
3365 ** [extended result code] even when extended result codes are
3366 ** disabled.
3367 **
3368 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3369 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3370 ** ^(Memory to hold the error message string is managed internally.
3371 ** The application does not need to worry about freeing the result.
3372 ** However, the error string might be overwritten or deallocated by
3373 ** subsequent calls to other SQLite interface functions.)^
3374 **
3375 ** ^The sqlite3_errstr() interface returns the English-language text
3376 ** that describes the [result code], as UTF-8.
3377 ** ^(Memory to hold the error message string is managed internally
3378 ** and must not be freed by the application)^.
3379 **
3380 ** When the serialized [threading mode] is in use, it might be the
3381 ** case that a second error occurs on a separate thread in between
3382 ** the time of the first error and the call to these interfaces.
3383 ** When that happens, the second error will be reported since these
3384 ** interfaces always report the most recent result.  To avoid
3385 ** this, each thread can obtain exclusive use of the [database connection] D
3386 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3387 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3388 ** all calls to the interfaces listed here are completed.
3389 **
3390 ** If an interface fails with SQLITE_MISUSE, that means the interface
3391 ** was invoked incorrectly by the application.  In that case, the
3392 ** error code and message may or may not be set.
3393 */
3394 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3395 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3396 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3397 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3398 SQLITE_API const char *sqlite3_errstr(int);
3399
3400 /*
3401 ** CAPI3REF: SQL Statement Object
3402 ** KEYWORDS: {prepared statement} {prepared statements}
3403 **
3404 ** An instance of this object represents a single SQL statement.
3405 ** This object is variously known as a "prepared statement" or a
3406 ** "compiled SQL statement" or simply as a "statement".
3407 **
3408 ** The life of a statement object goes something like this:
3409 **
3410 ** <ol>
3411 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3412 **      function.
3413 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3414 **      interfaces.
3415 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3416 ** <li> Reset the statement using [sqlite3_reset()] then go back
3417 **      to step 2.  Do this zero or more times.
3418 ** <li> Destroy the object using [sqlite3_finalize()].
3419 ** </ol>
3420 **
3421 ** Refer to documentation on individual methods above for additional
3422 ** information.
3423 */
3424 typedef struct sqlite3_stmt sqlite3_stmt;
3425
3426 /*
3427 ** CAPI3REF: Run-time Limits
3428 **
3429 ** ^(This interface allows the size of various constructs to be limited
3430 ** on a connection by connection basis.  The first parameter is the
3431 ** [database connection] whose limit is to be set or queried.  The
3432 ** second parameter is one of the [limit categories] that define a
3433 ** class of constructs to be size limited.  The third parameter is the
3434 ** new limit for that construct.)^
3435 **
3436 ** ^If the new limit is a negative number, the limit is unchanged.
3437 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3438 ** [limits | hard upper bound]
3439 ** set at compile-time by a C preprocessor macro called
3440 ** [limits | SQLITE_MAX_<i>NAME</i>].
3441 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3442 ** ^Attempts to increase a limit above its hard upper bound are
3443 ** silently truncated to the hard upper bound.
3444 **
3445 ** ^Regardless of whether or not the limit was changed, the
3446 ** [sqlite3_limit()] interface returns the prior value of the limit.
3447 ** ^Hence, to find the current value of a limit without changing it,
3448 ** simply invoke this interface with the third parameter set to -1.
3449 **
3450 ** Run-time limits are intended for use in applications that manage
3451 ** both their own internal database and also databases that are controlled
3452 ** by untrusted external sources.  An example application might be a
3453 ** web browser that has its own databases for storing history and
3454 ** separate databases controlled by JavaScript applications downloaded
3455 ** off the Internet.  The internal databases can be given the
3456 ** large, default limits.  Databases managed by external sources can
3457 ** be given much smaller limits designed to prevent a denial of service
3458 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3459 ** interface to further control untrusted SQL.  The size of the database
3460 ** created by an untrusted script can be contained using the
3461 ** [max_page_count] [PRAGMA].
3462 **
3463 ** New run-time limit categories may be added in future releases.
3464 */
3465 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3466
3467 /*
3468 ** CAPI3REF: Run-Time Limit Categories
3469 ** KEYWORDS: {limit category} {*limit categories}
3470 **
3471 ** These constants define various performance limits
3472 ** that can be lowered at run-time using [sqlite3_limit()].
3473 ** The synopsis of the meanings of the various limits is shown below.
3474 ** Additional information is available at [limits | Limits in SQLite].
3475 **
3476 ** <dl>
3477 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3478 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3479 **
3480 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3481 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3482 **
3483 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3484 ** <dd>The maximum number of columns in a table definition or in the
3485 ** result set of a [SELECT] or the maximum number of columns in an index
3486 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3487 **
3488 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3489 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3490 **
3491 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3492 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3493 **
3494 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3495 ** <dd>The maximum number of instructions in a virtual machine program
3496 ** used to implement an SQL statement.  This limit is not currently
3497 ** enforced, though that might be added in some future release of
3498 ** SQLite.</dd>)^
3499 **
3500 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3501 ** <dd>The maximum number of arguments on a function.</dd>)^
3502 **
3503 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3504 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3505 **
3506 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3507 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3508 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3509 ** [GLOB] operators.</dd>)^
3510 **
3511 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3512 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3513 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3514 **
3515 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3516 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3517 ** </dl>
3518 */
3519 #define SQLITE_LIMIT_LENGTH                    0
3520 #define SQLITE_LIMIT_SQL_LENGTH                1
3521 #define SQLITE_LIMIT_COLUMN                    2
3522 #define SQLITE_LIMIT_EXPR_DEPTH                3
3523 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3524 #define SQLITE_LIMIT_VDBE_OP                   5
3525 #define SQLITE_LIMIT_FUNCTION_ARG              6
3526 #define SQLITE_LIMIT_ATTACHED                  7
3527 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3528 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3529 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3530
3531 /*
3532 ** CAPI3REF: Compiling An SQL Statement
3533 ** KEYWORDS: {SQL statement compiler}
3534 **
3535 ** To execute an SQL query, it must first be compiled into a byte-code
3536 ** program using one of these routines.
3537 **
3538 ** The first argument, "db", is a [database connection] obtained from a
3539 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3540 ** [sqlite3_open16()].  The database connection must not have been closed.
3541 **
3542 ** The second argument, "zSql", is the statement to be compiled, encoded
3543 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3544 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3545 ** use UTF-16.
3546 **
3547 ** ^If the nByte argument is less than zero, then zSql is read up to the
3548 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3549 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3550 ** zSql string ends at either the first '\000' or '\u0000' character or
3551 ** the nByte-th byte, whichever comes first. If the caller knows
3552 ** that the supplied string is nul-terminated, then there is a small
3553 ** performance advantage to be gained by passing an nByte parameter that
3554 ** is equal to the number of bytes in the input string <i>including</i>
3555 ** the nul-terminator bytes as this saves SQLite from having to
3556 ** make a copy of the input string.
3557 **
3558 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3559 ** past the end of the first SQL statement in zSql.  These routines only
3560 ** compile the first statement in zSql, so *pzTail is left pointing to
3561 ** what remains uncompiled.
3562 **
3563 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3564 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3565 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3566 ** string or a comment) then *ppStmt is set to NULL.
3567 ** The calling procedure is responsible for deleting the compiled
3568 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3569 ** ppStmt may not be NULL.
3570 **
3571 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3572 ** otherwise an [error code] is returned.
3573 **
3574 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3575 ** recommended for all new programs. The two older interfaces are retained
3576 ** for backwards compatibility, but their use is discouraged.
3577 ** ^In the "v2" interfaces, the prepared statement
3578 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3579 ** original SQL text. This causes the [sqlite3_step()] interface to
3580 ** behave differently in three ways:
3581 **
3582 ** <ol>
3583 ** <li>
3584 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3585 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3586 ** statement and try to run it again.
3587 ** </li>
3588 **
3589 ** <li>
3590 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3591 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3592 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3593 ** and the application would have to make a second call to [sqlite3_reset()]
3594 ** in order to find the underlying cause of the problem. With the "v2" prepare
3595 ** interfaces, the underlying reason for the error is returned immediately.
3596 ** </li>
3597 **
3598 ** <li>
3599 ** ^If the specific value bound to [parameter | host parameter] in the
3600 ** WHERE clause might influence the choice of query plan for a statement,
3601 ** then the statement will be automatically recompiled, as if there had been
3602 ** a schema change, on the first  [sqlite3_step()] call following any change
3603 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3604 ** ^The specific value of WHERE-clause [parameter] might influence the
3605 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3606 ** or [GLOB] operator or if the parameter is compared to an indexed column
3607 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3608 ** the
3609 ** </li>
3610 ** </ol>
3611 */
3612 SQLITE_API int sqlite3_prepare(
3613   sqlite3 *db,            /* Database handle */
3614   const char *zSql,       /* SQL statement, UTF-8 encoded */
3615   int nByte,              /* Maximum length of zSql in bytes. */
3616   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3617   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3618 );
3619 SQLITE_API int sqlite3_prepare_v2(
3620   sqlite3 *db,            /* Database handle */
3621   const char *zSql,       /* SQL statement, UTF-8 encoded */
3622   int nByte,              /* Maximum length of zSql in bytes. */
3623   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3624   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3625 );
3626 SQLITE_API int sqlite3_prepare16(
3627   sqlite3 *db,            /* Database handle */
3628   const void *zSql,       /* SQL statement, UTF-16 encoded */
3629   int nByte,              /* Maximum length of zSql in bytes. */
3630   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3631   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3632 );
3633 SQLITE_API int sqlite3_prepare16_v2(
3634   sqlite3 *db,            /* Database handle */
3635   const void *zSql,       /* SQL statement, UTF-16 encoded */
3636   int nByte,              /* Maximum length of zSql in bytes. */
3637   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3638   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3639 );
3640
3641 /*
3642 ** CAPI3REF: Retrieving Statement SQL
3643 **
3644 ** ^This interface can be used to retrieve a saved copy of the original
3645 ** SQL text used to create a [prepared statement] if that statement was
3646 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3647 */
3648 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3649
3650 /*
3651 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3652 **
3653 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3654 ** and only if the [prepared statement] X makes no direct changes to
3655 ** the content of the database file.
3656 **
3657 ** Note that [application-defined SQL functions] or
3658 ** [virtual tables] might change the database indirectly as a side effect.
3659 ** ^(For example, if an application defines a function "eval()" that
3660 ** calls [sqlite3_exec()], then the following SQL statement would
3661 ** change the database file through side-effects:
3662 **
3663 ** <blockquote><pre>
3664 **    SELECT eval('DELETE FROM t1') FROM t2;
3665 ** </pre></blockquote>
3666 **
3667 ** But because the [SELECT] statement does not change the database file
3668 ** directly, sqlite3_stmt_readonly() would still return true.)^
3669 **
3670 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3671 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3672 ** since the statements themselves do not actually modify the database but
3673 ** rather they control the timing of when other statements modify the
3674 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3675 ** sqlite3_stmt_readonly() to return true since, while those statements
3676 ** change the configuration of a database connection, they do not make
3677 ** changes to the content of the database files on disk.
3678 */
3679 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3680
3681 /*
3682 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3683 **
3684 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3685 ** [prepared statement] S has been stepped at least once using
3686 ** [sqlite3_step(S)] but has not run to completion and/or has not
3687 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3688 ** interface returns false if S is a NULL pointer.  If S is not a
3689 ** NULL pointer and is not a pointer to a valid [prepared statement]
3690 ** object, then the behavior is undefined and probably undesirable.
3691 **
3692 ** This interface can be used in combination [sqlite3_next_stmt()]
3693 ** to locate all prepared statements associated with a database
3694 ** connection that are in need of being reset.  This can be used,
3695 ** for example, in diagnostic routines to search for prepared
3696 ** statements that are holding a transaction open.
3697 */
3698 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3699
3700 /*
3701 ** CAPI3REF: Dynamically Typed Value Object
3702 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3703 **
3704 ** SQLite uses the sqlite3_value object to represent all values
3705 ** that can be stored in a database table. SQLite uses dynamic typing
3706 ** for the values it stores.  ^Values stored in sqlite3_value objects
3707 ** can be integers, floating point values, strings, BLOBs, or NULL.
3708 **
3709 ** An sqlite3_value object may be either "protected" or "unprotected".
3710 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3711 ** will accept either a protected or an unprotected sqlite3_value.
3712 ** Every interface that accepts sqlite3_value arguments specifies
3713 ** whether or not it requires a protected sqlite3_value.
3714 **
3715 ** The terms "protected" and "unprotected" refer to whether or not
3716 ** a mutex is held.  An internal mutex is held for a protected
3717 ** sqlite3_value object but no mutex is held for an unprotected
3718 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3719 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3720 ** or if SQLite is run in one of reduced mutex modes
3721 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3722 ** then there is no distinction between protected and unprotected
3723 ** sqlite3_value objects and they can be used interchangeably.  However,
3724 ** for maximum code portability it is recommended that applications
3725 ** still make the distinction between protected and unprotected
3726 ** sqlite3_value objects even when not strictly required.
3727 **
3728 ** ^The sqlite3_value objects that are passed as parameters into the
3729 ** implementation of [application-defined SQL functions] are protected.
3730 ** ^The sqlite3_value object returned by
3731 ** [sqlite3_column_value()] is unprotected.
3732 ** Unprotected sqlite3_value objects may only be used with
3733 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3734 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3735 ** interfaces require protected sqlite3_value objects.
3736 */
3737 typedef struct Mem sqlite3_value;
3738
3739 /*
3740 ** CAPI3REF: SQL Function Context Object
3741 **
3742 ** The context in which an SQL function executes is stored in an
3743 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3744 ** is always first parameter to [application-defined SQL functions].
3745 ** The application-defined SQL function implementation will pass this
3746 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3747 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3748 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3749 ** and/or [sqlite3_set_auxdata()].
3750 */
3751 typedef struct sqlite3_context sqlite3_context;
3752
3753 /*
3754 ** CAPI3REF: Binding Values To Prepared Statements
3755 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3756 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3757 **
3758 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3759 ** literals may be replaced by a [parameter] that matches one of following
3760 ** templates:
3761 **
3762 ** <ul>
3763 ** <li>  ?
3764 ** <li>  ?NNN
3765 ** <li>  :VVV
3766 ** <li>  @VVV
3767 ** <li>  $VVV
3768 ** </ul>
3769 **
3770 ** In the templates above, NNN represents an integer literal,
3771 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3772 ** parameters (also called "host parameter names" or "SQL parameters")
3773 ** can be set using the sqlite3_bind_*() routines defined here.
3774 **
3775 ** ^The first argument to the sqlite3_bind_*() routines is always
3776 ** a pointer to the [sqlite3_stmt] object returned from
3777 ** [sqlite3_prepare_v2()] or its variants.
3778 **
3779 ** ^The second argument is the index of the SQL parameter to be set.
3780 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3781 ** SQL parameter is used more than once, second and subsequent
3782 ** occurrences have the same index as the first occurrence.
3783 ** ^The index for named parameters can be looked up using the
3784 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3785 ** for "?NNN" parameters is the value of NNN.
3786 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3787 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3788 **
3789 ** ^The third argument is the value to bind to the parameter.
3790 **
3791 ** ^(In those routines that have a fourth argument, its value is the
3792 ** number of bytes in the parameter.  To be clear: the value is the
3793 ** number of <u>bytes</u> in the value, not the number of characters.)^
3794 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3795 ** is negative, then the length of the string is
3796 ** the number of bytes up to the first zero terminator.
3797 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3798 ** the behavior is undefined.
3799 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3800 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3801 ** where the NUL terminator would occur assuming the string were NUL
3802 ** terminated.  If any NUL characters occur at byte offsets less than
3803 ** the value of the fourth parameter then the resulting string value will
3804 ** contain embedded NULs.  The result of expressions involving strings
3805 ** with embedded NULs is undefined.
3806 **
3807 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3808 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3809 ** string after SQLite has finished with it.  ^The destructor is called
3810 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3811 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3812 ** ^If the fifth argument is
3813 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3814 ** information is in static, unmanaged space and does not need to be freed.
3815 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3816 ** SQLite makes its own private copy of the data immediately, before
3817 ** the sqlite3_bind_*() routine returns.
3818 **
3819 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3820 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3821 ** (just an integer to hold its size) while it is being processed.
3822 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3823 ** content is later written using
3824 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3825 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3826 **
3827 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3828 ** for the [prepared statement] or with a prepared statement for which
3829 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3830 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3831 ** routine is passed a [prepared statement] that has been finalized, the
3832 ** result is undefined and probably harmful.
3833 **
3834 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3835 ** ^Unbound parameters are interpreted as NULL.
3836 **
3837 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3838 ** [error code] if anything goes wrong.
3839 ** ^[SQLITE_RANGE] is returned if the parameter
3840 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3841 **
3842 ** See also: [sqlite3_bind_parameter_count()],
3843 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3844 */
3845 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3846 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3847 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3848 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3849 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3850 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3851 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3852 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3853 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3854
3855 /*
3856 ** CAPI3REF: Number Of SQL Parameters
3857 **
3858 ** ^This routine can be used to find the number of [SQL parameters]
3859 ** in a [prepared statement].  SQL parameters are tokens of the
3860 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3861 ** placeholders for values that are [sqlite3_bind_blob | bound]
3862 ** to the parameters at a later time.
3863 **
3864 ** ^(This routine actually returns the index of the largest (rightmost)
3865 ** parameter. For all forms except ?NNN, this will correspond to the
3866 ** number of unique parameters.  If parameters of the ?NNN form are used,
3867 ** there may be gaps in the list.)^
3868 **
3869 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3870 ** [sqlite3_bind_parameter_name()], and
3871 ** [sqlite3_bind_parameter_index()].
3872 */
3873 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3874
3875 /*
3876 ** CAPI3REF: Name Of A Host Parameter
3877 **
3878 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3879 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3880 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3881 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3882 ** respectively.
3883 ** In other words, the initial ":" or "$" or "@" or "?"
3884 ** is included as part of the name.)^
3885 ** ^Parameters of the form "?" without a following integer have no name
3886 ** and are referred to as "nameless" or "anonymous parameters".
3887 **
3888 ** ^The first host parameter has an index of 1, not 0.
3889 **
3890 ** ^If the value N is out of range or if the N-th parameter is
3891 ** nameless, then NULL is returned.  ^The returned string is
3892 ** always in UTF-8 encoding even if the named parameter was
3893 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3894 ** [sqlite3_prepare16_v2()].
3895 **
3896 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3897 ** [sqlite3_bind_parameter_count()], and
3898 ** [sqlite3_bind_parameter_index()].
3899 */
3900 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3901
3902 /*
3903 ** CAPI3REF: Index Of A Parameter With A Given Name
3904 **
3905 ** ^Return the index of an SQL parameter given its name.  ^The
3906 ** index value returned is suitable for use as the second
3907 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3908 ** is returned if no matching parameter is found.  ^The parameter
3909 ** name must be given in UTF-8 even if the original statement
3910 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3911 **
3912 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3913 ** [sqlite3_bind_parameter_count()], and
3914 ** [sqlite3_bind_parameter_index()].
3915 */
3916 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3917
3918 /*
3919 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3920 **
3921 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3922 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3923 ** ^Use this routine to reset all host parameters to NULL.
3924 */
3925 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3926
3927 /*
3928 ** CAPI3REF: Number Of Columns In A Result Set
3929 **
3930 ** ^Return the number of columns in the result set returned by the
3931 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3932 ** statement that does not return data (for example an [UPDATE]).
3933 **
3934 ** See also: [sqlite3_data_count()]
3935 */
3936 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3937
3938 /*
3939 ** CAPI3REF: Column Names In A Result Set
3940 **
3941 ** ^These routines return the name assigned to a particular column
3942 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3943 ** interface returns a pointer to a zero-terminated UTF-8 string
3944 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3945 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3946 ** that implements the [SELECT] statement. ^The second parameter is the
3947 ** column number.  ^The leftmost column is number 0.
3948 **
3949 ** ^The returned string pointer is valid until either the [prepared statement]
3950 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3951 ** reprepared by the first call to [sqlite3_step()] for a particular run
3952 ** or until the next call to
3953 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3954 **
3955 ** ^If sqlite3_malloc() fails during the processing of either routine
3956 ** (for example during a conversion from UTF-8 to UTF-16) then a
3957 ** NULL pointer is returned.
3958 **
3959 ** ^The name of a result column is the value of the "AS" clause for
3960 ** that column, if there is an AS clause.  If there is no AS clause
3961 ** then the name of the column is unspecified and may change from
3962 ** one release of SQLite to the next.
3963 */
3964 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3965 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3966
3967 /*
3968 ** CAPI3REF: Source Of Data In A Query Result
3969 **
3970 ** ^These routines provide a means to determine the database, table, and
3971 ** table column that is the origin of a particular result column in
3972 ** [SELECT] statement.
3973 ** ^The name of the database or table or column can be returned as
3974 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3975 ** the database name, the _table_ routines return the table name, and
3976 ** the origin_ routines return the column name.
3977 ** ^The returned string is valid until the [prepared statement] is destroyed
3978 ** using [sqlite3_finalize()] or until the statement is automatically
3979 ** reprepared by the first call to [sqlite3_step()] for a particular run
3980 ** or until the same information is requested
3981 ** again in a different encoding.
3982 **
3983 ** ^The names returned are the original un-aliased names of the
3984 ** database, table, and column.
3985 **
3986 ** ^The first argument to these interfaces is a [prepared statement].
3987 ** ^These functions return information about the Nth result column returned by
3988 ** the statement, where N is the second function argument.
3989 ** ^The left-most column is column 0 for these routines.
3990 **
3991 ** ^If the Nth column returned by the statement is an expression or
3992 ** subquery and is not a column value, then all of these functions return
3993 ** NULL.  ^These routine might also return NULL if a memory allocation error
3994 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3995 ** or column that query result column was extracted from.
3996 **
3997 ** ^As with all other SQLite APIs, those whose names end with "16" return
3998 ** UTF-16 encoded strings and the other functions return UTF-8.
3999 **
4000 ** ^These APIs are only available if the library was compiled with the
4001 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4002 **
4003 ** If two or more threads call one or more of these routines against the same
4004 ** prepared statement and column at the same time then the results are
4005 ** undefined.
4006 **
4007 ** If two or more threads call one or more
4008 ** [sqlite3_column_database_name | column metadata interfaces]
4009 ** for the same [prepared statement] and result column
4010 ** at the same time then the results are undefined.
4011 */
4012 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4013 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4014 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4015 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4016 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4017 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4018
4019 /*
4020 ** CAPI3REF: Declared Datatype Of A Query Result
4021 **
4022 ** ^(The first parameter is a [prepared statement].
4023 ** If this statement is a [SELECT] statement and the Nth column of the
4024 ** returned result set of that [SELECT] is a table column (not an
4025 ** expression or subquery) then the declared type of the table
4026 ** column is returned.)^  ^If the Nth column of the result set is an
4027 ** expression or subquery, then a NULL pointer is returned.
4028 ** ^The returned string is always UTF-8 encoded.
4029 **
4030 ** ^(For example, given the database schema:
4031 **
4032 ** CREATE TABLE t1(c1 VARIANT);
4033 **
4034 ** and the following statement to be compiled:
4035 **
4036 ** SELECT c1 + 1, c1 FROM t1;
4037 **
4038 ** this routine would return the string "VARIANT" for the second result
4039 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4040 **
4041 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
4042 ** is declared to contain a particular type does not mean that the
4043 ** data stored in that column is of the declared type.  SQLite is
4044 ** strongly typed, but the typing is dynamic not static.  ^Type
4045 ** is associated with individual values, not with the containers
4046 ** used to hold those values.
4047 */
4048 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4049 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4050
4051 /*
4052 ** CAPI3REF: Evaluate An SQL Statement
4053 **
4054 ** After a [prepared statement] has been prepared using either
4055 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4056 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4057 ** must be called one or more times to evaluate the statement.
4058 **
4059 ** The details of the behavior of the sqlite3_step() interface depend
4060 ** on whether the statement was prepared using the newer "v2" interface
4061 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4062 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4063 ** new "v2" interface is recommended for new applications but the legacy
4064 ** interface will continue to be supported.
4065 **
4066 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4067 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4068 ** ^With the "v2" interface, any of the other [result codes] or
4069 ** [extended result codes] might be returned as well.
4070 **
4071 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4072 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4073 ** or occurs outside of an explicit transaction, then you can retry the
4074 ** statement.  If the statement is not a [COMMIT] and occurs within an
4075 ** explicit transaction then you should rollback the transaction before
4076 ** continuing.
4077 **
4078 ** ^[SQLITE_DONE] means that the statement has finished executing
4079 ** successfully.  sqlite3_step() should not be called again on this virtual
4080 ** machine without first calling [sqlite3_reset()] to reset the virtual
4081 ** machine back to its initial state.
4082 **
4083 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4084 ** is returned each time a new row of data is ready for processing by the
4085 ** caller. The values may be accessed using the [column access functions].
4086 ** sqlite3_step() is called again to retrieve the next row of data.
4087 **
4088 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4089 ** violation) has occurred.  sqlite3_step() should not be called again on
4090 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4091 ** ^With the legacy interface, a more specific error code (for example,
4092 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4093 ** can be obtained by calling [sqlite3_reset()] on the
4094 ** [prepared statement].  ^In the "v2" interface,
4095 ** the more specific error code is returned directly by sqlite3_step().
4096 **
4097 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4098 ** Perhaps it was called on a [prepared statement] that has
4099 ** already been [sqlite3_finalize | finalized] or on one that had
4100 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4101 ** be the case that the same database connection is being used by two or
4102 ** more threads at the same moment in time.
4103 **
4104 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4105 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4106 ** other than [SQLITE_ROW] before any subsequent invocation of
4107 ** sqlite3_step().  Failure to reset the prepared statement using
4108 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4109 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4110 ** calling [sqlite3_reset()] automatically in this circumstance rather
4111 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4112 ** break because any application that ever receives an SQLITE_MISUSE error
4113 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4114 ** can be used to restore the legacy behavior.
4115 **
4116 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4117 ** API always returns a generic error code, [SQLITE_ERROR], following any
4118 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4119 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4120 ** specific [error codes] that better describes the error.
4121 ** We admit that this is a goofy design.  The problem has been fixed
4122 ** with the "v2" interface.  If you prepare all of your SQL statements
4123 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4124 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4125 ** then the more specific [error codes] are returned directly
4126 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4127 */
4128 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4129
4130 /*
4131 ** CAPI3REF: Number of columns in a result set
4132 **
4133 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4134 ** current row of the result set of [prepared statement] P.
4135 ** ^If prepared statement P does not have results ready to return
4136 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4137 ** interfaces) then sqlite3_data_count(P) returns 0.
4138 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4139 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4140 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4141 ** will return non-zero if previous call to [sqlite3_step](P) returned
4142 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4143 ** where it always returns zero since each step of that multi-step
4144 ** pragma returns 0 columns of data.
4145 **
4146 ** See also: [sqlite3_column_count()]
4147 */
4148 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4149
4150 /*
4151 ** CAPI3REF: Fundamental Datatypes
4152 ** KEYWORDS: SQLITE_TEXT
4153 **
4154 ** ^(Every value in SQLite has one of five fundamental datatypes:
4155 **
4156 ** <ul>
4157 ** <li> 64-bit signed integer
4158 ** <li> 64-bit IEEE floating point number
4159 ** <li> string
4160 ** <li> BLOB
4161 ** <li> NULL
4162 ** </ul>)^
4163 **
4164 ** These constants are codes for each of those types.
4165 **
4166 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4167 ** for a completely different meaning.  Software that links against both
4168 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4169 ** SQLITE_TEXT.
4170 */
4171 #define SQLITE_INTEGER  1
4172 #define SQLITE_FLOAT    2
4173 #define SQLITE_BLOB     4
4174 #define SQLITE_NULL     5
4175 #ifdef SQLITE_TEXT
4176 # undef SQLITE_TEXT
4177 #else
4178 # define SQLITE_TEXT     3
4179 #endif
4180 #define SQLITE3_TEXT     3
4181
4182 /*
4183 ** CAPI3REF: Result Values From A Query
4184 ** KEYWORDS: {column access functions}
4185 **
4186 ** These routines form the "result set" interface.
4187 **
4188 ** ^These routines return information about a single column of the current
4189 ** result row of a query.  ^In every case the first argument is a pointer
4190 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4191 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4192 ** and the second argument is the index of the column for which information
4193 ** should be returned. ^The leftmost column of the result set has the index 0.
4194 ** ^The number of columns in the result can be determined using
4195 ** [sqlite3_column_count()].
4196 **
4197 ** If the SQL statement does not currently point to a valid row, or if the
4198 ** column index is out of range, the result is undefined.
4199 ** These routines may only be called when the most recent call to
4200 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4201 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4202 ** If any of these routines are called after [sqlite3_reset()] or
4203 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4204 ** something other than [SQLITE_ROW], the results are undefined.
4205 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4206 ** are called from a different thread while any of these routines
4207 ** are pending, then the results are undefined.
4208 **
4209 ** ^The sqlite3_column_type() routine returns the
4210 ** [SQLITE_INTEGER | datatype code] for the initial data type
4211 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4212 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4213 ** returned by sqlite3_column_type() is only meaningful if no type
4214 ** conversions have occurred as described below.  After a type conversion,
4215 ** the value returned by sqlite3_column_type() is undefined.  Future
4216 ** versions of SQLite may change the behavior of sqlite3_column_type()
4217 ** following a type conversion.
4218 **
4219 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4220 ** routine returns the number of bytes in that BLOB or string.
4221 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4222 ** the string to UTF-8 and then returns the number of bytes.
4223 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4224 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4225 ** the number of bytes in that string.
4226 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4227 **
4228 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4229 ** routine returns the number of bytes in that BLOB or string.
4230 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4231 ** the string to UTF-16 and then returns the number of bytes.
4232 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4233 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4234 ** the number of bytes in that string.
4235 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4236 **
4237 ** ^The values returned by [sqlite3_column_bytes()] and
4238 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4239 ** of the string.  ^For clarity: the values returned by
4240 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4241 ** bytes in the string, not the number of characters.
4242 **
4243 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4244 ** even empty strings, are always zero-terminated.  ^The return
4245 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4246 **
4247 ** ^The object returned by [sqlite3_column_value()] is an
4248 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4249 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4250 ** If the [unprotected sqlite3_value] object returned by
4251 ** [sqlite3_column_value()] is used in any other way, including calls
4252 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4253 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4254 **
4255 ** These routines attempt to convert the value where appropriate.  ^For
4256 ** example, if the internal representation is FLOAT and a text result
4257 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4258 ** conversion automatically.  ^(The following table details the conversions
4259 ** that are applied:
4260 **
4261 ** <blockquote>
4262 ** <table border="1">
4263 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4264 **
4265 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4266 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4267 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4268 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4269 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4270 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4271 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4272 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4273 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4274 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4275 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4276 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4277 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4278 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4279 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4280 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4281 ** </table>
4282 ** </blockquote>)^
4283 **
4284 ** The table above makes reference to standard C library functions atoi()
4285 ** and atof().  SQLite does not really use these functions.  It has its
4286 ** own equivalent internal routines.  The atoi() and atof() names are
4287 ** used in the table for brevity and because they are familiar to most
4288 ** C programmers.
4289 **
4290 ** Note that when type conversions occur, pointers returned by prior
4291 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4292 ** sqlite3_column_text16() may be invalidated.
4293 ** Type conversions and pointer invalidations might occur
4294 ** in the following cases:
4295 **
4296 ** <ul>
4297 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4298 **      sqlite3_column_text16() is called.  A zero-terminator might
4299 **      need to be added to the string.</li>
4300 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4301 **      sqlite3_column_text16() is called.  The content must be converted
4302 **      to UTF-16.</li>
4303 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4304 **      sqlite3_column_text() is called.  The content must be converted
4305 **      to UTF-8.</li>
4306 ** </ul>
4307 **
4308 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4309 ** not invalidate a prior pointer, though of course the content of the buffer
4310 ** that the prior pointer references will have been modified.  Other kinds
4311 ** of conversion are done in place when it is possible, but sometimes they
4312 ** are not possible and in those cases prior pointers are invalidated.
4313 **
4314 ** The safest and easiest to remember policy is to invoke these routines
4315 ** in one of the following ways:
4316 **
4317 ** <ul>
4318 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4319 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4320 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4321 ** </ul>
4322 **
4323 ** In other words, you should call sqlite3_column_text(),
4324 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4325 ** into the desired format, then invoke sqlite3_column_bytes() or
4326 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4327 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4328 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4329 ** with calls to sqlite3_column_bytes().
4330 **
4331 ** ^The pointers returned are valid until a type conversion occurs as
4332 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4333 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4334 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4335 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4336 ** [sqlite3_free()].
4337 **
4338 ** ^(If a memory allocation error occurs during the evaluation of any
4339 ** of these routines, a default value is returned.  The default value
4340 ** is either the integer 0, the floating point number 0.0, or a NULL
4341 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4342 ** [SQLITE_NOMEM].)^
4343 */
4344 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4345 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4346 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4347 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4348 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4349 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4350 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4351 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4352 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4353 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4354
4355 /*
4356 ** CAPI3REF: Destroy A Prepared Statement Object
4357 **
4358 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4359 ** ^If the most recent evaluation of the statement encountered no errors
4360 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4361 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4362 ** sqlite3_finalize(S) returns the appropriate [error code] or
4363 ** [extended error code].
4364 **
4365 ** ^The sqlite3_finalize(S) routine can be called at any point during
4366 ** the life cycle of [prepared statement] S:
4367 ** before statement S is ever evaluated, after
4368 ** one or more calls to [sqlite3_reset()], or after any call
4369 ** to [sqlite3_step()] regardless of whether or not the statement has
4370 ** completed execution.
4371 **
4372 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4373 **
4374 ** The application must finalize every [prepared statement] in order to avoid
4375 ** resource leaks.  It is a grievous error for the application to try to use
4376 ** a prepared statement after it has been finalized.  Any use of a prepared
4377 ** statement after it has been finalized can result in undefined and
4378 ** undesirable behavior such as segfaults and heap corruption.
4379 */
4380 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4381
4382 /*
4383 ** CAPI3REF: Reset A Prepared Statement Object
4384 **
4385 ** The sqlite3_reset() function is called to reset a [prepared statement]
4386 ** object back to its initial state, ready to be re-executed.
4387 ** ^Any SQL statement variables that had values bound to them using
4388 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4389 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4390 **
4391 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4392 ** back to the beginning of its program.
4393 **
4394 ** ^If the most recent call to [sqlite3_step(S)] for the
4395 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4396 ** or if [sqlite3_step(S)] has never before been called on S,
4397 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4398 **
4399 ** ^If the most recent call to [sqlite3_step(S)] for the
4400 ** [prepared statement] S indicated an error, then
4401 ** [sqlite3_reset(S)] returns an appropriate [error code].
4402 **
4403 ** ^The [sqlite3_reset(S)] interface does not change the values
4404 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4405 */
4406 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4407
4408 /*
4409 ** CAPI3REF: Create Or Redefine SQL Functions
4410 ** KEYWORDS: {function creation routines}
4411 ** KEYWORDS: {application-defined SQL function}
4412 ** KEYWORDS: {application-defined SQL functions}
4413 **
4414 ** ^These functions (collectively known as "function creation routines")
4415 ** are used to add SQL functions or aggregates or to redefine the behavior
4416 ** of existing SQL functions or aggregates.  The only differences between
4417 ** these routines are the text encoding expected for
4418 ** the second parameter (the name of the function being created)
4419 ** and the presence or absence of a destructor callback for
4420 ** the application data pointer.
4421 **
4422 ** ^The first parameter is the [database connection] to which the SQL
4423 ** function is to be added.  ^If an application uses more than one database
4424 ** connection then application-defined SQL functions must be added
4425 ** to each database connection separately.
4426 **
4427 ** ^The second parameter is the name of the SQL function to be created or
4428 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4429 ** representation, exclusive of the zero-terminator.  ^Note that the name
4430 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4431 ** ^Any attempt to create a function with a longer name
4432 ** will result in [SQLITE_MISUSE] being returned.
4433 **
4434 ** ^The third parameter (nArg)
4435 ** is the number of arguments that the SQL function or
4436 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4437 ** aggregate may take any number of arguments between 0 and the limit
4438 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4439 ** parameter is less than -1 or greater than 127 then the behavior is
4440 ** undefined.
4441 **
4442 ** ^The fourth parameter, eTextRep, specifies what
4443 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4444 ** its parameters.  Every SQL function implementation must be able to work
4445 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4446 ** more efficient with one encoding than another.  ^An application may
4447 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4448 ** times with the same function but with different values of eTextRep.
4449 ** ^When multiple implementations of the same function are available, SQLite
4450 ** will pick the one that involves the least amount of data conversion.
4451 ** If there is only a single implementation which does not care what text
4452 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4453 **
4454 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4455 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4456 **
4457 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4458 ** pointers to C-language functions that implement the SQL function or
4459 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4460 ** callback only; NULL pointers must be passed as the xStep and xFinal
4461 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4462 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4463 ** SQL function or aggregate, pass NULL pointers for all three function
4464 ** callbacks.
4465 **
4466 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4467 ** then it is destructor for the application data pointer.
4468 ** The destructor is invoked when the function is deleted, either by being
4469 ** overloaded or when the database connection closes.)^
4470 ** ^The destructor is also invoked if the call to
4471 ** sqlite3_create_function_v2() fails.
4472 ** ^When the destructor callback of the tenth parameter is invoked, it
4473 ** is passed a single argument which is a copy of the application data
4474 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4475 **
4476 ** ^It is permitted to register multiple implementations of the same
4477 ** functions with the same name but with either differing numbers of
4478 ** arguments or differing preferred text encodings.  ^SQLite will use
4479 ** the implementation that most closely matches the way in which the
4480 ** SQL function is used.  ^A function implementation with a non-negative
4481 ** nArg parameter is a better match than a function implementation with
4482 ** a negative nArg.  ^A function where the preferred text encoding
4483 ** matches the database encoding is a better
4484 ** match than a function where the encoding is different.
4485 ** ^A function where the encoding difference is between UTF16le and UTF16be
4486 ** is a closer match than a function where the encoding difference is
4487 ** between UTF8 and UTF16.
4488 **
4489 ** ^Built-in functions may be overloaded by new application-defined functions.
4490 **
4491 ** ^An application-defined function is permitted to call other
4492 ** SQLite interfaces.  However, such calls must not
4493 ** close the database connection nor finalize or reset the prepared
4494 ** statement in which the function is running.
4495 */
4496 SQLITE_API int sqlite3_create_function(
4497   sqlite3 *db,
4498   const char *zFunctionName,
4499   int nArg,
4500   int eTextRep,
4501   void *pApp,
4502   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4503   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4504   void (*xFinal)(sqlite3_context*)
4505 );
4506 SQLITE_API int sqlite3_create_function16(
4507   sqlite3 *db,
4508   const void *zFunctionName,
4509   int nArg,
4510   int eTextRep,
4511   void *pApp,
4512   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4513   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4514   void (*xFinal)(sqlite3_context*)
4515 );
4516 SQLITE_API int sqlite3_create_function_v2(
4517   sqlite3 *db,
4518   const char *zFunctionName,
4519   int nArg,
4520   int eTextRep,
4521   void *pApp,
4522   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4523   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4524   void (*xFinal)(sqlite3_context*),
4525   void(*xDestroy)(void*)
4526 );
4527
4528 /*
4529 ** CAPI3REF: Text Encodings
4530 **
4531 ** These constant define integer codes that represent the various
4532 ** text encodings supported by SQLite.
4533 */
4534 #define SQLITE_UTF8           1
4535 #define SQLITE_UTF16LE        2
4536 #define SQLITE_UTF16BE        3
4537 #define SQLITE_UTF16          4    /* Use native byte order */
4538 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4539 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4540
4541 /*
4542 ** CAPI3REF: Deprecated Functions
4543 ** DEPRECATED
4544 **
4545 ** These functions are [deprecated].  In order to maintain
4546 ** backwards compatibility with older code, these functions continue
4547 ** to be supported.  However, new applications should avoid
4548 ** the use of these functions.  To help encourage people to avoid
4549 ** using these functions, we are not going to tell you what they do.
4550 */
4551 #ifndef SQLITE_OMIT_DEPRECATED
4552 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4553 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4554 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4555 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4556 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4557 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4558 #endif
4559
4560 /*
4561 ** CAPI3REF: Obtaining SQL Function Parameter Values
4562 **
4563 ** The C-language implementation of SQL functions and aggregates uses
4564 ** this set of interface routines to access the parameter values on
4565 ** the function or aggregate.
4566 **
4567 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4568 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4569 ** define callbacks that implement the SQL functions and aggregates.
4570 ** The 3rd parameter to these callbacks is an array of pointers to
4571 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4572 ** each parameter to the SQL function.  These routines are used to
4573 ** extract values from the [sqlite3_value] objects.
4574 **
4575 ** These routines work only with [protected sqlite3_value] objects.
4576 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4577 ** object results in undefined behavior.
4578 **
4579 ** ^These routines work just like the corresponding [column access functions]
4580 ** except that  these routines take a single [protected sqlite3_value] object
4581 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4582 **
4583 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4584 ** in the native byte-order of the host machine.  ^The
4585 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4586 ** extract UTF-16 strings as big-endian and little-endian respectively.
4587 **
4588 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4589 ** numeric affinity to the value.  This means that an attempt is
4590 ** made to convert the value to an integer or floating point.  If
4591 ** such a conversion is possible without loss of information (in other
4592 ** words, if the value is a string that looks like a number)
4593 ** then the conversion is performed.  Otherwise no conversion occurs.
4594 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4595 **
4596 ** Please pay particular attention to the fact that the pointer returned
4597 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4598 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4599 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4600 ** or [sqlite3_value_text16()].
4601 **
4602 ** These routines must be called from the same thread as
4603 ** the SQL function that supplied the [sqlite3_value*] parameters.
4604 */
4605 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4606 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4607 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4608 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4609 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4610 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4611 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4612 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4613 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4614 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4615 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4616 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4617
4618 /*
4619 ** CAPI3REF: Obtain Aggregate Function Context
4620 **
4621 ** Implementations of aggregate SQL functions use this
4622 ** routine to allocate memory for storing their state.
4623 **
4624 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4625 ** for a particular aggregate function, SQLite
4626 ** allocates N of memory, zeroes out that memory, and returns a pointer
4627 ** to the new memory. ^On second and subsequent calls to
4628 ** sqlite3_aggregate_context() for the same aggregate function instance,
4629 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4630 ** called once for each invocation of the xStep callback and then one
4631 ** last time when the xFinal callback is invoked.  ^(When no rows match
4632 ** an aggregate query, the xStep() callback of the aggregate function
4633 ** implementation is never called and xFinal() is called exactly once.
4634 ** In those cases, sqlite3_aggregate_context() might be called for the
4635 ** first time from within xFinal().)^
4636 **
4637 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4638 ** less than or equal to zero or if a memory allocate error occurs.
4639 **
4640 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4641 ** determined by the N parameter on first successful call.  Changing the
4642 ** value of N in subsequent call to sqlite3_aggregate_context() within
4643 ** the same aggregate function instance will not resize the memory
4644 ** allocation.)^
4645 **
4646 ** ^SQLite automatically frees the memory allocated by
4647 ** sqlite3_aggregate_context() when the aggregate query concludes.
4648 **
4649 ** The first parameter must be a copy of the
4650 ** [sqlite3_context | SQL function context] that is the first parameter
4651 ** to the xStep or xFinal callback routine that implements the aggregate
4652 ** function.
4653 **
4654 ** This routine must be called from the same thread in which
4655 ** the aggregate SQL function is running.
4656 */
4657 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4658
4659 /*
4660 ** CAPI3REF: User Data For Functions
4661 **
4662 ** ^The sqlite3_user_data() interface returns a copy of
4663 ** the pointer that was the pUserData parameter (the 5th parameter)
4664 ** of the [sqlite3_create_function()]
4665 ** and [sqlite3_create_function16()] routines that originally
4666 ** registered the application defined function.
4667 **
4668 ** This routine must be called from the same thread in which
4669 ** the application-defined function is running.
4670 */
4671 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4672
4673 /*
4674 ** CAPI3REF: Database Connection For Functions
4675 **
4676 ** ^The sqlite3_context_db_handle() interface returns a copy of
4677 ** the pointer to the [database connection] (the 1st parameter)
4678 ** of the [sqlite3_create_function()]
4679 ** and [sqlite3_create_function16()] routines that originally
4680 ** registered the application defined function.
4681 */
4682 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4683
4684 /*
4685 ** CAPI3REF: Function Auxiliary Data
4686 **
4687 ** The following two functions may be used by scalar SQL functions to
4688 ** associate metadata with argument values. If the same value is passed to
4689 ** multiple invocations of the same SQL function during query execution, under
4690 ** some circumstances the associated metadata may be preserved. This may
4691 ** be used, for example, to add a regular-expression matching scalar
4692 ** function. The compiled version of the regular expression is stored as
4693 ** metadata associated with the SQL value passed as the regular expression
4694 ** pattern.  The compiled regular expression can be reused on multiple
4695 ** invocations of the same function so that the original pattern string
4696 ** does not need to be recompiled on each invocation.
4697 **
4698 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4699 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4700 ** value to the application-defined function. ^If no metadata has been ever
4701 ** been set for the Nth argument of the function, or if the corresponding
4702 ** function parameter has changed since the meta-data was set,
4703 ** then sqlite3_get_auxdata() returns a NULL pointer.
4704 **
4705 ** ^The sqlite3_set_auxdata() interface saves the metadata
4706 ** pointed to by its 3rd parameter as the metadata for the N-th
4707 ** argument of the application-defined function.  Subsequent
4708 ** calls to sqlite3_get_auxdata() might return this data, if it has
4709 ** not been destroyed.
4710 ** ^If it is not NULL, SQLite will invoke the destructor
4711 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4712 ** the metadata when the corresponding function parameter changes
4713 ** or when the SQL statement completes, whichever comes first.
4714 **
4715 ** SQLite is free to call the destructor and drop metadata on any
4716 ** parameter of any function at any time.  ^The only guarantee is that
4717 ** the destructor will be called before the metadata is dropped.
4718 **
4719 ** ^(In practice, metadata is preserved between function calls for
4720 ** expressions that are constant at compile time. This includes literal
4721 ** values and [parameters].)^
4722 **
4723 ** These routines must be called from the same thread in which
4724 ** the SQL function is running.
4725 */
4726 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4727 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4728
4729
4730 /*
4731 ** CAPI3REF: Constants Defining Special Destructor Behavior
4732 **
4733 ** These are special values for the destructor that is passed in as the
4734 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4735 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4736 ** and will never change.  It does not need to be destroyed.  ^The
4737 ** SQLITE_TRANSIENT value means that the content will likely change in
4738 ** the near future and that SQLite should make its own private copy of
4739 ** the content before returning.
4740 **
4741 ** The typedef is necessary to work around problems in certain
4742 ** C++ compilers.  See ticket #2191.
4743 */
4744 typedef void (*sqlite3_destructor_type)(void*);
4745 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4746 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4747
4748 /*
4749 ** CAPI3REF: Setting The Result Of An SQL Function
4750 **
4751 ** These routines are used by the xFunc or xFinal callbacks that
4752 ** implement SQL functions and aggregates.  See
4753 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4754 ** for additional information.
4755 **
4756 ** These functions work very much like the [parameter binding] family of
4757 ** functions used to bind values to host parameters in prepared statements.
4758 ** Refer to the [SQL parameter] documentation for additional information.
4759 **
4760 ** ^The sqlite3_result_blob() interface sets the result from
4761 ** an application-defined function to be the BLOB whose content is pointed
4762 ** to by the second parameter and which is N bytes long where N is the
4763 ** third parameter.
4764 **
4765 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4766 ** the application-defined function to be a BLOB containing all zero
4767 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4768 **
4769 ** ^The sqlite3_result_double() interface sets the result from
4770 ** an application-defined function to be a floating point value specified
4771 ** by its 2nd argument.
4772 **
4773 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4774 ** cause the implemented SQL function to throw an exception.
4775 ** ^SQLite uses the string pointed to by the
4776 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4777 ** as the text of an error message.  ^SQLite interprets the error
4778 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4779 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4780 ** byte order.  ^If the third parameter to sqlite3_result_error()
4781 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4782 ** message all text up through the first zero character.
4783 ** ^If the third parameter to sqlite3_result_error() or
4784 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4785 ** bytes (not characters) from the 2nd parameter as the error message.
4786 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4787 ** routines make a private copy of the error message text before
4788 ** they return.  Hence, the calling function can deallocate or
4789 ** modify the text after they return without harm.
4790 ** ^The sqlite3_result_error_code() function changes the error code
4791 ** returned by SQLite as a result of an error in a function.  ^By default,
4792 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4793 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4794 **
4795 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4796 ** error indicating that a string or BLOB is too long to represent.
4797 **
4798 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4799 ** error indicating that a memory allocation failed.
4800 **
4801 ** ^The sqlite3_result_int() interface sets the return value
4802 ** of the application-defined function to be the 32-bit signed integer
4803 ** value given in the 2nd argument.
4804 ** ^The sqlite3_result_int64() interface sets the return value
4805 ** of the application-defined function to be the 64-bit signed integer
4806 ** value given in the 2nd argument.
4807 **
4808 ** ^The sqlite3_result_null() interface sets the return value
4809 ** of the application-defined function to be NULL.
4810 **
4811 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4812 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4813 ** set the return value of the application-defined function to be
4814 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4815 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4816 ** ^SQLite takes the text result from the application from
4817 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4818 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4819 ** is negative, then SQLite takes result text from the 2nd parameter
4820 ** through the first zero character.
4821 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4822 ** is non-negative, then as many bytes (not characters) of the text
4823 ** pointed to by the 2nd parameter are taken as the application-defined
4824 ** function result.  If the 3rd parameter is non-negative, then it
4825 ** must be the byte offset into the string where the NUL terminator would
4826 ** appear if the string where NUL terminated.  If any NUL characters occur
4827 ** in the string at a byte offset that is less than the value of the 3rd
4828 ** parameter, then the resulting string will contain embedded NULs and the
4829 ** result of expressions operating on strings with embedded NULs is undefined.
4830 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4831 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4832 ** function as the destructor on the text or BLOB result when it has
4833 ** finished using that result.
4834 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4835 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4836 ** assumes that the text or BLOB result is in constant space and does not
4837 ** copy the content of the parameter nor call a destructor on the content
4838 ** when it has finished using that result.
4839 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4840 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4841 ** then SQLite makes a copy of the result into space obtained from
4842 ** from [sqlite3_malloc()] before it returns.
4843 **
4844 ** ^The sqlite3_result_value() interface sets the result of
4845 ** the application-defined function to be a copy the
4846 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4847 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4848 ** so that the [sqlite3_value] specified in the parameter may change or
4849 ** be deallocated after sqlite3_result_value() returns without harm.
4850 ** ^A [protected sqlite3_value] object may always be used where an
4851 ** [unprotected sqlite3_value] object is required, so either
4852 ** kind of [sqlite3_value] object can be used with this interface.
4853 **
4854 ** If these routines are called from within the different thread
4855 ** than the one containing the application-defined function that received
4856 ** the [sqlite3_context] pointer, the results are undefined.
4857 */
4858 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4859 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4860 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4861 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4862 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4863 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4864 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4865 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4866 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4867 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4868 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4869 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4870 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4871 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4872 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4873 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4874
4875 /*
4876 ** CAPI3REF: Define New Collating Sequences
4877 **
4878 ** ^These functions add, remove, or modify a [collation] associated
4879 ** with the [database connection] specified as the first argument.
4880 **
4881 ** ^The name of the collation is a UTF-8 string
4882 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4883 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4884 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4885 ** considered to be the same name.
4886 **
4887 ** ^(The third argument (eTextRep) must be one of the constants:
4888 ** <ul>
4889 ** <li> [SQLITE_UTF8],
4890 ** <li> [SQLITE_UTF16LE],
4891 ** <li> [SQLITE_UTF16BE],
4892 ** <li> [SQLITE_UTF16], or
4893 ** <li> [SQLITE_UTF16_ALIGNED].
4894 ** </ul>)^
4895 ** ^The eTextRep argument determines the encoding of strings passed
4896 ** to the collating function callback, xCallback.
4897 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4898 ** force strings to be UTF16 with native byte order.
4899 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4900 ** on an even byte address.
4901 **
4902 ** ^The fourth argument, pArg, is an application data pointer that is passed
4903 ** through as the first argument to the collating function callback.
4904 **
4905 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4906 ** ^Multiple collating functions can be registered using the same name but
4907 ** with different eTextRep parameters and SQLite will use whichever
4908 ** function requires the least amount of data transformation.
4909 ** ^If the xCallback argument is NULL then the collating function is
4910 ** deleted.  ^When all collating functions having the same name are deleted,
4911 ** that collation is no longer usable.
4912 **
4913 ** ^The collating function callback is invoked with a copy of the pArg
4914 ** application data pointer and with two strings in the encoding specified
4915 ** by the eTextRep argument.  The collating function must return an
4916 ** integer that is negative, zero, or positive
4917 ** if the first string is less than, equal to, or greater than the second,
4918 ** respectively.  A collating function must always return the same answer
4919 ** given the same inputs.  If two or more collating functions are registered
4920 ** to the same collation name (using different eTextRep values) then all
4921 ** must give an equivalent answer when invoked with equivalent strings.
4922 ** The collating function must obey the following properties for all
4923 ** strings A, B, and C:
4924 **
4925 ** <ol>
4926 ** <li> If A==B then B==A.
4927 ** <li> If A==B and B==C then A==C.
4928 ** <li> If A&lt;B THEN B&gt;A.
4929 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4930 ** </ol>
4931 **
4932 ** If a collating function fails any of the above constraints and that
4933 ** collating function is  registered and used, then the behavior of SQLite
4934 ** is undefined.
4935 **
4936 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4937 ** with the addition that the xDestroy callback is invoked on pArg when
4938 ** the collating function is deleted.
4939 ** ^Collating functions are deleted when they are overridden by later
4940 ** calls to the collation creation functions or when the
4941 ** [database connection] is closed using [sqlite3_close()].
4942 **
4943 ** ^The xDestroy callback is <u>not</u> called if the
4944 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4945 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4946 ** check the return code and dispose of the application data pointer
4947 ** themselves rather than expecting SQLite to deal with it for them.
4948 ** This is different from every other SQLite interface.  The inconsistency
4949 ** is unfortunate but cannot be changed without breaking backwards
4950 ** compatibility.
4951 **
4952 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4953 */
4954 SQLITE_API int sqlite3_create_collation(
4955   sqlite3*,
4956   const char *zName,
4957   int eTextRep,
4958   void *pArg,
4959   int(*xCompare)(void*,int,const void*,int,const void*)
4960 );
4961 SQLITE_API int sqlite3_create_collation_v2(
4962   sqlite3*,
4963   const char *zName,
4964   int eTextRep,
4965   void *pArg,
4966   int(*xCompare)(void*,int,const void*,int,const void*),
4967   void(*xDestroy)(void*)
4968 );
4969 SQLITE_API int sqlite3_create_collation16(
4970   sqlite3*,
4971   const void *zName,
4972   int eTextRep,
4973   void *pArg,
4974   int(*xCompare)(void*,int,const void*,int,const void*)
4975 );
4976
4977 /*
4978 ** CAPI3REF: Collation Needed Callbacks
4979 **
4980 ** ^To avoid having to register all collation sequences before a database
4981 ** can be used, a single callback function may be registered with the
4982 ** [database connection] to be invoked whenever an undefined collation
4983 ** sequence is required.
4984 **
4985 ** ^If the function is registered using the sqlite3_collation_needed() API,
4986 ** then it is passed the names of undefined collation sequences as strings
4987 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4988 ** the names are passed as UTF-16 in machine native byte order.
4989 ** ^A call to either function replaces the existing collation-needed callback.
4990 **
4991 ** ^(When the callback is invoked, the first argument passed is a copy
4992 ** of the second argument to sqlite3_collation_needed() or
4993 ** sqlite3_collation_needed16().  The second argument is the database
4994 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4995 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4996 ** sequence function required.  The fourth parameter is the name of the
4997 ** required collation sequence.)^
4998 **
4999 ** The callback function should register the desired collation using
5000 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5001 ** [sqlite3_create_collation_v2()].
5002 */
5003 SQLITE_API int sqlite3_collation_needed(
5004   sqlite3*,
5005   void*,
5006   void(*)(void*,sqlite3*,int eTextRep,const char*)
5007 );
5008 SQLITE_API int sqlite3_collation_needed16(
5009   sqlite3*,
5010   void*,
5011   void(*)(void*,sqlite3*,int eTextRep,const void*)
5012 );
5013
5014 #ifdef SQLITE_HAS_CODEC
5015 /*
5016 ** Specify the key for an encrypted database.  This routine should be
5017 ** called right after sqlite3_open().
5018 **
5019 ** The code to implement this API is not available in the public release
5020 ** of SQLite.
5021 */
5022 SQLITE_API int sqlite3_key(
5023   sqlite3 *db,                   /* Database to be rekeyed */
5024   const void *pKey, int nKey     /* The key */
5025 );
5026
5027 /*
5028 ** Change the key on an open database.  If the current database is not
5029 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5030 ** database is decrypted.
5031 **
5032 ** The code to implement this API is not available in the public release
5033 ** of SQLite.
5034 */
5035 SQLITE_API int sqlite3_rekey(
5036   sqlite3 *db,                   /* Database to be rekeyed */
5037   const void *pKey, int nKey     /* The new key */
5038 );
5039
5040 /*
5041 ** Specify the activation key for a SEE database.  Unless
5042 ** activated, none of the SEE routines will work.
5043 */
5044 SQLITE_API void sqlite3_activate_see(
5045   const char *zPassPhrase        /* Activation phrase */
5046 );
5047 #endif
5048
5049 #ifdef SQLITE_ENABLE_CEROD
5050 /*
5051 ** Specify the activation key for a CEROD database.  Unless
5052 ** activated, none of the CEROD routines will work.
5053 */
5054 SQLITE_API void sqlite3_activate_cerod(
5055   const char *zPassPhrase        /* Activation phrase */
5056 );
5057 #endif
5058
5059 /*
5060 ** CAPI3REF: Suspend Execution For A Short Time
5061 **
5062 ** The sqlite3_sleep() function causes the current thread to suspend execution
5063 ** for at least a number of milliseconds specified in its parameter.
5064 **
5065 ** If the operating system does not support sleep requests with
5066 ** millisecond time resolution, then the time will be rounded up to
5067 ** the nearest second. The number of milliseconds of sleep actually
5068 ** requested from the operating system is returned.
5069 **
5070 ** ^SQLite implements this interface by calling the xSleep()
5071 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
5072 ** of the default VFS is not implemented correctly, or not implemented at
5073 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5074 ** in the previous paragraphs.
5075 */
5076 SQLITE_API int sqlite3_sleep(int);
5077
5078 /*
5079 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5080 **
5081 ** ^(If this global variable is made to point to a string which is
5082 ** the name of a folder (a.k.a. directory), then all temporary files
5083 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5084 ** will be placed in that directory.)^  ^If this variable
5085 ** is a NULL pointer, then SQLite performs a search for an appropriate
5086 ** temporary file directory.
5087 **
5088 ** It is not safe to read or modify this variable in more than one
5089 ** thread at a time.  It is not safe to read or modify this variable
5090 ** if a [database connection] is being used at the same time in a separate
5091 ** thread.
5092 ** It is intended that this variable be set once
5093 ** as part of process initialization and before any SQLite interface
5094 ** routines have been called and that this variable remain unchanged
5095 ** thereafter.
5096 **
5097 ** ^The [temp_store_directory pragma] may modify this variable and cause
5098 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5099 ** the [temp_store_directory pragma] always assumes that any string
5100 ** that this variable points to is held in memory obtained from
5101 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5102 ** using [sqlite3_free].
5103 ** Hence, if this variable is modified directly, either it should be
5104 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5105 ** or else the use of the [temp_store_directory pragma] should be avoided.
5106 **
5107 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5108 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5109 ** features that require the use of temporary files may fail.  Here is an
5110 ** example of how to do this using C++ with the Windows Runtime:
5111 **
5112 ** <blockquote><pre>
5113 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5114 ** &nbsp;     TemporaryFolder->Path->Data();
5115 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5116 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5117 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5118 ** &nbsp;     NULL, NULL);
5119 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5120 ** </pre></blockquote>
5121 */
5122 SQLITE_API char *sqlite3_temp_directory;
5123
5124 /*
5125 ** CAPI3REF: Name Of The Folder Holding Database Files
5126 **
5127 ** ^(If this global variable is made to point to a string which is
5128 ** the name of a folder (a.k.a. directory), then all database files
5129 ** specified with a relative pathname and created or accessed by
5130 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5131 ** to be relative to that directory.)^ ^If this variable is a NULL
5132 ** pointer, then SQLite assumes that all database files specified
5133 ** with a relative pathname are relative to the current directory
5134 ** for the process.  Only the windows VFS makes use of this global
5135 ** variable; it is ignored by the unix VFS.
5136 **
5137 ** Changing the value of this variable while a database connection is
5138 ** open can result in a corrupt database.
5139 **
5140 ** It is not safe to read or modify this variable in more than one
5141 ** thread at a time.  It is not safe to read or modify this variable
5142 ** if a [database connection] is being used at the same time in a separate
5143 ** thread.
5144 ** It is intended that this variable be set once
5145 ** as part of process initialization and before any SQLite interface
5146 ** routines have been called and that this variable remain unchanged
5147 ** thereafter.
5148 **
5149 ** ^The [data_store_directory pragma] may modify this variable and cause
5150 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5151 ** the [data_store_directory pragma] always assumes that any string
5152 ** that this variable points to is held in memory obtained from
5153 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5154 ** using [sqlite3_free].
5155 ** Hence, if this variable is modified directly, either it should be
5156 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5157 ** or else the use of the [data_store_directory pragma] should be avoided.
5158 */
5159 SQLITE_API char *sqlite3_data_directory;
5160
5161 /*
5162 ** CAPI3REF: Test For Auto-Commit Mode
5163 ** KEYWORDS: {autocommit mode}
5164 **
5165 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5166 ** zero if the given database connection is or is not in autocommit mode,
5167 ** respectively.  ^Autocommit mode is on by default.
5168 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5169 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5170 **
5171 ** If certain kinds of errors occur on a statement within a multi-statement
5172 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5173 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5174 ** transaction might be rolled back automatically.  The only way to
5175 ** find out whether SQLite automatically rolled back the transaction after
5176 ** an error is to use this function.
5177 **
5178 ** If another thread changes the autocommit status of the database
5179 ** connection while this routine is running, then the return value
5180 ** is undefined.
5181 */
5182 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5183
5184 /*
5185 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5186 **
5187 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5188 ** to which a [prepared statement] belongs.  ^The [database connection]
5189 ** returned by sqlite3_db_handle is the same [database connection]
5190 ** that was the first argument
5191 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5192 ** create the statement in the first place.
5193 */
5194 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5195
5196 /*
5197 ** CAPI3REF: Return The Filename For A Database Connection
5198 **
5199 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5200 ** associated with database N of connection D.  ^The main database file
5201 ** has the name "main".  If there is no attached database N on the database
5202 ** connection D, or if database N is a temporary or in-memory database, then
5203 ** a NULL pointer is returned.
5204 **
5205 ** ^The filename returned by this function is the output of the
5206 ** xFullPathname method of the [VFS].  ^In other words, the filename
5207 ** will be an absolute pathname, even if the filename used
5208 ** to open the database originally was a URI or relative pathname.
5209 */
5210 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5211
5212 /*
5213 ** CAPI3REF: Determine if a database is read-only
5214 **
5215 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5216 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5217 ** the name of a database on connection D.
5218 */
5219 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5220
5221 /*
5222 ** CAPI3REF: Find the next prepared statement
5223 **
5224 ** ^This interface returns a pointer to the next [prepared statement] after
5225 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5226 ** then this interface returns a pointer to the first prepared statement
5227 ** associated with the database connection pDb.  ^If no prepared statement
5228 ** satisfies the conditions of this routine, it returns NULL.
5229 **
5230 ** The [database connection] pointer D in a call to
5231 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5232 ** connection and in particular must not be a NULL pointer.
5233 */
5234 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5235
5236 /*
5237 ** CAPI3REF: Commit And Rollback Notification Callbacks
5238 **
5239 ** ^The sqlite3_commit_hook() interface registers a callback
5240 ** function to be invoked whenever a transaction is [COMMIT | committed].
5241 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5242 ** for the same database connection is overridden.
5243 ** ^The sqlite3_rollback_hook() interface registers a callback
5244 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5245 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5246 ** for the same database connection is overridden.
5247 ** ^The pArg argument is passed through to the callback.
5248 ** ^If the callback on a commit hook function returns non-zero,
5249 ** then the commit is converted into a rollback.
5250 **
5251 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5252 ** return the P argument from the previous call of the same function
5253 ** on the same [database connection] D, or NULL for
5254 ** the first call for each function on D.
5255 **
5256 ** The commit and rollback hook callbacks are not reentrant.
5257 ** The callback implementation must not do anything that will modify
5258 ** the database connection that invoked the callback.  Any actions
5259 ** to modify the database connection must be deferred until after the
5260 ** completion of the [sqlite3_step()] call that triggered the commit
5261 ** or rollback hook in the first place.
5262 ** Note that running any other SQL statements, including SELECT statements,
5263 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5264 ** the database connections for the meaning of "modify" in this paragraph.
5265 **
5266 ** ^Registering a NULL function disables the callback.
5267 **
5268 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5269 ** operation is allowed to continue normally.  ^If the commit hook
5270 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5271 ** ^The rollback hook is invoked on a rollback that results from a commit
5272 ** hook returning non-zero, just as it would be with any other rollback.
5273 **
5274 ** ^For the purposes of this API, a transaction is said to have been
5275 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5276 ** an error or constraint causes an implicit rollback to occur.
5277 ** ^The rollback callback is not invoked if a transaction is
5278 ** automatically rolled back because the database connection is closed.
5279 **
5280 ** See also the [sqlite3_update_hook()] interface.
5281 */
5282 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5283 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5284
5285 /*
5286 ** CAPI3REF: Data Change Notification Callbacks
5287 **
5288 ** ^The sqlite3_update_hook() interface registers a callback function
5289 ** with the [database connection] identified by the first argument
5290 ** to be invoked whenever a row is updated, inserted or deleted.
5291 ** ^Any callback set by a previous call to this function
5292 ** for the same database connection is overridden.
5293 **
5294 ** ^The second argument is a pointer to the function to invoke when a
5295 ** row is updated, inserted or deleted.
5296 ** ^The first argument to the callback is a copy of the third argument
5297 ** to sqlite3_update_hook().
5298 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5299 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5300 ** to be invoked.
5301 ** ^The third and fourth arguments to the callback contain pointers to the
5302 ** database and table name containing the affected row.
5303 ** ^The final callback parameter is the [rowid] of the row.
5304 ** ^In the case of an update, this is the [rowid] after the update takes place.
5305 **
5306 ** ^(The update hook is not invoked when internal system tables are
5307 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5308 **
5309 ** ^In the current implementation, the update hook
5310 ** is not invoked when duplication rows are deleted because of an
5311 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5312 ** invoked when rows are deleted using the [truncate optimization].
5313 ** The exceptions defined in this paragraph might change in a future
5314 ** release of SQLite.
5315 **
5316 ** The update hook implementation must not do anything that will modify
5317 ** the database connection that invoked the update hook.  Any actions
5318 ** to modify the database connection must be deferred until after the
5319 ** completion of the [sqlite3_step()] call that triggered the update hook.
5320 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5321 ** database connections for the meaning of "modify" in this paragraph.
5322 **
5323 ** ^The sqlite3_update_hook(D,C,P) function
5324 ** returns the P argument from the previous call
5325 ** on the same [database connection] D, or NULL for
5326 ** the first call on D.
5327 **
5328 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5329 ** interfaces.
5330 */
5331 SQLITE_API void *sqlite3_update_hook(
5332   sqlite3*,
5333   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5334   void*
5335 );
5336
5337 /*
5338 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5339 **
5340 ** ^(This routine enables or disables the sharing of the database cache
5341 ** and schema data structures between [database connection | connections]
5342 ** to the same database. Sharing is enabled if the argument is true
5343 ** and disabled if the argument is false.)^
5344 **
5345 ** ^Cache sharing is enabled and disabled for an entire process.
5346 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5347 ** sharing was enabled or disabled for each thread separately.
5348 **
5349 ** ^(The cache sharing mode set by this interface effects all subsequent
5350 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5351 ** Existing database connections continue use the sharing mode
5352 ** that was in effect at the time they were opened.)^
5353 **
5354 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5355 ** successfully.  An [error code] is returned otherwise.)^
5356 **
5357 ** ^Shared cache is disabled by default. But this might change in
5358 ** future releases of SQLite.  Applications that care about shared
5359 ** cache setting should set it explicitly.
5360 **
5361 ** This interface is threadsafe on processors where writing a
5362 ** 32-bit integer is atomic.
5363 **
5364 ** See Also:  [SQLite Shared-Cache Mode]
5365 */
5366 SQLITE_API int sqlite3_enable_shared_cache(int);
5367
5368 /*
5369 ** CAPI3REF: Attempt To Free Heap Memory
5370 **
5371 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5372 ** of heap memory by deallocating non-essential memory allocations
5373 ** held by the database library.   Memory used to cache database
5374 ** pages to improve performance is an example of non-essential memory.
5375 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5376 ** which might be more or less than the amount requested.
5377 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5378 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5379 **
5380 ** See also: [sqlite3_db_release_memory()]
5381 */
5382 SQLITE_API int sqlite3_release_memory(int);
5383
5384 /*
5385 ** CAPI3REF: Free Memory Used By A Database Connection
5386 **
5387 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5388 ** memory as possible from database connection D. Unlike the
5389 ** [sqlite3_release_memory()] interface, this interface is effect even
5390 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5391 ** omitted.
5392 **
5393 ** See also: [sqlite3_release_memory()]
5394 */
5395 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5396
5397 /*
5398 ** CAPI3REF: Impose A Limit On Heap Size
5399 **
5400 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5401 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5402 ** ^SQLite strives to keep heap memory utilization below the soft heap
5403 ** limit by reducing the number of pages held in the page cache
5404 ** as heap memory usages approaches the limit.
5405 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5406 ** below the limit, it will exceed the limit rather than generate
5407 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5408 ** is advisory only.
5409 **
5410 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5411 ** the soft heap limit prior to the call, or negative in the case of an
5412 ** error.  ^If the argument N is negative
5413 ** then no change is made to the soft heap limit.  Hence, the current
5414 ** size of the soft heap limit can be determined by invoking
5415 ** sqlite3_soft_heap_limit64() with a negative argument.
5416 **
5417 ** ^If the argument N is zero then the soft heap limit is disabled.
5418 **
5419 ** ^(The soft heap limit is not enforced in the current implementation
5420 ** if one or more of following conditions are true:
5421 **
5422 ** <ul>
5423 ** <li> The soft heap limit is set to zero.
5424 ** <li> Memory accounting is disabled using a combination of the
5425 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5426 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5427 ** <li> An alternative page cache implementation is specified using
5428 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5429 ** <li> The page cache allocates from its own memory pool supplied
5430 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5431 **      from the heap.
5432 ** </ul>)^
5433 **
5434 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5435 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5436 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5437 ** the soft heap limit is enforced on every memory allocation.  Without
5438 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5439 ** when memory is allocated by the page cache.  Testing suggests that because
5440 ** the page cache is the predominate memory user in SQLite, most
5441 ** applications will achieve adequate soft heap limit enforcement without
5442 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5443 **
5444 ** The circumstances under which SQLite will enforce the soft heap limit may
5445 ** changes in future releases of SQLite.
5446 */
5447 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5448
5449 /*
5450 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5451 ** DEPRECATED
5452 **
5453 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5454 ** interface.  This routine is provided for historical compatibility
5455 ** only.  All new applications should use the
5456 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5457 */
5458 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5459
5460
5461 /*
5462 ** CAPI3REF: Extract Metadata About A Column Of A Table
5463 **
5464 ** ^This routine returns metadata about a specific column of a specific
5465 ** database table accessible using the [database connection] handle
5466 ** passed as the first function argument.
5467 **
5468 ** ^The column is identified by the second, third and fourth parameters to
5469 ** this function. ^The second parameter is either the name of the database
5470 ** (i.e. "main", "temp", or an attached database) containing the specified
5471 ** table or NULL. ^If it is NULL, then all attached databases are searched
5472 ** for the table using the same algorithm used by the database engine to
5473 ** resolve unqualified table references.
5474 **
5475 ** ^The third and fourth parameters to this function are the table and column
5476 ** name of the desired column, respectively. Neither of these parameters
5477 ** may be NULL.
5478 **
5479 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5480 ** and subsequent parameters to this function. ^Any of these arguments may be
5481 ** NULL, in which case the corresponding element of metadata is omitted.
5482 **
5483 ** ^(<blockquote>
5484 ** <table border="1">
5485 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5486 **
5487 ** <tr><td> 5th <td> const char* <td> Data type
5488 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5489 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5490 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5491 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5492 ** </table>
5493 ** </blockquote>)^
5494 **
5495 ** ^The memory pointed to by the character pointers returned for the
5496 ** declaration type and collation sequence is valid only until the next
5497 ** call to any SQLite API function.
5498 **
5499 ** ^If the specified table is actually a view, an [error code] is returned.
5500 **
5501 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5502 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5503 ** parameters are set for the explicitly declared column. ^(If there is no
5504 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5505 ** parameters are set as follows:
5506 **
5507 ** <pre>
5508 **     data type: "INTEGER"
5509 **     collation sequence: "BINARY"
5510 **     not null: 0
5511 **     primary key: 1
5512 **     auto increment: 0
5513 ** </pre>)^
5514 **
5515 ** ^(This function may load one or more schemas from database files. If an
5516 ** error occurs during this process, or if the requested table or column
5517 ** cannot be found, an [error code] is returned and an error message left
5518 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5519 **
5520 ** ^This API is only available if the library was compiled with the
5521 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5522 */
5523 SQLITE_API int sqlite3_table_column_metadata(
5524   sqlite3 *db,                /* Connection handle */
5525   const char *zDbName,        /* Database name or NULL */
5526   const char *zTableName,     /* Table name */
5527   const char *zColumnName,    /* Column name */
5528   char const **pzDataType,    /* OUTPUT: Declared data type */
5529   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5530   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5531   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5532   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5533 );
5534
5535 /*
5536 ** CAPI3REF: Load An Extension
5537 **
5538 ** ^This interface loads an SQLite extension library from the named file.
5539 **
5540 ** ^The sqlite3_load_extension() interface attempts to load an
5541 ** SQLite extension library contained in the file zFile.
5542 **
5543 ** ^The entry point is zProc.
5544 ** ^zProc may be 0, in which case the name of the entry point
5545 ** defaults to "sqlite3_extension_init".
5546 ** ^The sqlite3_load_extension() interface returns
5547 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5548 ** ^If an error occurs and pzErrMsg is not 0, then the
5549 ** [sqlite3_load_extension()] interface shall attempt to
5550 ** fill *pzErrMsg with error message text stored in memory
5551 ** obtained from [sqlite3_malloc()]. The calling function
5552 ** should free this memory by calling [sqlite3_free()].
5553 **
5554 ** ^Extension loading must be enabled using
5555 ** [sqlite3_enable_load_extension()] prior to calling this API,
5556 ** otherwise an error will be returned.
5557 **
5558 ** See also the [load_extension() SQL function].
5559 */
5560 SQLITE_API int sqlite3_load_extension(
5561   sqlite3 *db,          /* Load the extension into this database connection */
5562   const char *zFile,    /* Name of the shared library containing extension */
5563   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5564   char **pzErrMsg       /* Put error message here if not 0 */
5565 );
5566
5567 /*
5568 ** CAPI3REF: Enable Or Disable Extension Loading
5569 **
5570 ** ^So as not to open security holes in older applications that are
5571 ** unprepared to deal with extension loading, and as a means of disabling
5572 ** extension loading while evaluating user-entered SQL, the following API
5573 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5574 **
5575 ** ^Extension loading is off by default. See ticket #1863.
5576 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5577 ** to turn extension loading on and call it with onoff==0 to turn
5578 ** it back off again.
5579 */
5580 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5581
5582 /*
5583 ** CAPI3REF: Automatically Load Statically Linked Extensions
5584 **
5585 ** ^This interface causes the xEntryPoint() function to be invoked for
5586 ** each new [database connection] that is created.  The idea here is that
5587 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5588 ** that is to be automatically loaded into all new database connections.
5589 **
5590 ** ^(Even though the function prototype shows that xEntryPoint() takes
5591 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5592 ** arguments and expects and integer result as if the signature of the
5593 ** entry point where as follows:
5594 **
5595 ** <blockquote><pre>
5596 ** &nbsp;  int xEntryPoint(
5597 ** &nbsp;    sqlite3 *db,
5598 ** &nbsp;    const char **pzErrMsg,
5599 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5600 ** &nbsp;  );
5601 ** </pre></blockquote>)^
5602 **
5603 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5604 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5605 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5606 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5607 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5608 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5609 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5610 **
5611 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5612 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5613 ** will be called more than once for each database connection that is opened.
5614 **
5615 ** See also: [sqlite3_reset_auto_extension()].
5616 */
5617 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5618
5619 /*
5620 ** CAPI3REF: Reset Automatic Extension Loading
5621 **
5622 ** ^This interface disables all automatic extensions previously
5623 ** registered using [sqlite3_auto_extension()].
5624 */
5625 SQLITE_API void sqlite3_reset_auto_extension(void);
5626
5627 /*
5628 ** The interface to the virtual-table mechanism is currently considered
5629 ** to be experimental.  The interface might change in incompatible ways.
5630 ** If this is a problem for you, do not use the interface at this time.
5631 **
5632 ** When the virtual-table mechanism stabilizes, we will declare the
5633 ** interface fixed, support it indefinitely, and remove this comment.
5634 */
5635
5636 /*
5637 ** Structures used by the virtual table interface
5638 */
5639 typedef struct sqlite3_vtab sqlite3_vtab;
5640 typedef struct sqlite3_index_info sqlite3_index_info;
5641 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5642 typedef struct sqlite3_module sqlite3_module;
5643
5644 /*
5645 ** CAPI3REF: Virtual Table Object
5646 ** KEYWORDS: sqlite3_module {virtual table module}
5647 **
5648 ** This structure, sometimes called a "virtual table module",
5649 ** defines the implementation of a [virtual tables].
5650 ** This structure consists mostly of methods for the module.
5651 **
5652 ** ^A virtual table module is created by filling in a persistent
5653 ** instance of this structure and passing a pointer to that instance
5654 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5655 ** ^The registration remains valid until it is replaced by a different
5656 ** module or until the [database connection] closes.  The content
5657 ** of this structure must not change while it is registered with
5658 ** any database connection.
5659 */
5660 struct sqlite3_module {
5661   int iVersion;
5662   int (*xCreate)(sqlite3*, void *pAux,
5663                int argc, const char *const*argv,
5664                sqlite3_vtab **ppVTab, char**);
5665   int (*xConnect)(sqlite3*, void *pAux,
5666                int argc, const char *const*argv,
5667                sqlite3_vtab **ppVTab, char**);
5668   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5669   int (*xDisconnect)(sqlite3_vtab *pVTab);
5670   int (*xDestroy)(sqlite3_vtab *pVTab);
5671   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5672   int (*xClose)(sqlite3_vtab_cursor*);
5673   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5674                 int argc, sqlite3_value **argv);
5675   int (*xNext)(sqlite3_vtab_cursor*);
5676   int (*xEof)(sqlite3_vtab_cursor*);
5677   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5678   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5679   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5680   int (*xBegin)(sqlite3_vtab *pVTab);
5681   int (*xSync)(sqlite3_vtab *pVTab);
5682   int (*xCommit)(sqlite3_vtab *pVTab);
5683   int (*xRollback)(sqlite3_vtab *pVTab);
5684   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5685                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5686                        void **ppArg);
5687   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5688   /* The methods above are in version 1 of the sqlite_module object. Those
5689   ** below are for version 2 and greater. */
5690   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5691   int (*xRelease)(sqlite3_vtab *pVTab, int);
5692   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5693 };
5694
5695 /*
5696 ** CAPI3REF: Virtual Table Indexing Information
5697 ** KEYWORDS: sqlite3_index_info
5698 **
5699 ** The sqlite3_index_info structure and its substructures is used as part
5700 ** of the [virtual table] interface to
5701 ** pass information into and receive the reply from the [xBestIndex]
5702 ** method of a [virtual table module].  The fields under **Inputs** are the
5703 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5704 ** results into the **Outputs** fields.
5705 **
5706 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5707 **
5708 ** <blockquote>column OP expr</blockquote>
5709 **
5710 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5711 ** stored in aConstraint[].op using one of the
5712 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5713 ** ^(The index of the column is stored in
5714 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5715 ** expr on the right-hand side can be evaluated (and thus the constraint
5716 ** is usable) and false if it cannot.)^
5717 **
5718 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5719 ** and makes other simplifications to the WHERE clause in an attempt to
5720 ** get as many WHERE clause terms into the form shown above as possible.
5721 ** ^The aConstraint[] array only reports WHERE clause terms that are
5722 ** relevant to the particular virtual table being queried.
5723 **
5724 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5725 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5726 **
5727 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5728 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5729 ** the right-hand side of the corresponding aConstraint[] is evaluated
5730 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5731 ** is true, then the constraint is assumed to be fully handled by the
5732 ** virtual table and is not checked again by SQLite.)^
5733 **
5734 ** ^The idxNum and idxPtr values are recorded and passed into the
5735 ** [xFilter] method.
5736 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5737 ** needToFreeIdxPtr is true.
5738 **
5739 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5740 ** the correct order to satisfy the ORDER BY clause so that no separate
5741 ** sorting step is required.
5742 **
5743 ** ^The estimatedCost value is an estimate of the cost of doing the
5744 ** particular lookup.  A full scan of a table with N entries should have
5745 ** a cost of N.  A binary search of a table of N entries should have a
5746 ** cost of approximately log(N).
5747 */
5748 struct sqlite3_index_info {
5749   /* Inputs */
5750   int nConstraint;           /* Number of entries in aConstraint */
5751   struct sqlite3_index_constraint {
5752      int iColumn;              /* Column on left-hand side of constraint */
5753      unsigned char op;         /* Constraint operator */
5754      unsigned char usable;     /* True if this constraint is usable */
5755      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5756   } *aConstraint;            /* Table of WHERE clause constraints */
5757   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5758   struct sqlite3_index_orderby {
5759      int iColumn;              /* Column number */
5760      unsigned char desc;       /* True for DESC.  False for ASC. */
5761   } *aOrderBy;               /* The ORDER BY clause */
5762   /* Outputs */
5763   struct sqlite3_index_constraint_usage {
5764     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5765     unsigned char omit;      /* Do not code a test for this constraint */
5766   } *aConstraintUsage;
5767   int idxNum;                /* Number used to identify the index */
5768   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5769   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5770   int orderByConsumed;       /* True if output is already ordered */
5771   double estimatedCost;      /* Estimated cost of using this index */
5772 };
5773
5774 /*
5775 ** CAPI3REF: Virtual Table Constraint Operator Codes
5776 **
5777 ** These macros defined the allowed values for the
5778 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5779 ** an operator that is part of a constraint term in the wHERE clause of
5780 ** a query that uses a [virtual table].
5781 */
5782 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5783 #define SQLITE_INDEX_CONSTRAINT_GT    4
5784 #define SQLITE_INDEX_CONSTRAINT_LE    8
5785 #define SQLITE_INDEX_CONSTRAINT_LT    16
5786 #define SQLITE_INDEX_CONSTRAINT_GE    32
5787 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5788
5789 /*
5790 ** CAPI3REF: Register A Virtual Table Implementation
5791 **
5792 ** ^These routines are used to register a new [virtual table module] name.
5793 ** ^Module names must be registered before
5794 ** creating a new [virtual table] using the module and before using a
5795 ** preexisting [virtual table] for the module.
5796 **
5797 ** ^The module name is registered on the [database connection] specified
5798 ** by the first parameter.  ^The name of the module is given by the
5799 ** second parameter.  ^The third parameter is a pointer to
5800 ** the implementation of the [virtual table module].   ^The fourth
5801 ** parameter is an arbitrary client data pointer that is passed through
5802 ** into the [xCreate] and [xConnect] methods of the virtual table module
5803 ** when a new virtual table is be being created or reinitialized.
5804 **
5805 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5806 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5807 ** invoke the destructor function (if it is not NULL) when SQLite
5808 ** no longer needs the pClientData pointer.  ^The destructor will also
5809 ** be invoked if the call to sqlite3_create_module_v2() fails.
5810 ** ^The sqlite3_create_module()
5811 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5812 ** destructor.
5813 */
5814 SQLITE_API int sqlite3_create_module(
5815   sqlite3 *db,               /* SQLite connection to register module with */
5816   const char *zName,         /* Name of the module */
5817   const sqlite3_module *p,   /* Methods for the module */
5818   void *pClientData          /* Client data for xCreate/xConnect */
5819 );
5820 SQLITE_API int sqlite3_create_module_v2(
5821   sqlite3 *db,               /* SQLite connection to register module with */
5822   const char *zName,         /* Name of the module */
5823   const sqlite3_module *p,   /* Methods for the module */
5824   void *pClientData,         /* Client data for xCreate/xConnect */
5825   void(*xDestroy)(void*)     /* Module destructor function */
5826 );
5827
5828 /*
5829 ** CAPI3REF: Virtual Table Instance Object
5830 ** KEYWORDS: sqlite3_vtab
5831 **
5832 ** Every [virtual table module] implementation uses a subclass
5833 ** of this object to describe a particular instance
5834 ** of the [virtual table].  Each subclass will
5835 ** be tailored to the specific needs of the module implementation.
5836 ** The purpose of this superclass is to define certain fields that are
5837 ** common to all module implementations.
5838 **
5839 ** ^Virtual tables methods can set an error message by assigning a
5840 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5841 ** take care that any prior string is freed by a call to [sqlite3_free()]
5842 ** prior to assigning a new string to zErrMsg.  ^After the error message
5843 ** is delivered up to the client application, the string will be automatically
5844 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5845 */
5846 struct sqlite3_vtab {
5847   const sqlite3_module *pModule;  /* The module for this virtual table */
5848   int nRef;                       /* NO LONGER USED */
5849   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5850   /* Virtual table implementations will typically add additional fields */
5851 };
5852
5853 /*
5854 ** CAPI3REF: Virtual Table Cursor Object
5855 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5856 **
5857 ** Every [virtual table module] implementation uses a subclass of the
5858 ** following structure to describe cursors that point into the
5859 ** [virtual table] and are used
5860 ** to loop through the virtual table.  Cursors are created using the
5861 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5862 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5863 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5864 ** of the module.  Each module implementation will define
5865 ** the content of a cursor structure to suit its own needs.
5866 **
5867 ** This superclass exists in order to define fields of the cursor that
5868 ** are common to all implementations.
5869 */
5870 struct sqlite3_vtab_cursor {
5871   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5872   /* Virtual table implementations will typically add additional fields */
5873 };
5874
5875 /*
5876 ** CAPI3REF: Declare The Schema Of A Virtual Table
5877 **
5878 ** ^The [xCreate] and [xConnect] methods of a
5879 ** [virtual table module] call this interface
5880 ** to declare the format (the names and datatypes of the columns) of
5881 ** the virtual tables they implement.
5882 */
5883 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5884
5885 /*
5886 ** CAPI3REF: Overload A Function For A Virtual Table
5887 **
5888 ** ^(Virtual tables can provide alternative implementations of functions
5889 ** using the [xFindFunction] method of the [virtual table module].
5890 ** But global versions of those functions
5891 ** must exist in order to be overloaded.)^
5892 **
5893 ** ^(This API makes sure a global version of a function with a particular
5894 ** name and number of parameters exists.  If no such function exists
5895 ** before this API is called, a new function is created.)^  ^The implementation
5896 ** of the new function always causes an exception to be thrown.  So
5897 ** the new function is not good for anything by itself.  Its only
5898 ** purpose is to be a placeholder function that can be overloaded
5899 ** by a [virtual table].
5900 */
5901 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5902
5903 /*
5904 ** The interface to the virtual-table mechanism defined above (back up
5905 ** to a comment remarkably similar to this one) is currently considered
5906 ** to be experimental.  The interface might change in incompatible ways.
5907 ** If this is a problem for you, do not use the interface at this time.
5908 **
5909 ** When the virtual-table mechanism stabilizes, we will declare the
5910 ** interface fixed, support it indefinitely, and remove this comment.
5911 */
5912
5913 /*
5914 ** CAPI3REF: A Handle To An Open BLOB
5915 ** KEYWORDS: {BLOB handle} {BLOB handles}
5916 **
5917 ** An instance of this object represents an open BLOB on which
5918 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5919 ** ^Objects of this type are created by [sqlite3_blob_open()]
5920 ** and destroyed by [sqlite3_blob_close()].
5921 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5922 ** can be used to read or write small subsections of the BLOB.
5923 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5924 */
5925 typedef struct sqlite3_blob sqlite3_blob;
5926
5927 /*
5928 ** CAPI3REF: Open A BLOB For Incremental I/O
5929 **
5930 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5931 ** in row iRow, column zColumn, table zTable in database zDb;
5932 ** in other words, the same BLOB that would be selected by:
5933 **
5934 ** <pre>
5935 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5936 ** </pre>)^
5937 **
5938 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5939 ** and write access. ^If it is zero, the BLOB is opened for read access.
5940 ** ^It is not possible to open a column that is part of an index or primary
5941 ** key for writing. ^If [foreign key constraints] are enabled, it is
5942 ** not possible to open a column that is part of a [child key] for writing.
5943 **
5944 ** ^Note that the database name is not the filename that contains
5945 ** the database but rather the symbolic name of the database that
5946 ** appears after the AS keyword when the database is connected using [ATTACH].
5947 ** ^For the main database file, the database name is "main".
5948 ** ^For TEMP tables, the database name is "temp".
5949 **
5950 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5951 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5952 ** to be a null pointer.)^
5953 ** ^This function sets the [database connection] error code and message
5954 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5955 ** functions. ^Note that the *ppBlob variable is always initialized in a
5956 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5957 ** regardless of the success or failure of this routine.
5958 **
5959 ** ^(If the row that a BLOB handle points to is modified by an
5960 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5961 ** then the BLOB handle is marked as "expired".
5962 ** This is true if any column of the row is changed, even a column
5963 ** other than the one the BLOB handle is open on.)^
5964 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5965 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5966 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5967 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5968 ** commit if the transaction continues to completion.)^
5969 **
5970 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5971 ** the opened blob.  ^The size of a blob may not be changed by this
5972 ** interface.  Use the [UPDATE] SQL command to change the size of a
5973 ** blob.
5974 **
5975 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5976 ** and the built-in [zeroblob] SQL function can be used, if desired,
5977 ** to create an empty, zero-filled blob in which to read or write using
5978 ** this interface.
5979 **
5980 ** To avoid a resource leak, every open [BLOB handle] should eventually
5981 ** be released by a call to [sqlite3_blob_close()].
5982 */
5983 SQLITE_API int sqlite3_blob_open(
5984   sqlite3*,
5985   const char *zDb,
5986   const char *zTable,
5987   const char *zColumn,
5988   sqlite3_int64 iRow,
5989   int flags,
5990   sqlite3_blob **ppBlob
5991 );
5992
5993 /*
5994 ** CAPI3REF: Move a BLOB Handle to a New Row
5995 **
5996 ** ^This function is used to move an existing blob handle so that it points
5997 ** to a different row of the same database table. ^The new row is identified
5998 ** by the rowid value passed as the second argument. Only the row can be
5999 ** changed. ^The database, table and column on which the blob handle is open
6000 ** remain the same. Moving an existing blob handle to a new row can be
6001 ** faster than closing the existing handle and opening a new one.
6002 **
6003 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6004 ** it must exist and there must be either a blob or text value stored in
6005 ** the nominated column.)^ ^If the new row is not present in the table, or if
6006 ** it does not contain a blob or text value, or if another error occurs, an
6007 ** SQLite error code is returned and the blob handle is considered aborted.
6008 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6009 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6010 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6011 ** always returns zero.
6012 **
6013 ** ^This function sets the database handle error code and message.
6014 */
6015 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6016
6017 /*
6018 ** CAPI3REF: Close A BLOB Handle
6019 **
6020 ** ^Closes an open [BLOB handle].
6021 **
6022 ** ^Closing a BLOB shall cause the current transaction to commit
6023 ** if there are no other BLOBs, no pending prepared statements, and the
6024 ** database connection is in [autocommit mode].
6025 ** ^If any writes were made to the BLOB, they might be held in cache
6026 ** until the close operation if they will fit.
6027 **
6028 ** ^(Closing the BLOB often forces the changes
6029 ** out to disk and so if any I/O errors occur, they will likely occur
6030 ** at the time when the BLOB is closed.  Any errors that occur during
6031 ** closing are reported as a non-zero return value.)^
6032 **
6033 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
6034 ** an error code, the BLOB is still closed.)^
6035 **
6036 ** ^Calling this routine with a null pointer (such as would be returned
6037 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
6038 */
6039 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6040
6041 /*
6042 ** CAPI3REF: Return The Size Of An Open BLOB
6043 **
6044 ** ^Returns the size in bytes of the BLOB accessible via the
6045 ** successfully opened [BLOB handle] in its only argument.  ^The
6046 ** incremental blob I/O routines can only read or overwriting existing
6047 ** blob content; they cannot change the size of a blob.
6048 **
6049 ** This routine only works on a [BLOB handle] which has been created
6050 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6051 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6052 ** to this routine results in undefined and probably undesirable behavior.
6053 */
6054 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6055
6056 /*
6057 ** CAPI3REF: Read Data From A BLOB Incrementally
6058 **
6059 ** ^(This function is used to read data from an open [BLOB handle] into a
6060 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6061 ** from the open BLOB, starting at offset iOffset.)^
6062 **
6063 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6064 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6065 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6066 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6067 ** can be determined using the [sqlite3_blob_bytes()] interface.
6068 **
6069 ** ^An attempt to read from an expired [BLOB handle] fails with an
6070 ** error code of [SQLITE_ABORT].
6071 **
6072 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6073 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6074 **
6075 ** This routine only works on a [BLOB handle] which has been created
6076 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6077 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6078 ** to this routine results in undefined and probably undesirable behavior.
6079 **
6080 ** See also: [sqlite3_blob_write()].
6081 */
6082 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6083
6084 /*
6085 ** CAPI3REF: Write Data Into A BLOB Incrementally
6086 **
6087 ** ^This function is used to write data into an open [BLOB handle] from a
6088 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
6089 ** into the open BLOB, starting at offset iOffset.
6090 **
6091 ** ^If the [BLOB handle] passed as the first argument was not opened for
6092 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6093 ** this function returns [SQLITE_READONLY].
6094 **
6095 ** ^This function may only modify the contents of the BLOB; it is
6096 ** not possible to increase the size of a BLOB using this API.
6097 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6098 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
6099 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6100 ** The size of the BLOB (and hence the maximum value of N+iOffset)
6101 ** can be determined using the [sqlite3_blob_bytes()] interface.
6102 **
6103 ** ^An attempt to write to an expired [BLOB handle] fails with an
6104 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6105 ** before the [BLOB handle] expired are not rolled back by the
6106 ** expiration of the handle, though of course those changes might
6107 ** have been overwritten by the statement that expired the BLOB handle
6108 ** or by other independent statements.
6109 **
6110 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6111 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
6112 **
6113 ** This routine only works on a [BLOB handle] which has been created
6114 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6115 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6116 ** to this routine results in undefined and probably undesirable behavior.
6117 **
6118 ** See also: [sqlite3_blob_read()].
6119 */
6120 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6121
6122 /*
6123 ** CAPI3REF: Virtual File System Objects
6124 **
6125 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6126 ** that SQLite uses to interact
6127 ** with the underlying operating system.  Most SQLite builds come with a
6128 ** single default VFS that is appropriate for the host computer.
6129 ** New VFSes can be registered and existing VFSes can be unregistered.
6130 ** The following interfaces are provided.
6131 **
6132 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6133 ** ^Names are case sensitive.
6134 ** ^Names are zero-terminated UTF-8 strings.
6135 ** ^If there is no match, a NULL pointer is returned.
6136 ** ^If zVfsName is NULL then the default VFS is returned.
6137 **
6138 ** ^New VFSes are registered with sqlite3_vfs_register().
6139 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6140 ** ^The same VFS can be registered multiple times without injury.
6141 ** ^To make an existing VFS into the default VFS, register it again
6142 ** with the makeDflt flag set.  If two different VFSes with the
6143 ** same name are registered, the behavior is undefined.  If a
6144 ** VFS is registered with a name that is NULL or an empty string,
6145 ** then the behavior is undefined.
6146 **
6147 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6148 ** ^(If the default VFS is unregistered, another VFS is chosen as
6149 ** the default.  The choice for the new VFS is arbitrary.)^
6150 */
6151 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6152 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6153 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6154
6155 /*
6156 ** CAPI3REF: Mutexes
6157 **
6158 ** The SQLite core uses these routines for thread
6159 ** synchronization. Though they are intended for internal
6160 ** use by SQLite, code that links against SQLite is
6161 ** permitted to use any of these routines.
6162 **
6163 ** The SQLite source code contains multiple implementations
6164 ** of these mutex routines.  An appropriate implementation
6165 ** is selected automatically at compile-time.  ^(The following
6166 ** implementations are available in the SQLite core:
6167 **
6168 ** <ul>
6169 ** <li>   SQLITE_MUTEX_PTHREADS
6170 ** <li>   SQLITE_MUTEX_W32
6171 ** <li>   SQLITE_MUTEX_NOOP
6172 ** </ul>)^
6173 **
6174 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6175 ** that does no real locking and is appropriate for use in
6176 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
6177 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6178 ** and Windows.
6179 **
6180 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6181 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6182 ** implementation is included with the library. In this case the
6183 ** application must supply a custom mutex implementation using the
6184 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6185 ** before calling sqlite3_initialize() or any other public sqlite3_
6186 ** function that calls sqlite3_initialize().)^
6187 **
6188 ** ^The sqlite3_mutex_alloc() routine allocates a new
6189 ** mutex and returns a pointer to it. ^If it returns NULL
6190 ** that means that a mutex could not be allocated.  ^SQLite
6191 ** will unwind its stack and return an error.  ^(The argument
6192 ** to sqlite3_mutex_alloc() is one of these integer constants:
6193 **
6194 ** <ul>
6195 ** <li>  SQLITE_MUTEX_FAST
6196 ** <li>  SQLITE_MUTEX_RECURSIVE
6197 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6198 ** <li>  SQLITE_MUTEX_STATIC_MEM
6199 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6200 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6201 ** <li>  SQLITE_MUTEX_STATIC_LRU
6202 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6203 ** </ul>)^
6204 **
6205 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6206 ** cause sqlite3_mutex_alloc() to create
6207 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6208 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6209 ** The mutex implementation does not need to make a distinction
6210 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6211 ** not want to.  ^SQLite will only request a recursive mutex in
6212 ** cases where it really needs one.  ^If a faster non-recursive mutex
6213 ** implementation is available on the host platform, the mutex subsystem
6214 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6215 **
6216 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6217 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6218 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
6219 ** used by the current version of SQLite.  Future versions of SQLite
6220 ** may add additional static mutexes.  Static mutexes are for internal
6221 ** use by SQLite only.  Applications that use SQLite mutexes should
6222 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6223 ** SQLITE_MUTEX_RECURSIVE.
6224 **
6225 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6226 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6227 ** returns a different mutex on every call.  ^But for the static
6228 ** mutex types, the same mutex is returned on every call that has
6229 ** the same type number.
6230 **
6231 ** ^The sqlite3_mutex_free() routine deallocates a previously
6232 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6233 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6234 ** use when they are deallocated.  Attempting to deallocate a static
6235 ** mutex results in undefined behavior.  ^SQLite never deallocates
6236 ** a static mutex.
6237 **
6238 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6239 ** to enter a mutex.  ^If another thread is already within the mutex,
6240 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6241 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6242 ** upon successful entry.  ^(Mutexes created using
6243 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6244 ** In such cases the,
6245 ** mutex must be exited an equal number of times before another thread
6246 ** can enter.)^  ^(If the same thread tries to enter any other
6247 ** kind of mutex more than once, the behavior is undefined.
6248 ** SQLite will never exhibit
6249 ** such behavior in its own use of mutexes.)^
6250 **
6251 ** ^(Some systems (for example, Windows 95) do not support the operation
6252 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6253 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
6254 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6255 **
6256 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6257 ** previously entered by the same thread.   ^(The behavior
6258 ** is undefined if the mutex is not currently entered by the
6259 ** calling thread or is not currently allocated.  SQLite will
6260 ** never do either.)^
6261 **
6262 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6263 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6264 ** behave as no-ops.
6265 **
6266 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6267 */
6268 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6269 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6270 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6271 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6272 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6273
6274 /*
6275 ** CAPI3REF: Mutex Methods Object
6276 **
6277 ** An instance of this structure defines the low-level routines
6278 ** used to allocate and use mutexes.
6279 **
6280 ** Usually, the default mutex implementations provided by SQLite are
6281 ** sufficient, however the user has the option of substituting a custom
6282 ** implementation for specialized deployments or systems for which SQLite
6283 ** does not provide a suitable implementation. In this case, the user
6284 ** creates and populates an instance of this structure to pass
6285 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6286 ** Additionally, an instance of this structure can be used as an
6287 ** output variable when querying the system for the current mutex
6288 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6289 **
6290 ** ^The xMutexInit method defined by this structure is invoked as
6291 ** part of system initialization by the sqlite3_initialize() function.
6292 ** ^The xMutexInit routine is called by SQLite exactly once for each
6293 ** effective call to [sqlite3_initialize()].
6294 **
6295 ** ^The xMutexEnd method defined by this structure is invoked as
6296 ** part of system shutdown by the sqlite3_shutdown() function. The
6297 ** implementation of this method is expected to release all outstanding
6298 ** resources obtained by the mutex methods implementation, especially
6299 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6300 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6301 **
6302 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6303 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6304 ** xMutexNotheld) implement the following interfaces (respectively):
6305 **
6306 ** <ul>
6307 **   <li>  [sqlite3_mutex_alloc()] </li>
6308 **   <li>  [sqlite3_mutex_free()] </li>
6309 **   <li>  [sqlite3_mutex_enter()] </li>
6310 **   <li>  [sqlite3_mutex_try()] </li>
6311 **   <li>  [sqlite3_mutex_leave()] </li>
6312 **   <li>  [sqlite3_mutex_held()] </li>
6313 **   <li>  [sqlite3_mutex_notheld()] </li>
6314 ** </ul>)^
6315 **
6316 ** The only difference is that the public sqlite3_XXX functions enumerated
6317 ** above silently ignore any invocations that pass a NULL pointer instead
6318 ** of a valid mutex handle. The implementations of the methods defined
6319 ** by this structure are not required to handle this case, the results
6320 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6321 ** (i.e. it is acceptable to provide an implementation that segfaults if
6322 ** it is passed a NULL pointer).
6323 **
6324 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6325 ** invoke xMutexInit() multiple times within the same process and without
6326 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6327 ** xMutexInit() must be no-ops.
6328 **
6329 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6330 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6331 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6332 ** memory allocation for a fast or recursive mutex.
6333 **
6334 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6335 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6336 ** If xMutexInit fails in any way, it is expected to clean up after itself
6337 ** prior to returning.
6338 */
6339 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6340 struct sqlite3_mutex_methods {
6341   int (*xMutexInit)(void);
6342   int (*xMutexEnd)(void);
6343   sqlite3_mutex *(*xMutexAlloc)(int);
6344   void (*xMutexFree)(sqlite3_mutex *);
6345   void (*xMutexEnter)(sqlite3_mutex *);
6346   int (*xMutexTry)(sqlite3_mutex *);
6347   void (*xMutexLeave)(sqlite3_mutex *);
6348   int (*xMutexHeld)(sqlite3_mutex *);
6349   int (*xMutexNotheld)(sqlite3_mutex *);
6350 };
6351
6352 /*
6353 ** CAPI3REF: Mutex Verification Routines
6354 **
6355 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6356 ** are intended for use inside assert() statements.  ^The SQLite core
6357 ** never uses these routines except inside an assert() and applications
6358 ** are advised to follow the lead of the core.  ^The SQLite core only
6359 ** provides implementations for these routines when it is compiled
6360 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6361 ** are only required to provide these routines if SQLITE_DEBUG is
6362 ** defined and if NDEBUG is not defined.
6363 **
6364 ** ^These routines should return true if the mutex in their argument
6365 ** is held or not held, respectively, by the calling thread.
6366 **
6367 ** ^The implementation is not required to provide versions of these
6368 ** routines that actually work. If the implementation does not provide working
6369 ** versions of these routines, it should at least provide stubs that always
6370 ** return true so that one does not get spurious assertion failures.
6371 **
6372 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6373 ** the routine should return 1.   This seems counter-intuitive since
6374 ** clearly the mutex cannot be held if it does not exist.  But
6375 ** the reason the mutex does not exist is because the build is not
6376 ** using mutexes.  And we do not want the assert() containing the
6377 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6378 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6379 ** interface should also return 1 when given a NULL pointer.
6380 */
6381 #ifndef NDEBUG
6382 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6383 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6384 #endif
6385
6386 /*
6387 ** CAPI3REF: Mutex Types
6388 **
6389 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6390 ** which is one of these integer constants.
6391 **
6392 ** The set of static mutexes may change from one SQLite release to the
6393 ** next.  Applications that override the built-in mutex logic must be
6394 ** prepared to accommodate additional static mutexes.
6395 */
6396 #define SQLITE_MUTEX_FAST             0
6397 #define SQLITE_MUTEX_RECURSIVE        1
6398 #define SQLITE_MUTEX_STATIC_MASTER    2
6399 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6400 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6401 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6402 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6403 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6404 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6405 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6406
6407 /*
6408 ** CAPI3REF: Retrieve the mutex for a database connection
6409 **
6410 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6411 ** serializes access to the [database connection] given in the argument
6412 ** when the [threading mode] is Serialized.
6413 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6414 ** routine returns a NULL pointer.
6415 */
6416 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6417
6418 /*
6419 ** CAPI3REF: Low-Level Control Of Database Files
6420 **
6421 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6422 ** xFileControl method for the [sqlite3_io_methods] object associated
6423 ** with a particular database identified by the second argument. ^The
6424 ** name of the database is "main" for the main database or "temp" for the
6425 ** TEMP database, or the name that appears after the AS keyword for
6426 ** databases that are added using the [ATTACH] SQL command.
6427 ** ^A NULL pointer can be used in place of "main" to refer to the
6428 ** main database file.
6429 ** ^The third and fourth parameters to this routine
6430 ** are passed directly through to the second and third parameters of
6431 ** the xFileControl method.  ^The return value of the xFileControl
6432 ** method becomes the return value of this routine.
6433 **
6434 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6435 ** a pointer to the underlying [sqlite3_file] object to be written into
6436 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6437 ** case is a short-circuit path which does not actually invoke the
6438 ** underlying sqlite3_io_methods.xFileControl method.
6439 **
6440 ** ^If the second parameter (zDbName) does not match the name of any
6441 ** open database file, then SQLITE_ERROR is returned.  ^This error
6442 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6443 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6444 ** also return SQLITE_ERROR.  There is no way to distinguish between
6445 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6446 ** xFileControl method.
6447 **
6448 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6449 */
6450 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6451
6452 /*
6453 ** CAPI3REF: Testing Interface
6454 **
6455 ** ^The sqlite3_test_control() interface is used to read out internal
6456 ** state of SQLite and to inject faults into SQLite for testing
6457 ** purposes.  ^The first parameter is an operation code that determines
6458 ** the number, meaning, and operation of all subsequent parameters.
6459 **
6460 ** This interface is not for use by applications.  It exists solely
6461 ** for verifying the correct operation of the SQLite library.  Depending
6462 ** on how the SQLite library is compiled, this interface might not exist.
6463 **
6464 ** The details of the operation codes, their meanings, the parameters
6465 ** they take, and what they do are all subject to change without notice.
6466 ** Unlike most of the SQLite API, this function is not guaranteed to
6467 ** operate consistently from one release to the next.
6468 */
6469 SQLITE_API int sqlite3_test_control(int op, ...);
6470
6471 /*
6472 ** CAPI3REF: Testing Interface Operation Codes
6473 **
6474 ** These constants are the valid operation code parameters used
6475 ** as the first argument to [sqlite3_test_control()].
6476 **
6477 ** These parameters and their meanings are subject to change
6478 ** without notice.  These values are for testing purposes only.
6479 ** Applications should not use any of these parameters or the
6480 ** [sqlite3_test_control()] interface.
6481 */
6482 #define SQLITE_TESTCTRL_FIRST                    5
6483 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6484 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6485 #define SQLITE_TESTCTRL_PRNG_RESET               7
6486 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6487 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6488 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6489 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6490 #define SQLITE_TESTCTRL_ASSERT                  12
6491 #define SQLITE_TESTCTRL_ALWAYS                  13
6492 #define SQLITE_TESTCTRL_RESERVE                 14
6493 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6494 #define SQLITE_TESTCTRL_ISKEYWORD               16
6495 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6496 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6497 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6498 #define SQLITE_TESTCTRL_LAST                    19
6499
6500 /*
6501 ** CAPI3REF: SQLite Runtime Status
6502 **
6503 ** ^This interface is used to retrieve runtime status information
6504 ** about the performance of SQLite, and optionally to reset various
6505 ** highwater marks.  ^The first argument is an integer code for
6506 ** the specific parameter to measure.  ^(Recognized integer codes
6507 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6508 ** ^The current value of the parameter is returned into *pCurrent.
6509 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6510 ** resetFlag is true, then the highest record value is reset after
6511 ** *pHighwater is written.  ^(Some parameters do not record the highest
6512 ** value.  For those parameters
6513 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6514 ** ^(Other parameters record only the highwater mark and not the current
6515 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6516 **
6517 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6518 ** non-zero [error code] on failure.
6519 **
6520 ** This routine is threadsafe but is not atomic.  This routine can be
6521 ** called while other threads are running the same or different SQLite
6522 ** interfaces.  However the values returned in *pCurrent and
6523 ** *pHighwater reflect the status of SQLite at different points in time
6524 ** and it is possible that another thread might change the parameter
6525 ** in between the times when *pCurrent and *pHighwater are written.
6526 **
6527 ** See also: [sqlite3_db_status()]
6528 */
6529 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6530
6531
6532 /*
6533 ** CAPI3REF: Status Parameters
6534 ** KEYWORDS: {status parameters}
6535 **
6536 ** These integer constants designate various run-time status parameters
6537 ** that can be returned by [sqlite3_status()].
6538 **
6539 ** <dl>
6540 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6541 ** <dd>This parameter is the current amount of memory checked out
6542 ** using [sqlite3_malloc()], either directly or indirectly.  The
6543 ** figure includes calls made to [sqlite3_malloc()] by the application
6544 ** and internal memory usage by the SQLite library.  Scratch memory
6545 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6546 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6547 ** this parameter.  The amount returned is the sum of the allocation
6548 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6549 **
6550 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6551 ** <dd>This parameter records the largest memory allocation request
6552 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6553 ** internal equivalents).  Only the value returned in the
6554 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6555 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6556 **
6557 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6558 ** <dd>This parameter records the number of separate memory allocations
6559 ** currently checked out.</dd>)^
6560 **
6561 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6562 ** <dd>This parameter returns the number of pages used out of the
6563 ** [pagecache memory allocator] that was configured using
6564 ** [SQLITE_CONFIG_PAGECACHE].  The
6565 ** value returned is in pages, not in bytes.</dd>)^
6566 **
6567 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6568 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6569 ** <dd>This parameter returns the number of bytes of page cache
6570 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6571 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6572 ** returned value includes allocations that overflowed because they
6573 ** where too large (they were larger than the "sz" parameter to
6574 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6575 ** no space was left in the page cache.</dd>)^
6576 **
6577 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6578 ** <dd>This parameter records the largest memory allocation request
6579 ** handed to [pagecache memory allocator].  Only the value returned in the
6580 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6581 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6582 **
6583 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6584 ** <dd>This parameter returns the number of allocations used out of the
6585 ** [scratch memory allocator] configured using
6586 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6587 ** in bytes.  Since a single thread may only have one scratch allocation
6588 ** outstanding at time, this parameter also reports the number of threads
6589 ** using scratch memory at the same time.</dd>)^
6590 **
6591 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6592 ** <dd>This parameter returns the number of bytes of scratch memory
6593 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6594 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6595 ** returned include overflows because the requested allocation was too
6596 ** larger (that is, because the requested allocation was larger than the
6597 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6598 ** slots were available.
6599 ** </dd>)^
6600 **
6601 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6602 ** <dd>This parameter records the largest memory allocation request
6603 ** handed to [scratch memory allocator].  Only the value returned in the
6604 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6605 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6606 **
6607 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6608 ** <dd>This parameter records the deepest parser stack.  It is only
6609 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6610 ** </dl>
6611 **
6612 ** New status parameters may be added from time to time.
6613 */
6614 #define SQLITE_STATUS_MEMORY_USED          0
6615 #define SQLITE_STATUS_PAGECACHE_USED       1
6616 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6617 #define SQLITE_STATUS_SCRATCH_USED         3
6618 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6619 #define SQLITE_STATUS_MALLOC_SIZE          5
6620 #define SQLITE_STATUS_PARSER_STACK         6
6621 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6622 #define SQLITE_STATUS_SCRATCH_SIZE         8
6623 #define SQLITE_STATUS_MALLOC_COUNT         9
6624
6625 /*
6626 ** CAPI3REF: Database Connection Status
6627 **
6628 ** ^This interface is used to retrieve runtime status information
6629 ** about a single [database connection].  ^The first argument is the
6630 ** database connection object to be interrogated.  ^The second argument
6631 ** is an integer constant, taken from the set of
6632 ** [SQLITE_DBSTATUS options], that
6633 ** determines the parameter to interrogate.  The set of
6634 ** [SQLITE_DBSTATUS options] is likely
6635 ** to grow in future releases of SQLite.
6636 **
6637 ** ^The current value of the requested parameter is written into *pCur
6638 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6639 ** the resetFlg is true, then the highest instantaneous value is
6640 ** reset back down to the current value.
6641 **
6642 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6643 ** non-zero [error code] on failure.
6644 **
6645 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6646 */
6647 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6648
6649 /*
6650 ** CAPI3REF: Status Parameters for database connections
6651 ** KEYWORDS: {SQLITE_DBSTATUS options}
6652 **
6653 ** These constants are the available integer "verbs" that can be passed as
6654 ** the second argument to the [sqlite3_db_status()] interface.
6655 **
6656 ** New verbs may be added in future releases of SQLite. Existing verbs
6657 ** might be discontinued. Applications should check the return code from
6658 ** [sqlite3_db_status()] to make sure that the call worked.
6659 ** The [sqlite3_db_status()] interface will return a non-zero error code
6660 ** if a discontinued or unsupported verb is invoked.
6661 **
6662 ** <dl>
6663 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6664 ** <dd>This parameter returns the number of lookaside memory slots currently
6665 ** checked out.</dd>)^
6666 **
6667 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6668 ** <dd>This parameter returns the number malloc attempts that were
6669 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6670 ** the current value is always zero.)^
6671 **
6672 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6673 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6674 ** <dd>This parameter returns the number malloc attempts that might have
6675 ** been satisfied using lookaside memory but failed due to the amount of
6676 ** memory requested being larger than the lookaside slot size.
6677 ** Only the high-water value is meaningful;
6678 ** the current value is always zero.)^
6679 **
6680 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6681 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6682 ** <dd>This parameter returns the number malloc attempts that might have
6683 ** been satisfied using lookaside memory but failed due to all lookaside
6684 ** memory already being in use.
6685 ** Only the high-water value is meaningful;
6686 ** the current value is always zero.)^
6687 **
6688 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6689 ** <dd>This parameter returns the approximate number of of bytes of heap
6690 ** memory used by all pager caches associated with the database connection.)^
6691 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6692 **
6693 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6694 ** <dd>This parameter returns the approximate number of of bytes of heap
6695 ** memory used to store the schema for all databases associated
6696 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6697 ** ^The full amount of memory used by the schemas is reported, even if the
6698 ** schema memory is shared with other database connections due to
6699 ** [shared cache mode] being enabled.
6700 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6701 **
6702 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6703 ** <dd>This parameter returns the approximate number of of bytes of heap
6704 ** and lookaside memory used by all prepared statements associated with
6705 ** the database connection.)^
6706 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6707 ** </dd>
6708 **
6709 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6710 ** <dd>This parameter returns the number of pager cache hits that have
6711 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6712 ** is always 0.
6713 ** </dd>
6714 **
6715 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6716 ** <dd>This parameter returns the number of pager cache misses that have
6717 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6718 ** is always 0.
6719 ** </dd>
6720 **
6721 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6722 ** <dd>This parameter returns the number of dirty cache entries that have
6723 ** been written to disk. Specifically, the number of pages written to the
6724 ** wal file in wal mode databases, or the number of pages written to the
6725 ** database file in rollback mode databases. Any pages written as part of
6726 ** transaction rollback or database recovery operations are not included.
6727 ** If an IO or other error occurs while writing a page to disk, the effect
6728 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6729 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6730 ** </dd>
6731 ** </dl>
6732 */
6733 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6734 #define SQLITE_DBSTATUS_CACHE_USED           1
6735 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6736 #define SQLITE_DBSTATUS_STMT_USED            3
6737 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6738 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6739 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6740 #define SQLITE_DBSTATUS_CACHE_HIT            7
6741 #define SQLITE_DBSTATUS_CACHE_MISS           8
6742 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6743 #define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */
6744
6745
6746 /*
6747 ** CAPI3REF: Prepared Statement Status
6748 **
6749 ** ^(Each prepared statement maintains various
6750 ** [SQLITE_STMTSTATUS counters] that measure the number
6751 ** of times it has performed specific operations.)^  These counters can
6752 ** be used to monitor the performance characteristics of the prepared
6753 ** statements.  For example, if the number of table steps greatly exceeds
6754 ** the number of table searches or result rows, that would tend to indicate
6755 ** that the prepared statement is using a full table scan rather than
6756 ** an index.
6757 **
6758 ** ^(This interface is used to retrieve and reset counter values from
6759 ** a [prepared statement].  The first argument is the prepared statement
6760 ** object to be interrogated.  The second argument
6761 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6762 ** to be interrogated.)^
6763 ** ^The current value of the requested counter is returned.
6764 ** ^If the resetFlg is true, then the counter is reset to zero after this
6765 ** interface call returns.
6766 **
6767 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6768 */
6769 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6770
6771 /*
6772 ** CAPI3REF: Status Parameters for prepared statements
6773 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6774 **
6775 ** These preprocessor macros define integer codes that name counter
6776 ** values associated with the [sqlite3_stmt_status()] interface.
6777 ** The meanings of the various counters are as follows:
6778 **
6779 ** <dl>
6780 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6781 ** <dd>^This is the number of times that SQLite has stepped forward in
6782 ** a table as part of a full table scan.  Large numbers for this counter
6783 ** may indicate opportunities for performance improvement through
6784 ** careful use of indices.</dd>
6785 **
6786 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6787 ** <dd>^This is the number of sort operations that have occurred.
6788 ** A non-zero value in this counter may indicate an opportunity to
6789 ** improvement performance through careful use of indices.</dd>
6790 **
6791 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6792 ** <dd>^This is the number of rows inserted into transient indices that
6793 ** were created automatically in order to help joins run faster.
6794 ** A non-zero value in this counter may indicate an opportunity to
6795 ** improvement performance by adding permanent indices that do not
6796 ** need to be reinitialized each time the statement is run.</dd>
6797 ** </dl>
6798 */
6799 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6800 #define SQLITE_STMTSTATUS_SORT              2
6801 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6802
6803 /*
6804 ** CAPI3REF: Custom Page Cache Object
6805 **
6806 ** The sqlite3_pcache type is opaque.  It is implemented by
6807 ** the pluggable module.  The SQLite core has no knowledge of
6808 ** its size or internal structure and never deals with the
6809 ** sqlite3_pcache object except by holding and passing pointers
6810 ** to the object.
6811 **
6812 ** See [sqlite3_pcache_methods2] for additional information.
6813 */
6814 typedef struct sqlite3_pcache sqlite3_pcache;
6815
6816 /*
6817 ** CAPI3REF: Custom Page Cache Object
6818 **
6819 ** The sqlite3_pcache_page object represents a single page in the
6820 ** page cache.  The page cache will allocate instances of this
6821 ** object.  Various methods of the page cache use pointers to instances
6822 ** of this object as parameters or as their return value.
6823 **
6824 ** See [sqlite3_pcache_methods2] for additional information.
6825 */
6826 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6827 struct sqlite3_pcache_page {
6828   void *pBuf;        /* The content of the page */
6829   void *pExtra;      /* Extra information associated with the page */
6830 };
6831
6832 /*
6833 ** CAPI3REF: Application Defined Page Cache.
6834 ** KEYWORDS: {page cache}
6835 **
6836 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6837 ** register an alternative page cache implementation by passing in an
6838 ** instance of the sqlite3_pcache_methods2 structure.)^
6839 ** In many applications, most of the heap memory allocated by
6840 ** SQLite is used for the page cache.
6841 ** By implementing a
6842 ** custom page cache using this API, an application can better control
6843 ** the amount of memory consumed by SQLite, the way in which
6844 ** that memory is allocated and released, and the policies used to
6845 ** determine exactly which parts of a database file are cached and for
6846 ** how long.
6847 **
6848 ** The alternative page cache mechanism is an
6849 ** extreme measure that is only needed by the most demanding applications.
6850 ** The built-in page cache is recommended for most uses.
6851 **
6852 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6853 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6854 ** the application may discard the parameter after the call to
6855 ** [sqlite3_config()] returns.)^
6856 **
6857 ** [[the xInit() page cache method]]
6858 ** ^(The xInit() method is called once for each effective
6859 ** call to [sqlite3_initialize()])^
6860 ** (usually only once during the lifetime of the process). ^(The xInit()
6861 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6862 ** The intent of the xInit() method is to set up global data structures
6863 ** required by the custom page cache implementation.
6864 ** ^(If the xInit() method is NULL, then the
6865 ** built-in default page cache is used instead of the application defined
6866 ** page cache.)^
6867 **
6868 ** [[the xShutdown() page cache method]]
6869 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6870 ** It can be used to clean up
6871 ** any outstanding resources before process shutdown, if required.
6872 ** ^The xShutdown() method may be NULL.
6873 **
6874 ** ^SQLite automatically serializes calls to the xInit method,
6875 ** so the xInit method need not be threadsafe.  ^The
6876 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6877 ** not need to be threadsafe either.  All other methods must be threadsafe
6878 ** in multithreaded applications.
6879 **
6880 ** ^SQLite will never invoke xInit() more than once without an intervening
6881 ** call to xShutdown().
6882 **
6883 ** [[the xCreate() page cache methods]]
6884 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6885 ** SQLite will typically create one cache instance for each open database file,
6886 ** though this is not guaranteed. ^The
6887 ** first parameter, szPage, is the size in bytes of the pages that must
6888 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6889 ** second parameter szExtra is a number of bytes of extra storage
6890 ** associated with each page cache entry.  ^The szExtra parameter will
6891 ** a number less than 250.  SQLite will use the
6892 ** extra szExtra bytes on each page to store metadata about the underlying
6893 ** database page on disk.  The value passed into szExtra depends
6894 ** on the SQLite version, the target platform, and how SQLite was compiled.
6895 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6896 ** created will be used to cache database pages of a file stored on disk, or
6897 ** false if it is used for an in-memory database. The cache implementation
6898 ** does not have to do anything special based with the value of bPurgeable;
6899 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6900 ** never invoke xUnpin() except to deliberately delete a page.
6901 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6902 ** false will always have the "discard" flag set to true.
6903 ** ^Hence, a cache created with bPurgeable false will
6904 ** never contain any unpinned pages.
6905 **
6906 ** [[the xCachesize() page cache method]]
6907 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6908 ** suggested maximum cache-size (number of pages stored by) the cache
6909 ** instance passed as the first argument. This is the value configured using
6910 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6911 ** parameter, the implementation is not required to do anything with this
6912 ** value; it is advisory only.
6913 **
6914 ** [[the xPagecount() page cache methods]]
6915 ** The xPagecount() method must return the number of pages currently
6916 ** stored in the cache, both pinned and unpinned.
6917 **
6918 ** [[the xFetch() page cache methods]]
6919 ** The xFetch() method locates a page in the cache and returns a pointer to
6920 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6921 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6922 ** pointer to a buffer of szPage bytes used to store the content of a
6923 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6924 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6925 ** for each entry in the page cache.
6926 **
6927 ** The page to be fetched is determined by the key. ^The minimum key value
6928 ** is 1.  After it has been retrieved using xFetch, the page is considered
6929 ** to be "pinned".
6930 **
6931 ** If the requested page is already in the page cache, then the page cache
6932 ** implementation must return a pointer to the page buffer with its content
6933 ** intact.  If the requested page is not already in the cache, then the
6934 ** cache implementation should use the value of the createFlag
6935 ** parameter to help it determined what action to take:
6936 **
6937 ** <table border=1 width=85% align=center>
6938 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6939 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6940 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6941 **                 Otherwise return NULL.
6942 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6943 **                 NULL if allocating a new page is effectively impossible.
6944 ** </table>
6945 **
6946 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6947 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6948 ** failed.)^  In between the to xFetch() calls, SQLite may
6949 ** attempt to unpin one or more cache pages by spilling the content of
6950 ** pinned pages to disk and synching the operating system disk cache.
6951 **
6952 ** [[the xUnpin() page cache method]]
6953 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6954 ** as its second argument.  If the third parameter, discard, is non-zero,
6955 ** then the page must be evicted from the cache.
6956 ** ^If the discard parameter is
6957 ** zero, then the page may be discarded or retained at the discretion of
6958 ** page cache implementation. ^The page cache implementation
6959 ** may choose to evict unpinned pages at any time.
6960 **
6961 ** The cache must not perform any reference counting. A single
6962 ** call to xUnpin() unpins the page regardless of the number of prior calls
6963 ** to xFetch().
6964 **
6965 ** [[the xRekey() page cache methods]]
6966 ** The xRekey() method is used to change the key value associated with the
6967 ** page passed as the second argument. If the cache
6968 ** previously contains an entry associated with newKey, it must be
6969 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6970 ** to be pinned.
6971 **
6972 ** When SQLite calls the xTruncate() method, the cache must discard all
6973 ** existing cache entries with page numbers (keys) greater than or equal
6974 ** to the value of the iLimit parameter passed to xTruncate(). If any
6975 ** of these pages are pinned, they are implicitly unpinned, meaning that
6976 ** they can be safely discarded.
6977 **
6978 ** [[the xDestroy() page cache method]]
6979 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6980 ** All resources associated with the specified cache should be freed. ^After
6981 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6982 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6983 ** functions.
6984 **
6985 ** [[the xShrink() page cache method]]
6986 ** ^SQLite invokes the xShrink() method when it wants the page cache to
6987 ** free up as much of heap memory as possible.  The page cache implementation
6988 ** is not obligated to free any memory, but well-behaved implementations should
6989 ** do their best.
6990 */
6991 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6992 struct sqlite3_pcache_methods2 {
6993   int iVersion;
6994   void *pArg;
6995   int (*xInit)(void*);
6996   void (*xShutdown)(void*);
6997   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6998   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6999   int (*xPagecount)(sqlite3_pcache*);
7000   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7001   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7002   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7003       unsigned oldKey, unsigned newKey);
7004   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7005   void (*xDestroy)(sqlite3_pcache*);
7006   void (*xShrink)(sqlite3_pcache*);
7007 };
7008
7009 /*
7010 ** This is the obsolete pcache_methods object that has now been replaced
7011 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7012 ** retained in the header file for backwards compatibility only.
7013 */
7014 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7015 struct sqlite3_pcache_methods {
7016   void *pArg;
7017   int (*xInit)(void*);
7018   void (*xShutdown)(void*);
7019   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7020   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7021   int (*xPagecount)(sqlite3_pcache*);
7022   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7023   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7024   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7025   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7026   void (*xDestroy)(sqlite3_pcache*);
7027 };
7028
7029
7030 /*
7031 ** CAPI3REF: Online Backup Object
7032 **
7033 ** The sqlite3_backup object records state information about an ongoing
7034 ** online backup operation.  ^The sqlite3_backup object is created by
7035 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7036 ** [sqlite3_backup_finish()].
7037 **
7038 ** See Also: [Using the SQLite Online Backup API]
7039 */
7040 typedef struct sqlite3_backup sqlite3_backup;
7041
7042 /*
7043 ** CAPI3REF: Online Backup API.
7044 **
7045 ** The backup API copies the content of one database into another.
7046 ** It is useful either for creating backups of databases or
7047 ** for copying in-memory databases to or from persistent files.
7048 **
7049 ** See Also: [Using the SQLite Online Backup API]
7050 **
7051 ** ^SQLite holds a write transaction open on the destination database file
7052 ** for the duration of the backup operation.
7053 ** ^The source database is read-locked only while it is being read;
7054 ** it is not locked continuously for the entire backup operation.
7055 ** ^Thus, the backup may be performed on a live source database without
7056 ** preventing other database connections from
7057 ** reading or writing to the source database while the backup is underway.
7058 **
7059 ** ^(To perform a backup operation:
7060 **   <ol>
7061 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7062 **         backup,
7063 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7064 **         the data between the two databases, and finally
7065 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
7066 **         associated with the backup operation.
7067 **   </ol>)^
7068 ** There should be exactly one call to sqlite3_backup_finish() for each
7069 ** successful call to sqlite3_backup_init().
7070 **
7071 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7072 **
7073 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7074 ** [database connection] associated with the destination database
7075 ** and the database name, respectively.
7076 ** ^The database name is "main" for the main database, "temp" for the
7077 ** temporary database, or the name specified after the AS keyword in
7078 ** an [ATTACH] statement for an attached database.
7079 ** ^The S and M arguments passed to
7080 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7081 ** and database name of the source database, respectively.
7082 ** ^The source and destination [database connections] (parameters S and D)
7083 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7084 ** an error.
7085 **
7086 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7087 ** returned and an error code and error message are stored in the
7088 ** destination [database connection] D.
7089 ** ^The error code and message for the failed call to sqlite3_backup_init()
7090 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7091 ** [sqlite3_errmsg16()] functions.
7092 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7093 ** [sqlite3_backup] object.
7094 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7095 ** sqlite3_backup_finish() functions to perform the specified backup
7096 ** operation.
7097 **
7098 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7099 **
7100 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7101 ** the source and destination databases specified by [sqlite3_backup] object B.
7102 ** ^If N is negative, all remaining source pages are copied.
7103 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7104 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7105 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7106 ** from source to destination, then it returns [SQLITE_DONE].
7107 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7108 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7109 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7110 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7111 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7112 **
7113 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7114 ** <ol>
7115 ** <li> the destination database was opened read-only, or
7116 ** <li> the destination database is using write-ahead-log journaling
7117 ** and the destination and source page sizes differ, or
7118 ** <li> the destination database is an in-memory database and the
7119 ** destination and source page sizes differ.
7120 ** </ol>)^
7121 **
7122 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7123 ** the [sqlite3_busy_handler | busy-handler function]
7124 ** is invoked (if one is specified). ^If the
7125 ** busy-handler returns non-zero before the lock is available, then
7126 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7127 ** sqlite3_backup_step() can be retried later. ^If the source
7128 ** [database connection]
7129 ** is being used to write to the source database when sqlite3_backup_step()
7130 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7131 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7132 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7133 ** [SQLITE_READONLY] is returned, then
7134 ** there is no point in retrying the call to sqlite3_backup_step(). These
7135 ** errors are considered fatal.)^  The application must accept
7136 ** that the backup operation has failed and pass the backup operation handle
7137 ** to the sqlite3_backup_finish() to release associated resources.
7138 **
7139 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7140 ** on the destination file. ^The exclusive lock is not released until either
7141 ** sqlite3_backup_finish() is called or the backup operation is complete
7142 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7143 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7144 ** lasts for the duration of the sqlite3_backup_step() call.
7145 ** ^Because the source database is not locked between calls to
7146 ** sqlite3_backup_step(), the source database may be modified mid-way
7147 ** through the backup process.  ^If the source database is modified by an
7148 ** external process or via a database connection other than the one being
7149 ** used by the backup operation, then the backup will be automatically
7150 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7151 ** database is modified by the using the same database connection as is used
7152 ** by the backup operation, then the backup database is automatically
7153 ** updated at the same time.
7154 **
7155 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7156 **
7157 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7158 ** application wishes to abandon the backup operation, the application
7159 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7160 ** ^The sqlite3_backup_finish() interfaces releases all
7161 ** resources associated with the [sqlite3_backup] object.
7162 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7163 ** active write-transaction on the destination database is rolled back.
7164 ** The [sqlite3_backup] object is invalid
7165 ** and may not be used following a call to sqlite3_backup_finish().
7166 **
7167 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7168 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7169 ** sqlite3_backup_step() completed.
7170 ** ^If an out-of-memory condition or IO error occurred during any prior
7171 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7172 ** sqlite3_backup_finish() returns the corresponding [error code].
7173 **
7174 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7175 ** is not a permanent error and does not affect the return value of
7176 ** sqlite3_backup_finish().
7177 **
7178 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7179 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7180 **
7181 ** ^Each call to sqlite3_backup_step() sets two values inside
7182 ** the [sqlite3_backup] object: the number of pages still to be backed
7183 ** up and the total number of pages in the source database file.
7184 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7185 ** retrieve these two values, respectively.
7186 **
7187 ** ^The values returned by these functions are only updated by
7188 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7189 ** operation, then the values are not updated to account for any extra
7190 ** pages that need to be updated or the size of the source database file
7191 ** changing.
7192 **
7193 ** <b>Concurrent Usage of Database Handles</b>
7194 **
7195 ** ^The source [database connection] may be used by the application for other
7196 ** purposes while a backup operation is underway or being initialized.
7197 ** ^If SQLite is compiled and configured to support threadsafe database
7198 ** connections, then the source database connection may be used concurrently
7199 ** from within other threads.
7200 **
7201 ** However, the application must guarantee that the destination
7202 ** [database connection] is not passed to any other API (by any thread) after
7203 ** sqlite3_backup_init() is called and before the corresponding call to
7204 ** sqlite3_backup_finish().  SQLite does not currently check to see
7205 ** if the application incorrectly accesses the destination [database connection]
7206 ** and so no error code is reported, but the operations may malfunction
7207 ** nevertheless.  Use of the destination database connection while a
7208 ** backup is in progress might also also cause a mutex deadlock.
7209 **
7210 ** If running in [shared cache mode], the application must
7211 ** guarantee that the shared cache used by the destination database
7212 ** is not accessed while the backup is running. In practice this means
7213 ** that the application must guarantee that the disk file being
7214 ** backed up to is not accessed by any connection within the process,
7215 ** not just the specific connection that was passed to sqlite3_backup_init().
7216 **
7217 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7218 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7219 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7220 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7221 ** same time as another thread is invoking sqlite3_backup_step() it is
7222 ** possible that they return invalid values.
7223 */
7224 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7225   sqlite3 *pDest,                        /* Destination database handle */
7226   const char *zDestName,                 /* Destination database name */
7227   sqlite3 *pSource,                      /* Source database handle */
7228   const char *zSourceName                /* Source database name */
7229 );
7230 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7231 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7232 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7233 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7234
7235 /*
7236 ** CAPI3REF: Unlock Notification
7237 **
7238 ** ^When running in shared-cache mode, a database operation may fail with
7239 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7240 ** individual tables within the shared-cache cannot be obtained. See
7241 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7242 ** ^This API may be used to register a callback that SQLite will invoke
7243 ** when the connection currently holding the required lock relinquishes it.
7244 ** ^This API is only available if the library was compiled with the
7245 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7246 **
7247 ** See Also: [Using the SQLite Unlock Notification Feature].
7248 **
7249 ** ^Shared-cache locks are released when a database connection concludes
7250 ** its current transaction, either by committing it or rolling it back.
7251 **
7252 ** ^When a connection (known as the blocked connection) fails to obtain a
7253 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7254 ** identity of the database connection (the blocking connection) that
7255 ** has locked the required resource is stored internally. ^After an
7256 ** application receives an SQLITE_LOCKED error, it may call the
7257 ** sqlite3_unlock_notify() method with the blocked connection handle as
7258 ** the first argument to register for a callback that will be invoked
7259 ** when the blocking connections current transaction is concluded. ^The
7260 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7261 ** call that concludes the blocking connections transaction.
7262 **
7263 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7264 ** there is a chance that the blocking connection will have already
7265 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7266 ** If this happens, then the specified callback is invoked immediately,
7267 ** from within the call to sqlite3_unlock_notify().)^
7268 **
7269 ** ^If the blocked connection is attempting to obtain a write-lock on a
7270 ** shared-cache table, and more than one other connection currently holds
7271 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7272 ** the other connections to use as the blocking connection.
7273 **
7274 ** ^(There may be at most one unlock-notify callback registered by a
7275 ** blocked connection. If sqlite3_unlock_notify() is called when the
7276 ** blocked connection already has a registered unlock-notify callback,
7277 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7278 ** called with a NULL pointer as its second argument, then any existing
7279 ** unlock-notify callback is canceled. ^The blocked connections
7280 ** unlock-notify callback may also be canceled by closing the blocked
7281 ** connection using [sqlite3_close()].
7282 **
7283 ** The unlock-notify callback is not reentrant. If an application invokes
7284 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7285 ** crash or deadlock may be the result.
7286 **
7287 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7288 ** returns SQLITE_OK.
7289 **
7290 ** <b>Callback Invocation Details</b>
7291 **
7292 ** When an unlock-notify callback is registered, the application provides a
7293 ** single void* pointer that is passed to the callback when it is invoked.
7294 ** However, the signature of the callback function allows SQLite to pass
7295 ** it an array of void* context pointers. The first argument passed to
7296 ** an unlock-notify callback is a pointer to an array of void* pointers,
7297 ** and the second is the number of entries in the array.
7298 **
7299 ** When a blocking connections transaction is concluded, there may be
7300 ** more than one blocked connection that has registered for an unlock-notify
7301 ** callback. ^If two or more such blocked connections have specified the
7302 ** same callback function, then instead of invoking the callback function
7303 ** multiple times, it is invoked once with the set of void* context pointers
7304 ** specified by the blocked connections bundled together into an array.
7305 ** This gives the application an opportunity to prioritize any actions
7306 ** related to the set of unblocked database connections.
7307 **
7308 ** <b>Deadlock Detection</b>
7309 **
7310 ** Assuming that after registering for an unlock-notify callback a
7311 ** database waits for the callback to be issued before taking any further
7312 ** action (a reasonable assumption), then using this API may cause the
7313 ** application to deadlock. For example, if connection X is waiting for
7314 ** connection Y's transaction to be concluded, and similarly connection
7315 ** Y is waiting on connection X's transaction, then neither connection
7316 ** will proceed and the system may remain deadlocked indefinitely.
7317 **
7318 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7319 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7320 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7321 ** unlock-notify callback is registered. The system is said to be in
7322 ** a deadlocked state if connection A has registered for an unlock-notify
7323 ** callback on the conclusion of connection B's transaction, and connection
7324 ** B has itself registered for an unlock-notify callback when connection
7325 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7326 ** the system is also considered to be deadlocked if connection B has
7327 ** registered for an unlock-notify callback on the conclusion of connection
7328 ** C's transaction, where connection C is waiting on connection A. ^Any
7329 ** number of levels of indirection are allowed.
7330 **
7331 ** <b>The "DROP TABLE" Exception</b>
7332 **
7333 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7334 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7335 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7336 ** SQLite checks if there are any currently executing SELECT statements
7337 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7338 ** returned. In this case there is no "blocking connection", so invoking
7339 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7340 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7341 ** or "DROP INDEX" query, an infinite loop might be the result.
7342 **
7343 ** One way around this problem is to check the extended error code returned
7344 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7345 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7346 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7347 ** SQLITE_LOCKED.)^
7348 */
7349 SQLITE_API int sqlite3_unlock_notify(
7350   sqlite3 *pBlocked,                          /* Waiting connection */
7351   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7352   void *pNotifyArg                            /* Argument to pass to xNotify */
7353 );
7354
7355
7356 /*
7357 ** CAPI3REF: String Comparison
7358 **
7359 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7360 ** and extensions to compare the contents of two buffers containing UTF-8
7361 ** strings in a case-independent fashion, using the same definition of "case
7362 ** independence" that SQLite uses internally when comparing identifiers.
7363 */
7364 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7365 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7366
7367 /*
7368 ** CAPI3REF: Error Logging Interface
7369 **
7370 ** ^The [sqlite3_log()] interface writes a message into the error log
7371 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7372 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7373 ** used with [sqlite3_snprintf()] to generate the final output string.
7374 **
7375 ** The sqlite3_log() interface is intended for use by extensions such as
7376 ** virtual tables, collating functions, and SQL functions.  While there is
7377 ** nothing to prevent an application from calling sqlite3_log(), doing so
7378 ** is considered bad form.
7379 **
7380 ** The zFormat string must not be NULL.
7381 **
7382 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7383 ** will not use dynamically allocated memory.  The log message is stored in
7384 ** a fixed-length buffer on the stack.  If the log message is longer than
7385 ** a few hundred characters, it will be truncated to the length of the
7386 ** buffer.
7387 */
7388 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7389
7390 /*
7391 ** CAPI3REF: Write-Ahead Log Commit Hook
7392 **
7393 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7394 ** will be invoked each time a database connection commits data to a
7395 ** [write-ahead log] (i.e. whenever a transaction is committed in
7396 ** [journal_mode | journal_mode=WAL mode]).
7397 **
7398 ** ^The callback is invoked by SQLite after the commit has taken place and
7399 ** the associated write-lock on the database released, so the implementation
7400 ** may read, write or [checkpoint] the database as required.
7401 **
7402 ** ^The first parameter passed to the callback function when it is invoked
7403 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7404 ** registering the callback. ^The second is a copy of the database handle.
7405 ** ^The third parameter is the name of the database that was written to -
7406 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7407 ** is the number of pages currently in the write-ahead log file,
7408 ** including those that were just committed.
7409 **
7410 ** The callback function should normally return [SQLITE_OK].  ^If an error
7411 ** code is returned, that error will propagate back up through the
7412 ** SQLite code base to cause the statement that provoked the callback
7413 ** to report an error, though the commit will have still occurred. If the
7414 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7415 ** that does not correspond to any valid SQLite error code, the results
7416 ** are undefined.
7417 **
7418 ** A single database handle may have at most a single write-ahead log callback
7419 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7420 ** previously registered write-ahead log callback. ^Note that the
7421 ** [sqlite3_wal_autocheckpoint()] interface and the
7422 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7423 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7424 */
7425 SQLITE_API void *sqlite3_wal_hook(
7426   sqlite3*,
7427   int(*)(void *,sqlite3*,const char*,int),
7428   void*
7429 );
7430
7431 /*
7432 ** CAPI3REF: Configure an auto-checkpoint
7433 **
7434 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7435 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7436 ** to automatically [checkpoint]
7437 ** after committing a transaction if there are N or
7438 ** more frames in the [write-ahead log] file.  ^Passing zero or
7439 ** a negative value as the nFrame parameter disables automatic
7440 ** checkpoints entirely.
7441 **
7442 ** ^The callback registered by this function replaces any existing callback
7443 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7444 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7445 ** configured by this function.
7446 **
7447 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7448 ** from SQL.
7449 **
7450 ** ^Every new [database connection] defaults to having the auto-checkpoint
7451 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7452 ** pages.  The use of this interface
7453 ** is only necessary if the default setting is found to be suboptimal
7454 ** for a particular application.
7455 */
7456 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7457
7458 /*
7459 ** CAPI3REF: Checkpoint a database
7460 **
7461 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7462 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7463 ** empty string, then a checkpoint is run on all databases of
7464 ** connection D.  ^If the database connection D is not in
7465 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7466 **
7467 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7468 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7469 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7470 ** run whenever the WAL reaches a certain size threshold.
7471 **
7472 ** See also: [sqlite3_wal_checkpoint_v2()]
7473 */
7474 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7475
7476 /*
7477 ** CAPI3REF: Checkpoint a database
7478 **
7479 ** Run a checkpoint operation on WAL database zDb attached to database
7480 ** handle db. The specific operation is determined by the value of the
7481 ** eMode parameter:
7482 **
7483 ** <dl>
7484 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7485 **   Checkpoint as many frames as possible without waiting for any database
7486 **   readers or writers to finish. Sync the db file if all frames in the log
7487 **   are checkpointed. This mode is the same as calling
7488 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7489 **
7490 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7491 **   This mode blocks (calls the busy-handler callback) until there is no
7492 **   database writer and all readers are reading from the most recent database
7493 **   snapshot. It then checkpoints all frames in the log file and syncs the
7494 **   database file. This call blocks database writers while it is running,
7495 **   but not database readers.
7496 **
7497 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7498 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7499 **   checkpointing the log file it blocks (calls the busy-handler callback)
7500 **   until all readers are reading from the database file only. This ensures
7501 **   that the next client to write to the database file restarts the log file
7502 **   from the beginning. This call blocks database writers while it is running,
7503 **   but not database readers.
7504 ** </dl>
7505 **
7506 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7507 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7508 ** the total number of checkpointed frames (including any that were already
7509 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7510 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7511 ** If no values are available because of an error, they are both set to -1
7512 ** before returning to communicate this to the caller.
7513 **
7514 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7515 ** any other process is running a checkpoint operation at the same time, the
7516 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7517 ** busy-handler configured, it will not be invoked in this case.
7518 **
7519 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7520 ** "writer" lock on the database file. If the writer lock cannot be obtained
7521 ** immediately, and a busy-handler is configured, it is invoked and the writer
7522 ** lock retried until either the busy-handler returns 0 or the lock is
7523 ** successfully obtained. The busy-handler is also invoked while waiting for
7524 ** database readers as described above. If the busy-handler returns 0 before
7525 ** the writer lock is obtained or while waiting for database readers, the
7526 ** checkpoint operation proceeds from that point in the same way as
7527 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7528 ** without blocking any further. SQLITE_BUSY is returned in this case.
7529 **
7530 ** If parameter zDb is NULL or points to a zero length string, then the
7531 ** specified operation is attempted on all WAL databases. In this case the
7532 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7533 ** an SQLITE_BUSY error is encountered when processing one or more of the
7534 ** attached WAL databases, the operation is still attempted on any remaining
7535 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7536 ** error occurs while processing an attached database, processing is abandoned
7537 ** and the error code returned to the caller immediately. If no error
7538 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7539 ** databases, SQLITE_OK is returned.
7540 **
7541 ** If database zDb is the name of an attached database that is not in WAL
7542 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7543 ** zDb is not NULL (or a zero length string) and is not the name of any
7544 ** attached database, SQLITE_ERROR is returned to the caller.
7545 */
7546 SQLITE_API int sqlite3_wal_checkpoint_v2(
7547   sqlite3 *db,                    /* Database handle */
7548   const char *zDb,                /* Name of attached database (or NULL) */
7549   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7550   int *pnLog,                     /* OUT: Size of WAL log in frames */
7551   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7552 );
7553
7554 /*
7555 ** CAPI3REF: Checkpoint operation parameters
7556 **
7557 ** These constants can be used as the 3rd parameter to
7558 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7559 ** documentation for additional information about the meaning and use of
7560 ** each of these values.
7561 */
7562 #define SQLITE_CHECKPOINT_PASSIVE 0
7563 #define SQLITE_CHECKPOINT_FULL    1
7564 #define SQLITE_CHECKPOINT_RESTART 2
7565
7566 /*
7567 ** CAPI3REF: Virtual Table Interface Configuration
7568 **
7569 ** This function may be called by either the [xConnect] or [xCreate] method
7570 ** of a [virtual table] implementation to configure
7571 ** various facets of the virtual table interface.
7572 **
7573 ** If this interface is invoked outside the context of an xConnect or
7574 ** xCreate virtual table method then the behavior is undefined.
7575 **
7576 ** At present, there is only one option that may be configured using
7577 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7578 ** may be added in the future.
7579 */
7580 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7581
7582 /*
7583 ** CAPI3REF: Virtual Table Configuration Options
7584 **
7585 ** These macros define the various options to the
7586 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7587 ** can use to customize and optimize their behavior.
7588 **
7589 ** <dl>
7590 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7591 ** <dd>Calls of the form
7592 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7593 ** where X is an integer.  If X is zero, then the [virtual table] whose
7594 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7595 ** support constraints.  In this configuration (which is the default) if
7596 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7597 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7598 ** specified as part of the users SQL statement, regardless of the actual
7599 ** ON CONFLICT mode specified.
7600 **
7601 ** If X is non-zero, then the virtual table implementation guarantees
7602 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7603 ** any modifications to internal or persistent data structures have been made.
7604 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7605 ** is able to roll back a statement or database transaction, and abandon
7606 ** or continue processing the current SQL statement as appropriate.
7607 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7608 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7609 ** had been ABORT.
7610 **
7611 ** Virtual table implementations that are required to handle OR REPLACE
7612 ** must do so within the [xUpdate] method. If a call to the
7613 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7614 ** CONFLICT policy is REPLACE, the virtual table implementation should
7615 ** silently replace the appropriate rows within the xUpdate callback and
7616 ** return SQLITE_OK. Or, if this is not possible, it may return
7617 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7618 ** constraint handling.
7619 ** </dl>
7620 */
7621 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7622
7623 /*
7624 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7625 **
7626 ** This function may only be called from within a call to the [xUpdate] method
7627 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7628 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7629 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7630 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7631 ** [virtual table].
7632 */
7633 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7634
7635 /*
7636 ** CAPI3REF: Conflict resolution modes
7637 **
7638 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7639 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7640 ** is for the SQL statement being evaluated.
7641 **
7642 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7643 ** return value from the [sqlite3_set_authorizer()] callback and that
7644 ** [SQLITE_ABORT] is also a [result code].
7645 */
7646 #define SQLITE_ROLLBACK 1
7647 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7648 #define SQLITE_FAIL     3
7649 /* #define SQLITE_ABORT 4  // Also an error code */
7650 #define SQLITE_REPLACE  5
7651
7652
7653
7654 /*
7655 ** Undo the hack that converts floating point types to integer for
7656 ** builds on processors without floating point support.
7657 */
7658 #ifdef SQLITE_OMIT_FLOATING_POINT
7659 # undef double
7660 #endif
7661
7662 #if 0
7663 }  /* End of the 'extern "C"' block */
7664 #endif
7665 #endif
7666
7667 /*
7668 ** 2010 August 30
7669 **
7670 ** The author disclaims copyright to this source code.  In place of
7671 ** a legal notice, here is a blessing:
7672 **
7673 **    May you do good and not evil.
7674 **    May you find forgiveness for yourself and forgive others.
7675 **    May you share freely, never taking more than you give.
7676 **
7677 *************************************************************************
7678 */
7679
7680 #ifndef _SQLITE3RTREE_H_
7681 #define _SQLITE3RTREE_H_
7682
7683
7684 #if 0
7685 extern "C" {
7686 #endif
7687
7688 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7689
7690 /*
7691 ** Register a geometry callback named zGeom that can be used as part of an
7692 ** R-Tree geometry query as follows:
7693 **
7694 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7695 */
7696 SQLITE_API int sqlite3_rtree_geometry_callback(
7697   sqlite3 *db,
7698   const char *zGeom,
7699 #ifdef SQLITE_RTREE_INT_ONLY
7700   int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7701 #else
7702   int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7703 #endif
7704   void *pContext
7705 );
7706
7707
7708 /*
7709 ** A pointer to a structure of the following type is passed as the first
7710 ** argument to callbacks registered using rtree_geometry_callback().
7711 */
7712 struct sqlite3_rtree_geometry {
7713   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7714   int nParam;                     /* Size of array aParam[] */
7715   double *aParam;                 /* Parameters passed to SQL geom function */
7716   void *pUser;                    /* Callback implementation user data */
7717   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7718 };
7719
7720
7721 #if 0
7722 }  /* end of the 'extern "C"' block */
7723 #endif
7724
7725 #endif  /* ifndef _SQLITE3RTREE_H_ */
7726
7727
7728 /************** End of sqlite3.h *********************************************/
7729 /************** Continuing where we left off in sqliteInt.h ******************/
7730 /************** Include hash.h in the middle of sqliteInt.h ******************/
7731 /************** Begin file hash.h ********************************************/
7732 /*
7733 ** 2001 September 22
7734 **
7735 ** The author disclaims copyright to this source code.  In place of
7736 ** a legal notice, here is a blessing:
7737 **
7738 **    May you do good and not evil.
7739 **    May you find forgiveness for yourself and forgive others.
7740 **    May you share freely, never taking more than you give.
7741 **
7742 *************************************************************************
7743 ** This is the header file for the generic hash-table implemenation
7744 ** used in SQLite.
7745 */
7746 #ifndef _SQLITE_HASH_H_
7747 #define _SQLITE_HASH_H_
7748
7749 /* Forward declarations of structures. */
7750 typedef struct Hash Hash;
7751 typedef struct HashElem HashElem;
7752
7753 /* A complete hash table is an instance of the following structure.
7754 ** The internals of this structure are intended to be opaque -- client
7755 ** code should not attempt to access or modify the fields of this structure
7756 ** directly.  Change this structure only by using the routines below.
7757 ** However, some of the "procedures" and "functions" for modifying and
7758 ** accessing this structure are really macros, so we can't really make
7759 ** this structure opaque.
7760 **
7761 ** All elements of the hash table are on a single doubly-linked list.
7762 ** Hash.first points to the head of this list.
7763 **
7764 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7765 ** the global doubly-linked list.  The contents of the bucket are the
7766 ** element pointed to plus the next _ht.count-1 elements in the list.
7767 **
7768 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7769 ** by a linear search of the global list.  For small tables, the
7770 ** Hash.ht table is never allocated because if there are few elements
7771 ** in the table, it is faster to do a linear search than to manage
7772 ** the hash table.
7773 */
7774 struct Hash {
7775   unsigned int htsize;      /* Number of buckets in the hash table */
7776   unsigned int count;       /* Number of entries in this table */
7777   HashElem *first;          /* The first element of the array */
7778   struct _ht {              /* the hash table */
7779     int count;                 /* Number of entries with this hash */
7780     HashElem *chain;           /* Pointer to first entry with this hash */
7781   } *ht;
7782 };
7783
7784 /* Each element in the hash table is an instance of the following
7785 ** structure.  All elements are stored on a single doubly-linked list.
7786 **
7787 ** Again, this structure is intended to be opaque, but it can't really
7788 ** be opaque because it is used by macros.
7789 */
7790 struct HashElem {
7791   HashElem *next, *prev;       /* Next and previous elements in the table */
7792   void *data;                  /* Data associated with this element */
7793   const char *pKey; int nKey;  /* Key associated with this element */
7794 };
7795
7796 /*
7797 ** Access routines.  To delete, insert a NULL pointer.
7798 */
7799 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7800 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7801 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7802 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7803
7804 /*
7805 ** Macros for looping over all elements of a hash table.  The idiom is
7806 ** like this:
7807 **
7808 **   Hash h;
7809 **   HashElem *p;
7810 **   ...
7811 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7812 **     SomeStructure *pData = sqliteHashData(p);
7813 **     // do something with pData
7814 **   }
7815 */
7816 #define sqliteHashFirst(H)  ((H)->first)
7817 #define sqliteHashNext(E)   ((E)->next)
7818 #define sqliteHashData(E)   ((E)->data)
7819 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7820 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7821
7822 /*
7823 ** Number of entries in a hash table
7824 */
7825 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7826
7827 #endif /* _SQLITE_HASH_H_ */
7828
7829 /************** End of hash.h ************************************************/
7830 /************** Continuing where we left off in sqliteInt.h ******************/
7831 /************** Include parse.h in the middle of sqliteInt.h *****************/
7832 /************** Begin file parse.h *******************************************/
7833 #define TK_SEMI                            1
7834 #define TK_EXPLAIN                         2
7835 #define TK_QUERY                           3
7836 #define TK_PLAN                            4
7837 #define TK_BEGIN                           5
7838 #define TK_TRANSACTION                     6
7839 #define TK_DEFERRED                        7
7840 #define TK_IMMEDIATE                       8
7841 #define TK_EXCLUSIVE                       9
7842 #define TK_COMMIT                         10
7843 #define TK_END                            11
7844 #define TK_ROLLBACK                       12
7845 #define TK_SAVEPOINT                      13
7846 #define TK_RELEASE                        14
7847 #define TK_TO                             15
7848 #define TK_TABLE                          16
7849 #define TK_CREATE                         17
7850 #define TK_IF                             18
7851 #define TK_NOT                            19
7852 #define TK_EXISTS                         20
7853 #define TK_TEMP                           21
7854 #define TK_LP                             22
7855 #define TK_RP                             23
7856 #define TK_AS                             24
7857 #define TK_COMMA                          25
7858 #define TK_ID                             26
7859 #define TK_INDEXED                        27
7860 #define TK_ABORT                          28
7861 #define TK_ACTION                         29
7862 #define TK_AFTER                          30
7863 #define TK_ANALYZE                        31
7864 #define TK_ASC                            32
7865 #define TK_ATTACH                         33
7866 #define TK_BEFORE                         34
7867 #define TK_BY                             35
7868 #define TK_CASCADE                        36
7869 #define TK_CAST                           37
7870 #define TK_COLUMNKW                       38
7871 #define TK_CONFLICT                       39
7872 #define TK_DATABASE                       40
7873 #define TK_DESC                           41
7874 #define TK_DETACH                         42
7875 #define TK_EACH                           43
7876 #define TK_FAIL                           44
7877 #define TK_FOR                            45
7878 #define TK_IGNORE                         46
7879 #define TK_INITIALLY                      47
7880 #define TK_INSTEAD                        48
7881 #define TK_LIKE_KW                        49
7882 #define TK_MATCH                          50
7883 #define TK_NO                             51
7884 #define TK_KEY                            52
7885 #define TK_OF                             53
7886 #define TK_OFFSET                         54
7887 #define TK_PRAGMA                         55
7888 #define TK_RAISE                          56
7889 #define TK_REPLACE                        57
7890 #define TK_RESTRICT                       58
7891 #define TK_ROW                            59
7892 #define TK_TRIGGER                        60
7893 #define TK_VACUUM                         61
7894 #define TK_VIEW                           62
7895 #define TK_VIRTUAL                        63
7896 #define TK_REINDEX                        64
7897 #define TK_RENAME                         65
7898 #define TK_CTIME_KW                       66
7899 #define TK_ANY                            67
7900 #define TK_OR                             68
7901 #define TK_AND                            69
7902 #define TK_IS                             70
7903 #define TK_BETWEEN                        71
7904 #define TK_IN                             72
7905 #define TK_ISNULL                         73
7906 #define TK_NOTNULL                        74
7907 #define TK_NE                             75
7908 #define TK_EQ                             76
7909 #define TK_GT                             77
7910 #define TK_LE                             78
7911 #define TK_LT                             79
7912 #define TK_GE                             80
7913 #define TK_ESCAPE                         81
7914 #define TK_BITAND                         82
7915 #define TK_BITOR                          83
7916 #define TK_LSHIFT                         84
7917 #define TK_RSHIFT                         85
7918 #define TK_PLUS                           86
7919 #define TK_MINUS                          87
7920 #define TK_STAR                           88
7921 #define TK_SLASH                          89
7922 #define TK_REM                            90
7923 #define TK_CONCAT                         91
7924 #define TK_COLLATE                        92
7925 #define TK_BITNOT                         93
7926 #define TK_STRING                         94
7927 #define TK_JOIN_KW                        95
7928 #define TK_CONSTRAINT                     96
7929 #define TK_DEFAULT                        97
7930 #define TK_NULL                           98
7931 #define TK_PRIMARY                        99
7932 #define TK_UNIQUE                         100
7933 #define TK_CHECK                          101
7934 #define TK_REFERENCES                     102
7935 #define TK_AUTOINCR                       103
7936 #define TK_ON                             104
7937 #define TK_INSERT                         105
7938 #define TK_DELETE                         106
7939 #define TK_UPDATE                         107
7940 #define TK_SET                            108
7941 #define TK_DEFERRABLE                     109
7942 #define TK_FOREIGN                        110
7943 #define TK_DROP                           111
7944 #define TK_UNION                          112
7945 #define TK_ALL                            113
7946 #define TK_EXCEPT                         114
7947 #define TK_INTERSECT                      115
7948 #define TK_SELECT                         116
7949 #define TK_DISTINCT                       117
7950 #define TK_DOT                            118
7951 #define TK_FROM                           119
7952 #define TK_JOIN                           120
7953 #define TK_USING                          121
7954 #define TK_ORDER                          122
7955 #define TK_GROUP                          123
7956 #define TK_HAVING                         124
7957 #define TK_LIMIT                          125
7958 #define TK_WHERE                          126
7959 #define TK_INTO                           127
7960 #define TK_VALUES                         128
7961 #define TK_INTEGER                        129
7962 #define TK_FLOAT                          130
7963 #define TK_BLOB                           131
7964 #define TK_REGISTER                       132
7965 #define TK_VARIABLE                       133
7966 #define TK_CASE                           134
7967 #define TK_WHEN                           135
7968 #define TK_THEN                           136
7969 #define TK_ELSE                           137
7970 #define TK_INDEX                          138
7971 #define TK_ALTER                          139
7972 #define TK_ADD                            140
7973 #define TK_TO_TEXT                        141
7974 #define TK_TO_BLOB                        142
7975 #define TK_TO_NUMERIC                     143
7976 #define TK_TO_INT                         144
7977 #define TK_TO_REAL                        145
7978 #define TK_ISNOT                          146
7979 #define TK_END_OF_FILE                    147
7980 #define TK_ILLEGAL                        148
7981 #define TK_SPACE                          149
7982 #define TK_UNCLOSED_STRING                150
7983 #define TK_FUNCTION                       151
7984 #define TK_COLUMN                         152
7985 #define TK_AGG_FUNCTION                   153
7986 #define TK_AGG_COLUMN                     154
7987 #define TK_CONST_FUNC                     155
7988 #define TK_UMINUS                         156
7989 #define TK_UPLUS                          157
7990
7991 /************** End of parse.h ***********************************************/
7992 /************** Continuing where we left off in sqliteInt.h ******************/
7993 #include <stdio.h>
7994 #include <stdlib.h>
7995 #include <string.h>
7996 #include <assert.h>
7997 #include <stddef.h>
7998
7999 /*
8000 ** If compiling for a processor that lacks floating point support,
8001 ** substitute integer for floating-point
8002 */
8003 #ifdef SQLITE_OMIT_FLOATING_POINT
8004 # define double sqlite_int64
8005 # define float sqlite_int64
8006 # define LONGDOUBLE_TYPE sqlite_int64
8007 # ifndef SQLITE_BIG_DBL
8008 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8009 # endif
8010 # define SQLITE_OMIT_DATETIME_FUNCS 1
8011 # define SQLITE_OMIT_TRACE 1
8012 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8013 # undef SQLITE_HAVE_ISNAN
8014 #endif
8015 #ifndef SQLITE_BIG_DBL
8016 # define SQLITE_BIG_DBL (1e99)
8017 #endif
8018
8019 /*
8020 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8021 ** afterward. Having this macro allows us to cause the C compiler
8022 ** to omit code used by TEMP tables without messy #ifndef statements.
8023 */
8024 #ifdef SQLITE_OMIT_TEMPDB
8025 #define OMIT_TEMPDB 1
8026 #else
8027 #define OMIT_TEMPDB 0
8028 #endif
8029
8030 /*
8031 ** The "file format" number is an integer that is incremented whenever
8032 ** the VDBE-level file format changes.  The following macros define the
8033 ** the default file format for new databases and the maximum file format
8034 ** that the library can read.
8035 */
8036 #define SQLITE_MAX_FILE_FORMAT 4
8037 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8038 # define SQLITE_DEFAULT_FILE_FORMAT 4
8039 #endif
8040
8041 /*
8042 ** Determine whether triggers are recursive by default.  This can be
8043 ** changed at run-time using a pragma.
8044 */
8045 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8046 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8047 #endif
8048
8049 /*
8050 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8051 ** on the command-line
8052 */
8053 #ifndef SQLITE_TEMP_STORE
8054 # define SQLITE_TEMP_STORE 1
8055 #endif
8056
8057 /*
8058 ** GCC does not define the offsetof() macro so we'll have to do it
8059 ** ourselves.
8060 */
8061 #ifndef offsetof
8062 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8063 #endif
8064
8065 /*
8066 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8067 ** not, there are still machines out there that use EBCDIC.)
8068 */
8069 #if 'A' == '\301'
8070 # define SQLITE_EBCDIC 1
8071 #else
8072 # define SQLITE_ASCII 1
8073 #endif
8074
8075 /*
8076 ** Integers of known sizes.  These typedefs might change for architectures
8077 ** where the sizes very.  Preprocessor macros are available so that the
8078 ** types can be conveniently redefined at compile-type.  Like this:
8079 **
8080 **         cc '-DUINTPTR_TYPE=long long int' ...
8081 */
8082 #ifndef UINT32_TYPE
8083 # ifdef HAVE_UINT32_T
8084 #  define UINT32_TYPE uint32_t
8085 # else
8086 #  define UINT32_TYPE unsigned int
8087 # endif
8088 #endif
8089 #ifndef UINT16_TYPE
8090 # ifdef HAVE_UINT16_T
8091 #  define UINT16_TYPE uint16_t
8092 # else
8093 #  define UINT16_TYPE unsigned short int
8094 # endif
8095 #endif
8096 #ifndef INT16_TYPE
8097 # ifdef HAVE_INT16_T
8098 #  define INT16_TYPE int16_t
8099 # else
8100 #  define INT16_TYPE short int
8101 # endif
8102 #endif
8103 #ifndef UINT8_TYPE
8104 # ifdef HAVE_UINT8_T
8105 #  define UINT8_TYPE uint8_t
8106 # else
8107 #  define UINT8_TYPE unsigned char
8108 # endif
8109 #endif
8110 #ifndef INT8_TYPE
8111 # ifdef HAVE_INT8_T
8112 #  define INT8_TYPE int8_t
8113 # else
8114 #  define INT8_TYPE signed char
8115 # endif
8116 #endif
8117 #ifndef LONGDOUBLE_TYPE
8118 # define LONGDOUBLE_TYPE long double
8119 #endif
8120 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8121 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8122 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8123 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8124 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8125 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8126 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8127
8128 /*
8129 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8130 ** that can be stored in a u32 without loss of data.  The value
8131 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8132 ** have to specify the value in the less intuitive manner shown:
8133 */
8134 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8135
8136 /*
8137 ** The datatype used to store estimates of the number of rows in a
8138 ** table or index.  This is an unsigned integer type.  For 99.9% of
8139 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8140 ** can be used at compile-time if desired.
8141 */
8142 #ifdef SQLITE_64BIT_STATS
8143  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8144 #else
8145  typedef u32 tRowcnt;    /* 32-bit is the default */
8146 #endif
8147
8148 /*
8149 ** Macros to determine whether the machine is big or little endian,
8150 ** evaluated at runtime.
8151 */
8152 #ifdef SQLITE_AMALGAMATION
8153 SQLITE_PRIVATE const int sqlite3one = 1;
8154 #else
8155 SQLITE_PRIVATE const int sqlite3one;
8156 #endif
8157 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8158                              || defined(__x86_64) || defined(__x86_64__)
8159 # define SQLITE_BIGENDIAN    0
8160 # define SQLITE_LITTLEENDIAN 1
8161 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8162 #else
8163 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8164 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8165 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8166 #endif
8167
8168 /*
8169 ** Constants for the largest and smallest possible 64-bit signed integers.
8170 ** These macros are designed to work correctly on both 32-bit and 64-bit
8171 ** compilers.
8172 */
8173 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8174 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8175
8176 /*
8177 ** Round up a number to the next larger multiple of 8.  This is used
8178 ** to force 8-byte alignment on 64-bit architectures.
8179 */
8180 #define ROUND8(x)     (((x)+7)&~7)
8181
8182 /*
8183 ** Round down to the nearest multiple of 8
8184 */
8185 #define ROUNDDOWN8(x) ((x)&~7)
8186
8187 /*
8188 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
8189 ** macro is used only within assert() to verify that the code gets
8190 ** all alignment restrictions correct.
8191 **
8192 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8193 ** underlying malloc() implemention might return us 4-byte aligned
8194 ** pointers.  In that case, only verify 4-byte alignment.
8195 */
8196 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8197 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8198 #else
8199 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8200 #endif
8201
8202
8203 /*
8204 ** An instance of the following structure is used to store the busy-handler
8205 ** callback for a given sqlite handle.
8206 **
8207 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8208 ** callback for the database handle. Each pager opened via the sqlite
8209 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8210 ** callback is currently invoked only from within pager.c.
8211 */
8212 typedef struct BusyHandler BusyHandler;
8213 struct BusyHandler {
8214   int (*xFunc)(void *,int);  /* The busy callback */
8215   void *pArg;                /* First arg to busy callback */
8216   int nBusy;                 /* Incremented with each busy call */
8217 };
8218
8219 /*
8220 ** Name of the master database table.  The master database table
8221 ** is a special table that holds the names and attributes of all
8222 ** user tables and indices.
8223 */
8224 #define MASTER_NAME       "sqlite_master"
8225 #define TEMP_MASTER_NAME  "sqlite_temp_master"
8226
8227 /*
8228 ** The root-page of the master database table.
8229 */
8230 #define MASTER_ROOT       1
8231
8232 /*
8233 ** The name of the schema table.
8234 */
8235 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8236
8237 /*
8238 ** A convenience macro that returns the number of elements in
8239 ** an array.
8240 */
8241 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8242
8243 /*
8244 ** The following value as a destructor means to use sqlite3DbFree().
8245 ** The sqlite3DbFree() routine requires two parameters instead of the
8246 ** one parameter that destructors normally want.  So we have to introduce
8247 ** this magic value that the code knows to handle differently.  Any
8248 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8249 ** and SQLITE_TRANSIENT.
8250 */
8251 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8252
8253 /*
8254 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8255 ** not support Writable Static Data (WSD) such as global and static variables.
8256 ** All variables must either be on the stack or dynamically allocated from
8257 ** the heap.  When WSD is unsupported, the variable declarations scattered
8258 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8259 ** macro is used for this purpose.  And instead of referencing the variable
8260 ** directly, we use its constant as a key to lookup the run-time allocated
8261 ** buffer that holds real variable.  The constant is also the initializer
8262 ** for the run-time allocated buffer.
8263 **
8264 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8265 ** macros become no-ops and have zero performance impact.
8266 */
8267 #ifdef SQLITE_OMIT_WSD
8268   #define SQLITE_WSD const
8269   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8270   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8271 SQLITE_API   int sqlite3_wsd_init(int N, int J);
8272 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8273 #else
8274   #define SQLITE_WSD
8275   #define GLOBAL(t,v) v
8276   #define sqlite3GlobalConfig sqlite3Config
8277 #endif
8278
8279 /*
8280 ** The following macros are used to suppress compiler warnings and to
8281 ** make it clear to human readers when a function parameter is deliberately
8282 ** left unused within the body of a function. This usually happens when
8283 ** a function is called via a function pointer. For example the
8284 ** implementation of an SQL aggregate step callback may not use the
8285 ** parameter indicating the number of arguments passed to the aggregate,
8286 ** if it knows that this is enforced elsewhere.
8287 **
8288 ** When a function parameter is not used at all within the body of a function,
8289 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8290 ** However, these macros may also be used to suppress warnings related to
8291 ** parameters that may or may not be used depending on compilation options.
8292 ** For example those parameters only used in assert() statements. In these
8293 ** cases the parameters are named as per the usual conventions.
8294 */
8295 #define UNUSED_PARAMETER(x) (void)(x)
8296 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8297
8298 /*
8299 ** Forward references to structures
8300 */
8301 typedef struct AggInfo AggInfo;
8302 typedef struct AuthContext AuthContext;
8303 typedef struct AutoincInfo AutoincInfo;
8304 typedef struct Bitvec Bitvec;
8305 typedef struct CollSeq CollSeq;
8306 typedef struct Column Column;
8307 typedef struct Db Db;
8308 typedef struct Schema Schema;
8309 typedef struct Expr Expr;
8310 typedef struct ExprList ExprList;
8311 typedef struct ExprSpan ExprSpan;
8312 typedef struct FKey FKey;
8313 typedef struct FuncDestructor FuncDestructor;
8314 typedef struct FuncDef FuncDef;
8315 typedef struct FuncDefHash FuncDefHash;
8316 typedef struct IdList IdList;
8317 typedef struct Index Index;
8318 typedef struct IndexSample IndexSample;
8319 typedef struct KeyClass KeyClass;
8320 typedef struct KeyInfo KeyInfo;
8321 typedef struct Lookaside Lookaside;
8322 typedef struct LookasideSlot LookasideSlot;
8323 typedef struct Module Module;
8324 typedef struct NameContext NameContext;
8325 typedef struct Parse Parse;
8326 typedef struct RowSet RowSet;
8327 typedef struct Savepoint Savepoint;
8328 typedef struct Select Select;
8329 typedef struct SelectDest SelectDest;
8330 typedef struct SrcList SrcList;
8331 typedef struct StrAccum StrAccum;
8332 typedef struct Table Table;
8333 typedef struct TableLock TableLock;
8334 typedef struct Token Token;
8335 typedef struct Trigger Trigger;
8336 typedef struct TriggerPrg TriggerPrg;
8337 typedef struct TriggerStep TriggerStep;
8338 typedef struct UnpackedRecord UnpackedRecord;
8339 typedef struct VTable VTable;
8340 typedef struct VtabCtx VtabCtx;
8341 typedef struct Walker Walker;
8342 typedef struct WherePlan WherePlan;
8343 typedef struct WhereInfo WhereInfo;
8344 typedef struct WhereLevel WhereLevel;
8345
8346 /*
8347 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8348 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8349 ** pointer types (i.e. FuncDef) defined above.
8350 */
8351 /************** Include btree.h in the middle of sqliteInt.h *****************/
8352 /************** Begin file btree.h *******************************************/
8353 /*
8354 ** 2001 September 15
8355 **
8356 ** The author disclaims copyright to this source code.  In place of
8357 ** a legal notice, here is a blessing:
8358 **
8359 **    May you do good and not evil.
8360 **    May you find forgiveness for yourself and forgive others.
8361 **    May you share freely, never taking more than you give.
8362 **
8363 *************************************************************************
8364 ** This header file defines the interface that the sqlite B-Tree file
8365 ** subsystem.  See comments in the source code for a detailed description
8366 ** of what each interface routine does.
8367 */
8368 #ifndef _BTREE_H_
8369 #define _BTREE_H_
8370
8371 /* TODO: This definition is just included so other modules compile. It
8372 ** needs to be revisited.
8373 */
8374 #define SQLITE_N_BTREE_META 10
8375
8376 /*
8377 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8378 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8379 */
8380 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8381   #define SQLITE_DEFAULT_AUTOVACUUM 0
8382 #endif
8383
8384 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8385 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8386 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8387
8388 /*
8389 ** Forward declarations of structure
8390 */
8391 typedef struct Btree Btree;
8392 typedef struct BtCursor BtCursor;
8393 typedef struct BtShared BtShared;
8394
8395
8396 SQLITE_PRIVATE int sqlite3BtreeOpen(
8397   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8398   const char *zFilename,   /* Name of database file to open */
8399   sqlite3 *db,             /* Associated database connection */
8400   Btree **ppBtree,         /* Return open Btree* here */
8401   int flags,               /* Flags */
8402   int vfsFlags             /* Flags passed through to VFS open */
8403 );
8404
8405 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8406 ** following values.
8407 **
8408 ** NOTE:  These values must match the corresponding PAGER_ values in
8409 ** pager.h.
8410 */
8411 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8412 #define BTREE_MEMORY        2  /* This is an in-memory DB */
8413 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8414 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8415
8416 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8417 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8418 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8419 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8420 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8421 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8422 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8423 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8424 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8425 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8426 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8427 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8428 #endif
8429 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8430 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8431 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8432 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8433 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8434 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8435 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8436 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8437 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8438 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8439 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8440 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8441 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8442 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8443 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8444 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8445
8446 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8447 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8448 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8449
8450 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8451
8452 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8453 ** of the flags shown below.
8454 **
8455 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8456 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8457 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8458 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8459 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8460 ** indices.)
8461 */
8462 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8463 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8464
8465 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8466 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8467 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8468
8469 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8470 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8471
8472 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8473
8474 /*
8475 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8476 ** should be one of the following values. The integer values are assigned
8477 ** to constants so that the offset of the corresponding field in an
8478 ** SQLite database header may be found using the following formula:
8479 **
8480 **   offset = 36 + (idx * 4)
8481 **
8482 ** For example, the free-page-count field is located at byte offset 36 of
8483 ** the database file header. The incr-vacuum-flag field is located at
8484 ** byte offset 64 (== 36+4*7).
8485 */
8486 #define BTREE_FREE_PAGE_COUNT     0
8487 #define BTREE_SCHEMA_VERSION      1
8488 #define BTREE_FILE_FORMAT         2
8489 #define BTREE_DEFAULT_CACHE_SIZE  3
8490 #define BTREE_LARGEST_ROOT_PAGE   4
8491 #define BTREE_TEXT_ENCODING       5
8492 #define BTREE_USER_VERSION        6
8493 #define BTREE_INCR_VACUUM         7
8494
8495 /*
8496 ** Values that may be OR'd together to form the second argument of an
8497 ** sqlite3BtreeCursorHints() call.
8498 */
8499 #define BTREE_BULKLOAD 0x00000001
8500
8501 SQLITE_PRIVATE int sqlite3BtreeCursor(
8502   Btree*,                              /* BTree containing table to open */
8503   int iTable,                          /* Index of root page */
8504   int wrFlag,                          /* 1 for writing.  0 for read-only */
8505   struct KeyInfo*,                     /* First argument to compare function */
8506   BtCursor *pCursor                    /* Space to write cursor structure */
8507 );
8508 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8509 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8510
8511 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8512 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8513   BtCursor*,
8514   UnpackedRecord *pUnKey,
8515   i64 intKey,
8516   int bias,
8517   int *pRes
8518 );
8519 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8520 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8521 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8522                                   const void *pData, int nData,
8523                                   int nZero, int bias, int seekResult);
8524 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8525 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8526 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8527 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8528 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8529 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8530 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8531 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8532 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8533 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8534 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8535 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8536 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8537
8538 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8539 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8540
8541 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8542 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8543 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8544 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8545 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8546
8547 #ifndef NDEBUG
8548 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8549 #endif
8550
8551 #ifndef SQLITE_OMIT_BTREECOUNT
8552 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8553 #endif
8554
8555 #ifdef SQLITE_TEST
8556 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8557 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8558 #endif
8559
8560 #ifndef SQLITE_OMIT_WAL
8561 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8562 #endif
8563
8564 /*
8565 ** If we are not using shared cache, then there is no need to
8566 ** use mutexes to access the BtShared structures.  So make the
8567 ** Enter and Leave procedures no-ops.
8568 */
8569 #ifndef SQLITE_OMIT_SHARED_CACHE
8570 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8571 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8572 #else
8573 # define sqlite3BtreeEnter(X)
8574 # define sqlite3BtreeEnterAll(X)
8575 #endif
8576
8577 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8578 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8579 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8580 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8581 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8582 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8583 #ifndef NDEBUG
8584   /* These routines are used inside assert() statements only. */
8585 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8586 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8587 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8588 #endif
8589 #else
8590
8591 # define sqlite3BtreeSharable(X) 0
8592 # define sqlite3BtreeLeave(X)
8593 # define sqlite3BtreeEnterCursor(X)
8594 # define sqlite3BtreeLeaveCursor(X)
8595 # define sqlite3BtreeLeaveAll(X)
8596
8597 # define sqlite3BtreeHoldsMutex(X) 1
8598 # define sqlite3BtreeHoldsAllMutexes(X) 1
8599 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8600 #endif
8601
8602
8603 #endif /* _BTREE_H_ */
8604
8605 /************** End of btree.h ***********************************************/
8606 /************** Continuing where we left off in sqliteInt.h ******************/
8607 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8608 /************** Begin file vdbe.h ********************************************/
8609 /*
8610 ** 2001 September 15
8611 **
8612 ** The author disclaims copyright to this source code.  In place of
8613 ** a legal notice, here is a blessing:
8614 **
8615 **    May you do good and not evil.
8616 **    May you find forgiveness for yourself and forgive others.
8617 **    May you share freely, never taking more than you give.
8618 **
8619 *************************************************************************
8620 ** Header file for the Virtual DataBase Engine (VDBE)
8621 **
8622 ** This header defines the interface to the virtual database engine
8623 ** or VDBE.  The VDBE implements an abstract machine that runs a
8624 ** simple program to access and modify the underlying database.
8625 */
8626 #ifndef _SQLITE_VDBE_H_
8627 #define _SQLITE_VDBE_H_
8628 /* #include <stdio.h> */
8629
8630 /*
8631 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8632 ** in the source file sqliteVdbe.c are allowed to see the insides
8633 ** of this structure.
8634 */
8635 typedef struct Vdbe Vdbe;
8636
8637 /*
8638 ** The names of the following types declared in vdbeInt.h are required
8639 ** for the VdbeOp definition.
8640 */
8641 typedef struct VdbeFunc VdbeFunc;
8642 typedef struct Mem Mem;
8643 typedef struct SubProgram SubProgram;
8644
8645 /*
8646 ** A single instruction of the virtual machine has an opcode
8647 ** and as many as three operands.  The instruction is recorded
8648 ** as an instance of the following structure:
8649 */
8650 struct VdbeOp {
8651   u8 opcode;          /* What operation to perform */
8652   signed char p4type; /* One of the P4_xxx constants for p4 */
8653   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8654   u8 p5;              /* Fifth parameter is an unsigned character */
8655   int p1;             /* First operand */
8656   int p2;             /* Second parameter (often the jump destination) */
8657   int p3;             /* The third parameter */
8658   union {             /* fourth parameter */
8659     int i;                 /* Integer value if p4type==P4_INT32 */
8660     void *p;               /* Generic pointer */
8661     char *z;               /* Pointer to data for string (char array) types */
8662     i64 *pI64;             /* Used when p4type is P4_INT64 */
8663     double *pReal;         /* Used when p4type is P4_REAL */
8664     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8665     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8666     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8667     Mem *pMem;             /* Used when p4type is P4_MEM */
8668     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8669     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8670     int *ai;               /* Used when p4type is P4_INTARRAY */
8671     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8672     int (*xAdvance)(BtCursor *, int *);
8673   } p4;
8674 #ifdef SQLITE_DEBUG
8675   char *zComment;          /* Comment to improve readability */
8676 #endif
8677 #ifdef VDBE_PROFILE
8678   int cnt;                 /* Number of times this instruction was executed */
8679   u64 cycles;              /* Total time spent executing this instruction */
8680 #endif
8681 };
8682 typedef struct VdbeOp VdbeOp;
8683
8684
8685 /*
8686 ** A sub-routine used to implement a trigger program.
8687 */
8688 struct SubProgram {
8689   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8690   int nOp;                      /* Elements in aOp[] */
8691   int nMem;                     /* Number of memory cells required */
8692   int nCsr;                     /* Number of cursors required */
8693   int nOnce;                    /* Number of OP_Once instructions */
8694   void *token;                  /* id that may be used to recursive triggers */
8695   SubProgram *pNext;            /* Next sub-program already visited */
8696 };
8697
8698 /*
8699 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8700 ** it takes up less space.
8701 */
8702 struct VdbeOpList {
8703   u8 opcode;          /* What operation to perform */
8704   signed char p1;     /* First operand */
8705   signed char p2;     /* Second parameter (often the jump destination) */
8706   signed char p3;     /* Third parameter */
8707 };
8708 typedef struct VdbeOpList VdbeOpList;
8709
8710 /*
8711 ** Allowed values of VdbeOp.p4type
8712 */
8713 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8714 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8715 #define P4_STATIC   (-2)  /* Pointer to a static string */
8716 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8717 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8718 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8719 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8720 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8721 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8722 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8723 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8724 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8725 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8726 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8727 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8728 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8729 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8730
8731 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8732 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8733 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8734 ** gets freed when the Vdbe is finalized so it still should be obtained
8735 ** from a single sqliteMalloc().  But no copy is made and the calling
8736 ** function should *not* try to free the KeyInfo.
8737 */
8738 #define P4_KEYINFO_HANDOFF (-16)
8739 #define P4_KEYINFO_STATIC  (-17)
8740
8741 /*
8742 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
8743 ** number of columns of data returned by the statement.
8744 */
8745 #define COLNAME_NAME     0
8746 #define COLNAME_DECLTYPE 1
8747 #define COLNAME_DATABASE 2
8748 #define COLNAME_TABLE    3
8749 #define COLNAME_COLUMN   4
8750 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8751 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8752 #else
8753 # ifdef SQLITE_OMIT_DECLTYPE
8754 #   define COLNAME_N      1      /* Store only the name */
8755 # else
8756 #   define COLNAME_N      2      /* Store the name and decltype */
8757 # endif
8758 #endif
8759
8760 /*
8761 ** The following macro converts a relative address in the p2 field
8762 ** of a VdbeOp structure into a negative number so that
8763 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8764 ** the macro again restores the address.
8765 */
8766 #define ADDR(X)  (-1-(X))
8767
8768 /*
8769 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8770 ** header file that defines a number for each opcode used by the VDBE.
8771 */
8772 /************** Include opcodes.h in the middle of vdbe.h ********************/
8773 /************** Begin file opcodes.h *****************************************/
8774 /* Automatically generated.  Do not edit */
8775 /* See the mkopcodeh.awk script for details */
8776 #define OP_Goto                                 1
8777 #define OP_Gosub                                2
8778 #define OP_Return                               3
8779 #define OP_Yield                                4
8780 #define OP_HaltIfNull                           5
8781 #define OP_Halt                                 6
8782 #define OP_Integer                              7
8783 #define OP_Int64                                8
8784 #define OP_Real                               130   /* same as TK_FLOAT    */
8785 #define OP_String8                             94   /* same as TK_STRING   */
8786 #define OP_String                               9
8787 #define OP_Null                                10
8788 #define OP_Blob                                11
8789 #define OP_Variable                            12
8790 #define OP_Move                                13
8791 #define OP_Copy                                14
8792 #define OP_SCopy                               15
8793 #define OP_ResultRow                           16
8794 #define OP_Concat                              91   /* same as TK_CONCAT   */
8795 #define OP_Add                                 86   /* same as TK_PLUS     */
8796 #define OP_Subtract                            87   /* same as TK_MINUS    */
8797 #define OP_Multiply                            88   /* same as TK_STAR     */
8798 #define OP_Divide                              89   /* same as TK_SLASH    */
8799 #define OP_Remainder                           90   /* same as TK_REM      */
8800 #define OP_CollSeq                             17
8801 #define OP_Function                            18
8802 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8803 #define OP_BitOr                               83   /* same as TK_BITOR    */
8804 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8805 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8806 #define OP_AddImm                              20
8807 #define OP_MustBeInt                           21
8808 #define OP_RealAffinity                        22
8809 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8810 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8811 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8812 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8813 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8814 #define OP_Eq                                  76   /* same as TK_EQ       */
8815 #define OP_Ne                                  75   /* same as TK_NE       */
8816 #define OP_Lt                                  79   /* same as TK_LT       */
8817 #define OP_Le                                  78   /* same as TK_LE       */
8818 #define OP_Gt                                  77   /* same as TK_GT       */
8819 #define OP_Ge                                  80   /* same as TK_GE       */
8820 #define OP_Permutation                         23
8821 #define OP_Compare                             24
8822 #define OP_Jump                                25
8823 #define OP_And                                 69   /* same as TK_AND      */
8824 #define OP_Or                                  68   /* same as TK_OR       */
8825 #define OP_Not                                 19   /* same as TK_NOT      */
8826 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8827 #define OP_Once                                26
8828 #define OP_If                                  27
8829 #define OP_IfNot                               28
8830 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8831 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8832 #define OP_Column                              29
8833 #define OP_Affinity                            30
8834 #define OP_MakeRecord                          31
8835 #define OP_Count                               32
8836 #define OP_Savepoint                           33
8837 #define OP_AutoCommit                          34
8838 #define OP_Transaction                         35
8839 #define OP_ReadCookie                          36
8840 #define OP_SetCookie                           37
8841 #define OP_VerifyCookie                        38
8842 #define OP_OpenRead                            39
8843 #define OP_OpenWrite                           40
8844 #define OP_OpenAutoindex                       41
8845 #define OP_OpenEphemeral                       42
8846 #define OP_SorterOpen                          43
8847 #define OP_OpenPseudo                          44
8848 #define OP_Close                               45
8849 #define OP_SeekLt                              46
8850 #define OP_SeekLe                              47
8851 #define OP_SeekGe                              48
8852 #define OP_SeekGt                              49
8853 #define OP_Seek                                50
8854 #define OP_NotFound                            51
8855 #define OP_Found                               52
8856 #define OP_IsUnique                            53
8857 #define OP_NotExists                           54
8858 #define OP_Sequence                            55
8859 #define OP_NewRowid                            56
8860 #define OP_Insert                              57
8861 #define OP_InsertInt                           58
8862 #define OP_Delete                              59
8863 #define OP_ResetCount                          60
8864 #define OP_SorterCompare                       61
8865 #define OP_SorterData                          62
8866 #define OP_RowKey                              63
8867 #define OP_RowData                             64
8868 #define OP_Rowid                               65
8869 #define OP_NullRow                             66
8870 #define OP_Last                                67
8871 #define OP_SorterSort                          70
8872 #define OP_Sort                                71
8873 #define OP_Rewind                              72
8874 #define OP_SorterNext                          81
8875 #define OP_Prev                                92
8876 #define OP_Next                                95
8877 #define OP_SorterInsert                        96
8878 #define OP_IdxInsert                           97
8879 #define OP_IdxDelete                           98
8880 #define OP_IdxRowid                            99
8881 #define OP_IdxLT                              100
8882 #define OP_IdxGE                              101
8883 #define OP_Destroy                            102
8884 #define OP_Clear                              103
8885 #define OP_CreateIndex                        104
8886 #define OP_CreateTable                        105
8887 #define OP_ParseSchema                        106
8888 #define OP_LoadAnalysis                       107
8889 #define OP_DropTable                          108
8890 #define OP_DropIndex                          109
8891 #define OP_DropTrigger                        110
8892 #define OP_IntegrityCk                        111
8893 #define OP_RowSetAdd                          112
8894 #define OP_RowSetRead                         113
8895 #define OP_RowSetTest                         114
8896 #define OP_Program                            115
8897 #define OP_Param                              116
8898 #define OP_FkCounter                          117
8899 #define OP_FkIfZero                           118
8900 #define OP_MemMax                             119
8901 #define OP_IfPos                              120
8902 #define OP_IfNeg                              121
8903 #define OP_IfZero                             122
8904 #define OP_AggStep                            123
8905 #define OP_AggFinal                           124
8906 #define OP_Checkpoint                         125
8907 #define OP_JournalMode                        126
8908 #define OP_Vacuum                             127
8909 #define OP_IncrVacuum                         128
8910 #define OP_Expire                             129
8911 #define OP_TableLock                          131
8912 #define OP_VBegin                             132
8913 #define OP_VCreate                            133
8914 #define OP_VDestroy                           134
8915 #define OP_VOpen                              135
8916 #define OP_VFilter                            136
8917 #define OP_VColumn                            137
8918 #define OP_VNext                              138
8919 #define OP_VRename                            139
8920 #define OP_VUpdate                            140
8921 #define OP_Pagecount                          146
8922 #define OP_MaxPgcnt                           147
8923 #define OP_Trace                              148
8924 #define OP_Noop                               149
8925 #define OP_Explain                            150
8926
8927
8928 /* Properties such as "out2" or "jump" that are specified in
8929 ** comments following the "case" for each opcode in the vdbe.c
8930 ** are encoded into bitvectors as follows:
8931 */
8932 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8933 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8934 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8935 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8936 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8937 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8938 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8939 #define OPFLG_INITIALIZER {\
8940 /*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
8941 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\
8942 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8943 /*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
8944 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8945 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8946 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8947 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8948 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8949 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8950 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8951 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8952 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8953 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8954 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8955 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8956 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8957 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8958 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8959
8960 /************** End of opcodes.h *********************************************/
8961 /************** Continuing where we left off in vdbe.h ***********************/
8962
8963 /*
8964 ** Prototypes for the VDBE interface.  See comments on the implementation
8965 ** for a description of what each of these routines does.
8966 */
8967 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8968 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8969 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8970 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8971 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8972 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8973 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8974 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8975 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8976 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8977 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8978 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8979 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8980 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8981 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
8982 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8983 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8984 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8985 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8986 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8987 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8988 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
8989 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8990 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8991 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8992 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8993 #ifdef SQLITE_DEBUG
8994 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8995 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8996 #endif
8997 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8998 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8999 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9000 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9001 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9002 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9003 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9004 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9005 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9006 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9007 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
9008 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9009 #ifndef SQLITE_OMIT_TRACE
9010 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9011 #endif
9012
9013 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9014 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9015 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9016
9017 #ifndef SQLITE_OMIT_TRIGGER
9018 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9019 #endif
9020
9021
9022 #ifndef NDEBUG
9023 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9024 # define VdbeComment(X)  sqlite3VdbeComment X
9025 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9026 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9027 #else
9028 # define VdbeComment(X)
9029 # define VdbeNoopComment(X)
9030 #endif
9031
9032 #endif
9033
9034 /************** End of vdbe.h ************************************************/
9035 /************** Continuing where we left off in sqliteInt.h ******************/
9036 /************** Include pager.h in the middle of sqliteInt.h *****************/
9037 /************** Begin file pager.h *******************************************/
9038 /*
9039 ** 2001 September 15
9040 **
9041 ** The author disclaims copyright to this source code.  In place of
9042 ** a legal notice, here is a blessing:
9043 **
9044 **    May you do good and not evil.
9045 **    May you find forgiveness for yourself and forgive others.
9046 **    May you share freely, never taking more than you give.
9047 **
9048 *************************************************************************
9049 ** This header file defines the interface that the sqlite page cache
9050 ** subsystem.  The page cache subsystem reads and writes a file a page
9051 ** at a time and provides a journal for rollback.
9052 */
9053
9054 #ifndef _PAGER_H_
9055 #define _PAGER_H_
9056
9057 /*
9058 ** Default maximum size for persistent journal files. A negative
9059 ** value means no limit. This value may be overridden using the
9060 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9061 */
9062 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9063   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9064 #endif
9065
9066 /*
9067 ** The type used to represent a page number.  The first page in a file
9068 ** is called page 1.  0 is used to represent "not a page".
9069 */
9070 typedef u32 Pgno;
9071
9072 /*
9073 ** Each open file is managed by a separate instance of the "Pager" structure.
9074 */
9075 typedef struct Pager Pager;
9076
9077 /*
9078 ** Handle type for pages.
9079 */
9080 typedef struct PgHdr DbPage;
9081
9082 /*
9083 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9084 ** reserved for working around a windows/posix incompatibility). It is
9085 ** used in the journal to signify that the remainder of the journal file
9086 ** is devoted to storing a master journal name - there are no more pages to
9087 ** roll back. See comments for function writeMasterJournal() in pager.c
9088 ** for details.
9089 */
9090 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9091
9092 /*
9093 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9094 **
9095 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9096 */
9097 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9098 #define PAGER_MEMORY        0x0002    /* In-memory database */
9099
9100 /*
9101 ** Valid values for the second argument to sqlite3PagerLockingMode().
9102 */
9103 #define PAGER_LOCKINGMODE_QUERY      -1
9104 #define PAGER_LOCKINGMODE_NORMAL      0
9105 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
9106
9107 /*
9108 ** Numeric constants that encode the journalmode.
9109 */
9110 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9111 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9112 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9113 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9114 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9115 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9116 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9117
9118 /*
9119 ** The remainder of this file contains the declarations of the functions
9120 ** that make up the Pager sub-system API. See source code comments for
9121 ** a detailed description of each routine.
9122 */
9123
9124 /* Open and close a Pager connection. */
9125 SQLITE_PRIVATE int sqlite3PagerOpen(
9126   sqlite3_vfs*,
9127   Pager **ppPager,
9128   const char*,
9129   int,
9130   int,
9131   int,
9132   void(*)(DbPage*)
9133 );
9134 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9135 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9136
9137 /* Functions used to configure a Pager object. */
9138 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9139 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9140 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9141 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9142 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9143 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
9144 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9145 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9146 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9147 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9148 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9149 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9150
9151 /* Functions used to obtain and release page references. */
9152 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9153 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9154 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9155 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9156 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9157
9158 /* Operations on page references. */
9159 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9160 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9161 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9162 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9163 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9164 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9165
9166 /* Functions used to manage pager transactions and savepoints. */
9167 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9168 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9169 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9170 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9171 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9172 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9173 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9174 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9175 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9176 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9177
9178 #ifndef SQLITE_OMIT_WAL
9179 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9180 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
9181 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
9182 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9183 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
9184 #endif
9185
9186 #ifdef SQLITE_ENABLE_ZIPVFS
9187 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9188 #endif
9189
9190 /* Functions used to query pager state and configuration. */
9191 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9192 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9193 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9194 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9195 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9196 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9197 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9198 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9199 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9200 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9201 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9202 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9203 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9204
9205 /* Functions used to truncate the database file. */
9206 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9207
9208 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9209 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9210 #endif
9211
9212 /* Functions to support testing and debugging. */
9213 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9214 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9215 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9216 #endif
9217 #ifdef SQLITE_TEST
9218 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9219 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9220   void disable_simulated_io_errors(void);
9221   void enable_simulated_io_errors(void);
9222 #else
9223 # define disable_simulated_io_errors()
9224 # define enable_simulated_io_errors()
9225 #endif
9226
9227 #endif /* _PAGER_H_ */
9228
9229 /************** End of pager.h ***********************************************/
9230 /************** Continuing where we left off in sqliteInt.h ******************/
9231 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9232 /************** Begin file pcache.h ******************************************/
9233 /*
9234 ** 2008 August 05
9235 **
9236 ** The author disclaims copyright to this source code.  In place of
9237 ** a legal notice, here is a blessing:
9238 **
9239 **    May you do good and not evil.
9240 **    May you find forgiveness for yourself and forgive others.
9241 **    May you share freely, never taking more than you give.
9242 **
9243 *************************************************************************
9244 ** This header file defines the interface that the sqlite page cache
9245 ** subsystem.
9246 */
9247
9248 #ifndef _PCACHE_H_
9249
9250 typedef struct PgHdr PgHdr;
9251 typedef struct PCache PCache;
9252
9253 /*
9254 ** Every page in the cache is controlled by an instance of the following
9255 ** structure.
9256 */
9257 struct PgHdr {
9258   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9259   void *pData;                   /* Page data */
9260   void *pExtra;                  /* Extra content */
9261   PgHdr *pDirty;                 /* Transient list of dirty pages */
9262   Pager *pPager;                 /* The pager this page is part of */
9263   Pgno pgno;                     /* Page number for this page */
9264 #ifdef SQLITE_CHECK_PAGES
9265   u32 pageHash;                  /* Hash of page content */
9266 #endif
9267   u16 flags;                     /* PGHDR flags defined below */
9268
9269   /**********************************************************************
9270   ** Elements above are public.  All that follows is private to pcache.c
9271   ** and should not be accessed by other modules.
9272   */
9273   i16 nRef;                      /* Number of users of this page */
9274   PCache *pCache;                /* Cache that owns this page */
9275
9276   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9277   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9278 };
9279
9280 /* Bit values for PgHdr.flags */
9281 #define PGHDR_DIRTY             0x002  /* Page has changed */
9282 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9283                                        ** writing this page to the database */
9284 #define PGHDR_NEED_READ         0x008  /* Content is unread */
9285 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9286 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9287
9288 /* Initialize and shutdown the page cache subsystem */
9289 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9290 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9291
9292 /* Page cache buffer management:
9293 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9294 */
9295 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9296
9297 /* Create a new pager cache.
9298 ** Under memory stress, invoke xStress to try to make pages clean.
9299 ** Only clean and unpinned pages can be reclaimed.
9300 */
9301 SQLITE_PRIVATE void sqlite3PcacheOpen(
9302   int szPage,                    /* Size of every page */
9303   int szExtra,                   /* Extra space associated with each page */
9304   int bPurgeable,                /* True if pages are on backing store */
9305   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9306   void *pStress,                 /* Argument to xStress */
9307   PCache *pToInit                /* Preallocated space for the PCache */
9308 );
9309
9310 /* Modify the page-size after the cache has been created. */
9311 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9312
9313 /* Return the size in bytes of a PCache object.  Used to preallocate
9314 ** storage space.
9315 */
9316 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9317
9318 /* One release per successful fetch.  Page is pinned until released.
9319 ** Reference counted.
9320 */
9321 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9322 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9323
9324 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9325 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9326 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9327 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9328
9329 /* Change a page number.  Used by incr-vacuum. */
9330 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9331
9332 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
9333 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9334
9335 /* Get a list of all dirty pages in the cache, sorted by page number */
9336 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9337
9338 /* Reset and close the cache object */
9339 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9340
9341 /* Clear flags from pages of the page cache */
9342 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9343
9344 /* Discard the contents of the cache */
9345 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9346
9347 /* Return the total number of outstanding page references */
9348 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9349
9350 /* Increment the reference count of an existing page */
9351 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9352
9353 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9354
9355 /* Return the total number of pages stored in the cache */
9356 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9357
9358 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9359 /* Iterate through all dirty pages currently stored in the cache. This
9360 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
9361 ** library is built.
9362 */
9363 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9364 #endif
9365
9366 /* Set and get the suggested cache-size for the specified pager-cache.
9367 **
9368 ** If no global maximum is configured, then the system attempts to limit
9369 ** the total number of pages cached by purgeable pager-caches to the sum
9370 ** of the suggested cache-sizes.
9371 */
9372 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9373 #ifdef SQLITE_TEST
9374 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9375 #endif
9376
9377 /* Free up as much memory as possible from the page cache */
9378 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9379
9380 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9381 /* Try to return memory used by the pcache module to the main memory heap */
9382 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9383 #endif
9384
9385 #ifdef SQLITE_TEST
9386 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9387 #endif
9388
9389 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9390
9391 #endif /* _PCACHE_H_ */
9392
9393 /************** End of pcache.h **********************************************/
9394 /************** Continuing where we left off in sqliteInt.h ******************/
9395
9396 /************** Include os.h in the middle of sqliteInt.h ********************/
9397 /************** Begin file os.h **********************************************/
9398 /*
9399 ** 2001 September 16
9400 **
9401 ** The author disclaims copyright to this source code.  In place of
9402 ** a legal notice, here is a blessing:
9403 **
9404 **    May you do good and not evil.
9405 **    May you find forgiveness for yourself and forgive others.
9406 **    May you share freely, never taking more than you give.
9407 **
9408 ******************************************************************************
9409 **
9410 ** This header file (together with is companion C source-code file
9411 ** "os.c") attempt to abstract the underlying operating system so that
9412 ** the SQLite library will work on both POSIX and windows systems.
9413 **
9414 ** This header file is #include-ed by sqliteInt.h and thus ends up
9415 ** being included by every source file.
9416 */
9417 #ifndef _SQLITE_OS_H_
9418 #define _SQLITE_OS_H_
9419
9420 /*
9421 ** Figure out if we are dealing with Unix, Windows, or some other
9422 ** operating system.  After the following block of preprocess macros,
9423 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
9424 ** will defined to either 1 or 0.  One of the four will be 1.  The other
9425 ** three will be 0.
9426 */
9427 #if defined(SQLITE_OS_OTHER)
9428 # if SQLITE_OS_OTHER==1
9429 #   undef SQLITE_OS_UNIX
9430 #   define SQLITE_OS_UNIX 0
9431 #   undef SQLITE_OS_WIN
9432 #   define SQLITE_OS_WIN 0
9433 # else
9434 #   undef SQLITE_OS_OTHER
9435 # endif
9436 #endif
9437 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9438 # define SQLITE_OS_OTHER 0
9439 # ifndef SQLITE_OS_WIN
9440 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9441 #     define SQLITE_OS_WIN 1
9442 #     define SQLITE_OS_UNIX 0
9443 #   else
9444 #     define SQLITE_OS_WIN 0
9445 #     define SQLITE_OS_UNIX 1
9446 #  endif
9447 # else
9448 #  define SQLITE_OS_UNIX 0
9449 # endif
9450 #else
9451 # ifndef SQLITE_OS_WIN
9452 #  define SQLITE_OS_WIN 0
9453 # endif
9454 #endif
9455
9456 #if SQLITE_OS_WIN
9457 # include <windows.h>
9458 #endif
9459
9460 /*
9461 ** Determine if we are dealing with Windows NT.
9462 **
9463 ** We ought to be able to determine if we are compiling for win98 or winNT
9464 ** using the _WIN32_WINNT macro as follows:
9465 **
9466 ** #if defined(_WIN32_WINNT)
9467 ** # define SQLITE_OS_WINNT 1
9468 ** #else
9469 ** # define SQLITE_OS_WINNT 0
9470 ** #endif
9471 **
9472 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9473 ** so the above test does not work.  We'll just assume that everything is
9474 ** winNT unless the programmer explicitly says otherwise by setting
9475 ** SQLITE_OS_WINNT to 0.
9476 */
9477 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9478 # define SQLITE_OS_WINNT 1
9479 #endif
9480
9481 /*
9482 ** Determine if we are dealing with WindowsCE - which has a much
9483 ** reduced API.
9484 */
9485 #if defined(_WIN32_WCE)
9486 # define SQLITE_OS_WINCE 1
9487 #else
9488 # define SQLITE_OS_WINCE 0
9489 #endif
9490
9491 /*
9492 ** Determine if we are dealing with WinRT, which provides only a subset of
9493 ** the full Win32 API.
9494 */
9495 #if !defined(SQLITE_OS_WINRT)
9496 # define SQLITE_OS_WINRT 0
9497 #endif
9498
9499 /*
9500 ** When compiled for WinCE or WinRT, there is no concept of the current
9501 ** directory.
9502  */
9503 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
9504 # define SQLITE_CURDIR 1
9505 #endif
9506
9507 /* If the SET_FULLSYNC macro is not defined above, then make it
9508 ** a no-op
9509 */
9510 #ifndef SET_FULLSYNC
9511 # define SET_FULLSYNC(x,y)
9512 #endif
9513
9514 /*
9515 ** The default size of a disk sector
9516 */
9517 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9518 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9519 #endif
9520
9521 /*
9522 ** Temporary files are named starting with this prefix followed by 16 random
9523 ** alphanumeric characters, and no file extension. They are stored in the
9524 ** OS's standard temporary file directory, and are deleted prior to exit.
9525 ** If sqlite is being embedded in another program, you may wish to change the
9526 ** prefix to reflect your program's name, so that if your program exits
9527 ** prematurely, old temporary files can be easily identified. This can be done
9528 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9529 **
9530 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9531 ** Mcafee started using SQLite in their anti-virus product and it
9532 ** started putting files with the "sqlite" name in the c:/temp folder.
9533 ** This annoyed many windows users.  Those users would then do a
9534 ** Google search for "sqlite", find the telephone numbers of the
9535 ** developers and call to wake them up at night and complain.
9536 ** For this reason, the default name prefix is changed to be "sqlite"
9537 ** spelled backwards.  So the temp files are still identified, but
9538 ** anybody smart enough to figure out the code is also likely smart
9539 ** enough to know that calling the developer will not help get rid
9540 ** of the file.
9541 */
9542 #ifndef SQLITE_TEMP_FILE_PREFIX
9543 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9544 #endif
9545
9546 /*
9547 ** The following values may be passed as the second argument to
9548 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9549 **
9550 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9551 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9552 **            any time. Other processes may hold and obtain new SHARED locks.
9553 ** PENDING:   A single process may hold a PENDING lock on a file at
9554 **            any one time. Existing SHARED locks may persist, but no new
9555 **            SHARED locks may be obtained by other processes.
9556 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9557 **
9558 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9559 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9560 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9561 ** sqlite3OsLock().
9562 */
9563 #define NO_LOCK         0
9564 #define SHARED_LOCK     1
9565 #define RESERVED_LOCK   2
9566 #define PENDING_LOCK    3
9567 #define EXCLUSIVE_LOCK  4
9568
9569 /*
9570 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9571 **
9572 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9573 ** those functions are not available.  So we use only LockFile() and
9574 ** UnlockFile().
9575 **
9576 ** LockFile() prevents not just writing but also reading by other processes.
9577 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
9578 ** byte out of a specific range of bytes. The lock byte is obtained at
9579 ** random so two separate readers can probably access the file at the
9580 ** same time, unless they are unlucky and choose the same lock byte.
9581 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9582 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9583 ** a single byte of the file that is designated as the reserved lock byte.
9584 ** A PENDING_LOCK is obtained by locking a designated byte different from
9585 ** the RESERVED_LOCK byte.
9586 **
9587 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9588 ** which means we can use reader/writer locks.  When reader/writer locks
9589 ** are used, the lock is placed on the same range of bytes that is used
9590 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9591 ** will support two or more Win95 readers or two or more WinNT readers.
9592 ** But a single Win95 reader will lock out all WinNT readers and a single
9593 ** WinNT reader will lock out all other Win95 readers.
9594 **
9595 ** The following #defines specify the range of bytes used for locking.
9596 ** SHARED_SIZE is the number of bytes available in the pool from which
9597 ** a random byte is selected for a shared lock.  The pool of bytes for
9598 ** shared locks begins at SHARED_FIRST.
9599 **
9600 ** The same locking strategy and
9601 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9602 ** clients on win95, winNT, and unix all talking to the same shared file
9603 ** and all locking correctly.  To do so would require that samba (or whatever
9604 ** tool is being used for file sharing) implements locks correctly between
9605 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9606 ** using the same locking range we are at least open to the possibility.
9607 **
9608 ** Locking in windows is manditory.  For this reason, we cannot store
9609 ** actual data in the bytes used for locking.  The pager never allocates
9610 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9611 ** that all locks will fit on a single page even at the minimum page size.
9612 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9613 ** is set high so that we don't have to allocate an unused page except
9614 ** for very large databases.  But one should test the page skipping logic
9615 ** by setting PENDING_BYTE low and running the entire regression suite.
9616 **
9617 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9618 ** file format.  Depending on how it is changed, you might not notice
9619 ** the incompatibility right away, even running a full regression test.
9620 ** The default location of PENDING_BYTE is the first byte past the
9621 ** 1GB boundary.
9622 **
9623 */
9624 #ifdef SQLITE_OMIT_WSD
9625 # define PENDING_BYTE     (0x40000000)
9626 #else
9627 # define PENDING_BYTE      sqlite3PendingByte
9628 #endif
9629 #define RESERVED_BYTE     (PENDING_BYTE+1)
9630 #define SHARED_FIRST      (PENDING_BYTE+2)
9631 #define SHARED_SIZE       510
9632
9633 /*
9634 ** Wrapper around OS specific sqlite3_os_init() function.
9635 */
9636 SQLITE_PRIVATE int sqlite3OsInit(void);
9637
9638 /*
9639 ** Functions for accessing sqlite3_file methods
9640 */
9641 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9642 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9643 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9644 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9645 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9646 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9647 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9648 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9649 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9650 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9651 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9652 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9653 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9654 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9655 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9656 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9657 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9658 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9659
9660
9661 /*
9662 ** Functions for accessing sqlite3_vfs methods
9663 */
9664 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9665 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9666 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9667 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9668 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9669 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9670 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9671 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9672 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9673 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9674 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9675 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9676 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9677
9678 /*
9679 ** Convenience functions for opening and closing files using
9680 ** sqlite3_malloc() to obtain space for the file-handle structure.
9681 */
9682 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9683 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9684
9685 #endif /* _SQLITE_OS_H_ */
9686
9687 /************** End of os.h **************************************************/
9688 /************** Continuing where we left off in sqliteInt.h ******************/
9689 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9690 /************** Begin file mutex.h *******************************************/
9691 /*
9692 ** 2007 August 28
9693 **
9694 ** The author disclaims copyright to this source code.  In place of
9695 ** a legal notice, here is a blessing:
9696 **
9697 **    May you do good and not evil.
9698 **    May you find forgiveness for yourself and forgive others.
9699 **    May you share freely, never taking more than you give.
9700 **
9701 *************************************************************************
9702 **
9703 ** This file contains the common header for all mutex implementations.
9704 ** The sqliteInt.h header #includes this file so that it is available
9705 ** to all source files.  We break it out in an effort to keep the code
9706 ** better organized.
9707 **
9708 ** NOTE:  source files should *not* #include this header file directly.
9709 ** Source files should #include the sqliteInt.h file and let that file
9710 ** include this one indirectly.
9711 */
9712
9713
9714 /*
9715 ** Figure out what version of the code to use.  The choices are
9716 **
9717 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9718 **                             mutexes implemention cannot be overridden
9719 **                             at start-time.
9720 **
9721 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9722 **                             mutual exclusion is provided.  But this
9723 **                             implementation can be overridden at
9724 **                             start-time.
9725 **
9726 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9727 **
9728 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9729 */
9730 #if !SQLITE_THREADSAFE
9731 # define SQLITE_MUTEX_OMIT
9732 #endif
9733 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9734 #  if SQLITE_OS_UNIX
9735 #    define SQLITE_MUTEX_PTHREADS
9736 #  elif SQLITE_OS_WIN
9737 #    define SQLITE_MUTEX_W32
9738 #  else
9739 #    define SQLITE_MUTEX_NOOP
9740 #  endif
9741 #endif
9742
9743 #ifdef SQLITE_MUTEX_OMIT
9744 /*
9745 ** If this is a no-op implementation, implement everything as macros.
9746 */
9747 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9748 #define sqlite3_mutex_free(X)
9749 #define sqlite3_mutex_enter(X)
9750 #define sqlite3_mutex_try(X)      SQLITE_OK
9751 #define sqlite3_mutex_leave(X)
9752 #define sqlite3_mutex_held(X)     ((void)(X),1)
9753 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9754 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9755 #define sqlite3MutexInit()        SQLITE_OK
9756 #define sqlite3MutexEnd()
9757 #define MUTEX_LOGIC(X)
9758 #else
9759 #define MUTEX_LOGIC(X)            X
9760 #endif /* defined(SQLITE_MUTEX_OMIT) */
9761
9762 /************** End of mutex.h ***********************************************/
9763 /************** Continuing where we left off in sqliteInt.h ******************/
9764
9765
9766 /*
9767 ** Each database file to be accessed by the system is an instance
9768 ** of the following structure.  There are normally two of these structures
9769 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9770 ** aDb[1] is the database file used to hold temporary tables.  Additional
9771 ** databases may be attached.
9772 */
9773 struct Db {
9774   char *zName;         /* Name of this database */
9775   Btree *pBt;          /* The B*Tree structure for this database file */
9776   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9777   u8 safety_level;     /* How aggressive at syncing data to disk */
9778   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9779 };
9780
9781 /*
9782 ** An instance of the following structure stores a database schema.
9783 **
9784 ** Most Schema objects are associated with a Btree.  The exception is
9785 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9786 ** In shared cache mode, a single Schema object can be shared by multiple
9787 ** Btrees that refer to the same underlying BtShared object.
9788 **
9789 ** Schema objects are automatically deallocated when the last Btree that
9790 ** references them is destroyed.   The TEMP Schema is manually freed by
9791 ** sqlite3_close().
9792 *
9793 ** A thread must be holding a mutex on the corresponding Btree in order
9794 ** to access Schema content.  This implies that the thread must also be
9795 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9796 ** For a TEMP Schema, only the connection mutex is required.
9797 */
9798 struct Schema {
9799   int schema_cookie;   /* Database schema version number for this file */
9800   int iGeneration;     /* Generation counter.  Incremented with each change */
9801   Hash tblHash;        /* All tables indexed by name */
9802   Hash idxHash;        /* All (named) indices indexed by name */
9803   Hash trigHash;       /* All triggers indexed by name */
9804   Hash fkeyHash;       /* All foreign keys by referenced table name */
9805   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9806   u8 file_format;      /* Schema format version for this file */
9807   u8 enc;              /* Text encoding used by this database */
9808   u16 flags;           /* Flags associated with this schema */
9809   int cache_size;      /* Number of pages to use in the cache */
9810 };
9811
9812 /*
9813 ** These macros can be used to test, set, or clear bits in the
9814 ** Db.pSchema->flags field.
9815 */
9816 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9817 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9818 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9819 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9820
9821 /*
9822 ** Allowed values for the DB.pSchema->flags field.
9823 **
9824 ** The DB_SchemaLoaded flag is set after the database schema has been
9825 ** read into internal hash tables.
9826 **
9827 ** DB_UnresetViews means that one or more views have column names that
9828 ** have been filled out.  If the schema changes, these column names might
9829 ** changes and so the view will need to be reset.
9830 */
9831 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9832 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9833 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9834
9835 /*
9836 ** The number of different kinds of things that can be limited
9837 ** using the sqlite3_limit() interface.
9838 */
9839 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9840
9841 /*
9842 ** Lookaside malloc is a set of fixed-size buffers that can be used
9843 ** to satisfy small transient memory allocation requests for objects
9844 ** associated with a particular database connection.  The use of
9845 ** lookaside malloc provides a significant performance enhancement
9846 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9847 ** SQL statements.
9848 **
9849 ** The Lookaside structure holds configuration information about the
9850 ** lookaside malloc subsystem.  Each available memory allocation in
9851 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9852 ** objects.
9853 **
9854 ** Lookaside allocations are only allowed for objects that are associated
9855 ** with a particular database connection.  Hence, schema information cannot
9856 ** be stored in lookaside because in shared cache mode the schema information
9857 ** is shared by multiple database connections.  Therefore, while parsing
9858 ** schema information, the Lookaside.bEnabled flag is cleared so that
9859 ** lookaside allocations are not used to construct the schema objects.
9860 */
9861 struct Lookaside {
9862   u16 sz;                 /* Size of each buffer in bytes */
9863   u8 bEnabled;            /* False to disable new lookaside allocations */
9864   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9865   int nOut;               /* Number of buffers currently checked out */
9866   int mxOut;              /* Highwater mark for nOut */
9867   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9868   LookasideSlot *pFree;   /* List of available buffers */
9869   void *pStart;           /* First byte of available memory space */
9870   void *pEnd;             /* First byte past end of available space */
9871 };
9872 struct LookasideSlot {
9873   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9874 };
9875
9876 /*
9877 ** A hash table for function definitions.
9878 **
9879 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9880 ** Collisions are on the FuncDef.pHash chain.
9881 */
9882 struct FuncDefHash {
9883   FuncDef *a[23];       /* Hash table for functions */
9884 };
9885
9886 /*
9887 ** Each database connection is an instance of the following structure.
9888 */
9889 struct sqlite3 {
9890   sqlite3_vfs *pVfs;            /* OS Interface */
9891   struct Vdbe *pVdbe;           /* List of active virtual machines */
9892   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9893   sqlite3_mutex *mutex;         /* Connection mutex */
9894   Db *aDb;                      /* All backends */
9895   int nDb;                      /* Number of backends currently in use */
9896   int flags;                    /* Miscellaneous flags. See below */
9897   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9898   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9899   int errCode;                  /* Most recent error code (SQLITE_*) */
9900   int errMask;                  /* & result codes with this before returning */
9901   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
9902   u8 autoCommit;                /* The auto-commit flag. */
9903   u8 temp_store;                /* 1: file 2: memory 0: default */
9904   u8 mallocFailed;              /* True if we have seen a malloc failure */
9905   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9906   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9907   u8 suppressErr;               /* Do not issue error messages if true */
9908   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9909   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9910   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9911   u32 magic;                    /* Magic number for detect library misuse */
9912   int nChange;                  /* Value returned by sqlite3_changes() */
9913   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9914   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9915   struct sqlite3InitInfo {      /* Information used during initialization */
9916     int newTnum;                /* Rootpage of table being initialized */
9917     u8 iDb;                     /* Which db file is being initialized */
9918     u8 busy;                    /* TRUE if currently initializing */
9919     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9920   } init;
9921   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9922   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9923   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9924   int nExtension;               /* Number of loaded extensions */
9925   void **aExtension;            /* Array of shared library handles */
9926   void (*xTrace)(void*,const char*);        /* Trace function */
9927   void *pTraceArg;                          /* Argument to the trace function */
9928   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9929   void *pProfileArg;                        /* Argument to profile function */
9930   void *pCommitArg;                 /* Argument to xCommitCallback() */
9931   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9932   void *pRollbackArg;               /* Argument to xRollbackCallback() */
9933   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9934   void *pUpdateArg;
9935   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9936 #ifndef SQLITE_OMIT_WAL
9937   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9938   void *pWalArg;
9939 #endif
9940   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9941   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9942   void *pCollNeededArg;
9943   sqlite3_value *pErr;          /* Most recent error message */
9944   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9945   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9946   union {
9947     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9948     double notUsed1;            /* Spacer */
9949   } u1;
9950   Lookaside lookaside;          /* Lookaside malloc configuration */
9951 #ifndef SQLITE_OMIT_AUTHORIZATION
9952   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9953                                 /* Access authorization function */
9954   void *pAuthArg;               /* 1st argument to the access auth function */
9955 #endif
9956 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9957   int (*xProgress)(void *);     /* The progress callback */
9958   void *pProgressArg;           /* Argument to the progress callback */
9959   int nProgressOps;             /* Number of opcodes for progress callback */
9960 #endif
9961 #ifndef SQLITE_OMIT_VIRTUALTABLE
9962   int nVTrans;                  /* Allocated size of aVTrans */
9963   Hash aModule;                 /* populated by sqlite3_create_module() */
9964   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9965   VTable **aVTrans;             /* Virtual tables with open transactions */
9966   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9967 #endif
9968   FuncDefHash aFunc;            /* Hash table of connection functions */
9969   Hash aCollSeq;                /* All collating sequences */
9970   BusyHandler busyHandler;      /* Busy callback */
9971   Db aDbStatic[2];              /* Static space for the 2 default backends */
9972   Savepoint *pSavepoint;        /* List of active savepoints */
9973   int busyTimeout;              /* Busy handler timeout, in msec */
9974   int nSavepoint;               /* Number of non-transaction savepoints */
9975   int nStatement;               /* Number of nested statement-transactions  */
9976   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9977   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9978
9979 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9980   /* The following variables are all protected by the STATIC_MASTER
9981   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9982   **
9983   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9984   ** unlock so that it can proceed.
9985   **
9986   ** When X.pBlockingConnection==Y, that means that something that X tried
9987   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9988   ** held by Y.
9989   */
9990   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9991   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9992   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9993   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9994   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9995 #endif
9996 };
9997
9998 /*
9999 ** A macro to discover the encoding of a database.
10000 */
10001 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10002
10003 /*
10004 ** Possible values for the sqlite3.flags.
10005 */
10006 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10007 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10008 #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
10009 #define SQLITE_ShortColNames  0x00000008  /* Show short columns names */
10010 #define SQLITE_CountRows      0x00000010  /* Count rows changed by INSERT, */
10011                                           /*   DELETE, or UPDATE and return */
10012                                           /*   the count using a callback. */
10013 #define SQLITE_NullCallback   0x00000020  /* Invoke the callback once if the */
10014                                           /*   result set is empty */
10015 #define SQLITE_SqlTrace       0x00000040  /* Debug print SQL as it executes */
10016 #define SQLITE_VdbeListing    0x00000080  /* Debug listings of VDBE programs */
10017 #define SQLITE_WriteSchema    0x00000100  /* OK to update SQLITE_MASTER */
10018                          /*   0x00000200  Unused */
10019 #define SQLITE_IgnoreChecks   0x00000400  /* Do not enforce check constraints */
10020 #define SQLITE_ReadUncommitted 0x0000800  /* For shared-cache mode */
10021 #define SQLITE_LegacyFileFmt  0x00001000  /* Create new databases in format 1 */
10022 #define SQLITE_FullFSync      0x00002000  /* Use full fsync on the backend */
10023 #define SQLITE_CkptFullFSync  0x00004000  /* Use full fsync for checkpoint */
10024 #define SQLITE_RecoveryMode   0x00008000  /* Ignore schema errors */
10025 #define SQLITE_ReverseOrder   0x00010000  /* Reverse unordered SELECTs */
10026 #define SQLITE_RecTriggers    0x00020000  /* Enable recursive triggers */
10027 #define SQLITE_ForeignKeys    0x00040000  /* Enforce foreign key constraints  */
10028 #define SQLITE_AutoIndex      0x00080000  /* Enable automatic indexes */
10029 #define SQLITE_PreferBuiltin  0x00100000  /* Preference to built-in funcs */
10030 #define SQLITE_LoadExtension  0x00200000  /* Enable load_extension */
10031 #define SQLITE_EnableTrigger  0x00400000  /* True to enable triggers */
10032
10033 /*
10034 ** Bits of the sqlite3.dbOptFlags field that are used by the
10035 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10036 ** selectively disable various optimizations.
10037 */
10038 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10039 #define SQLITE_ColumnCache    0x0002   /* Column cache */
10040 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10041 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10042 #define SQLITE_IdxRealAsInt   0x0010   /* Store REAL as INT in indices */
10043 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10044 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10045 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10046 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10047 #define SQLITE_AllOpts        0xffff   /* All optimizations */
10048
10049 /*
10050 ** Macros for testing whether or not optimizations are enabled or disabled.
10051 */
10052 #ifndef SQLITE_OMIT_BUILTIN_TEST
10053 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10054 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10055 #else
10056 #define OptimizationDisabled(db, mask)  0
10057 #define OptimizationEnabled(db, mask)   1
10058 #endif
10059
10060 /*
10061 ** Possible values for the sqlite.magic field.
10062 ** The numbers are obtained at random and have no special meaning, other
10063 ** than being distinct from one another.
10064 */
10065 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10066 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10067 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10068 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10069 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10070 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10071
10072 /*
10073 ** Each SQL function is defined by an instance of the following
10074 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
10075 ** hash table.  When multiple functions have the same name, the hash table
10076 ** points to a linked list of these structures.
10077 */
10078 struct FuncDef {
10079   i16 nArg;            /* Number of arguments.  -1 means unlimited */
10080   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
10081   u8 flags;            /* Some combination of SQLITE_FUNC_* */
10082   void *pUserData;     /* User data parameter */
10083   FuncDef *pNext;      /* Next function with same name */
10084   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10085   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10086   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10087   char *zName;         /* SQL name of the function. */
10088   FuncDef *pHash;      /* Next with a different name but the same hash */
10089   FuncDestructor *pDestructor;   /* Reference counted destructor function */
10090 };
10091
10092 /*
10093 ** This structure encapsulates a user-function destructor callback (as
10094 ** configured using create_function_v2()) and a reference counter. When
10095 ** create_function_v2() is called to create a function with a destructor,
10096 ** a single object of this type is allocated. FuncDestructor.nRef is set to
10097 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10098 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10099 ** member of each of the new FuncDef objects is set to point to the allocated
10100 ** FuncDestructor.
10101 **
10102 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10103 ** count on this object is decremented. When it reaches 0, the destructor
10104 ** is invoked and the FuncDestructor structure freed.
10105 */
10106 struct FuncDestructor {
10107   int nRef;
10108   void (*xDestroy)(void *);
10109   void *pUserData;
10110 };
10111
10112 /*
10113 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10114 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10115 ** are assert() statements in the code to verify this.
10116 */
10117 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
10118 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
10119 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
10120 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10121 #define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */
10122 #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10123 #define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */
10124 #define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */
10125
10126 /*
10127 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10128 ** used to create the initializers for the FuncDef structures.
10129 **
10130 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10131 **     Used to create a scalar function definition of a function zName
10132 **     implemented by C function xFunc that accepts nArg arguments. The
10133 **     value passed as iArg is cast to a (void*) and made available
10134 **     as the user-data (sqlite3_user_data()) for the function. If
10135 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10136 **
10137 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10138 **     Used to create an aggregate function definition implemented by
10139 **     the C functions xStep and xFinal. The first four parameters
10140 **     are interpreted in the same way as the first 4 parameters to
10141 **     FUNCTION().
10142 **
10143 **   LIKEFUNC(zName, nArg, pArg, flags)
10144 **     Used to create a scalar function definition of a function zName
10145 **     that accepts nArg arguments and is implemented by a call to C
10146 **     function likeFunc. Argument pArg is cast to a (void *) and made
10147 **     available as the function user-data (sqlite3_user_data()). The
10148 **     FuncDef.flags variable is set to the value passed as the flags
10149 **     parameter.
10150 */
10151 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10152   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10153    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10154 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10155   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10156    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10157 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10158   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10159    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10160 #define LIKEFUNC(zName, nArg, arg, flags) \
10161   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10162 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10163   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10164    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10165
10166 /*
10167 ** All current savepoints are stored in a linked list starting at
10168 ** sqlite3.pSavepoint. The first element in the list is the most recently
10169 ** opened savepoint. Savepoints are added to the list by the vdbe
10170 ** OP_Savepoint instruction.
10171 */
10172 struct Savepoint {
10173   char *zName;                        /* Savepoint name (nul-terminated) */
10174   i64 nDeferredCons;                  /* Number of deferred fk violations */
10175   Savepoint *pNext;                   /* Parent savepoint (if any) */
10176 };
10177
10178 /*
10179 ** The following are used as the second parameter to sqlite3Savepoint(),
10180 ** and as the P1 argument to the OP_Savepoint instruction.
10181 */
10182 #define SAVEPOINT_BEGIN      0
10183 #define SAVEPOINT_RELEASE    1
10184 #define SAVEPOINT_ROLLBACK   2
10185
10186
10187 /*
10188 ** Each SQLite module (virtual table definition) is defined by an
10189 ** instance of the following structure, stored in the sqlite3.aModule
10190 ** hash table.
10191 */
10192 struct Module {
10193   const sqlite3_module *pModule;       /* Callback pointers */
10194   const char *zName;                   /* Name passed to create_module() */
10195   void *pAux;                          /* pAux passed to create_module() */
10196   void (*xDestroy)(void *);            /* Module destructor function */
10197 };
10198
10199 /*
10200 ** information about each column of an SQL table is held in an instance
10201 ** of this structure.
10202 */
10203 struct Column {
10204   char *zName;     /* Name of this column */
10205   Expr *pDflt;     /* Default value of this column */
10206   char *zDflt;     /* Original text of the default value */
10207   char *zType;     /* Data type for this column */
10208   char *zColl;     /* Collating sequence.  If NULL, use the default */
10209   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10210   char affinity;   /* One of the SQLITE_AFF_... values */
10211   u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
10212 };
10213
10214 /* Allowed values for Column.colFlags:
10215 */
10216 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10217 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10218
10219 /*
10220 ** A "Collating Sequence" is defined by an instance of the following
10221 ** structure. Conceptually, a collating sequence consists of a name and
10222 ** a comparison routine that defines the order of that sequence.
10223 **
10224 ** If CollSeq.xCmp is NULL, it means that the
10225 ** collating sequence is undefined.  Indices built on an undefined
10226 ** collating sequence may not be read or written.
10227 */
10228 struct CollSeq {
10229   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10230   u8 enc;               /* Text encoding handled by xCmp() */
10231   void *pUser;          /* First argument to xCmp() */
10232   int (*xCmp)(void*,int, const void*, int, const void*);
10233   void (*xDel)(void*);  /* Destructor for pUser */
10234 };
10235
10236 /*
10237 ** A sort order can be either ASC or DESC.
10238 */
10239 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10240 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10241
10242 /*
10243 ** Column affinity types.
10244 **
10245 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10246 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10247 ** the speed a little by numbering the values consecutively.
10248 **
10249 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
10250 ** when multiple affinity types are concatenated into a string and
10251 ** used as the P4 operand, they will be more readable.
10252 **
10253 ** Note also that the numeric types are grouped together so that testing
10254 ** for a numeric type is a single comparison.
10255 */
10256 #define SQLITE_AFF_TEXT     'a'
10257 #define SQLITE_AFF_NONE     'b'
10258 #define SQLITE_AFF_NUMERIC  'c'
10259 #define SQLITE_AFF_INTEGER  'd'
10260 #define SQLITE_AFF_REAL     'e'
10261
10262 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10263
10264 /*
10265 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10266 ** affinity value.
10267 */
10268 #define SQLITE_AFF_MASK     0x67
10269
10270 /*
10271 ** Additional bit values that can be ORed with an affinity without
10272 ** changing the affinity.
10273 */
10274 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10275 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10276 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10277
10278 /*
10279 ** An object of this type is created for each virtual table present in
10280 ** the database schema.
10281 **
10282 ** If the database schema is shared, then there is one instance of this
10283 ** structure for each database connection (sqlite3*) that uses the shared
10284 ** schema. This is because each database connection requires its own unique
10285 ** instance of the sqlite3_vtab* handle used to access the virtual table
10286 ** implementation. sqlite3_vtab* handles can not be shared between
10287 ** database connections, even when the rest of the in-memory database
10288 ** schema is shared, as the implementation often stores the database
10289 ** connection handle passed to it via the xConnect() or xCreate() method
10290 ** during initialization internally. This database connection handle may
10291 ** then be used by the virtual table implementation to access real tables
10292 ** within the database. So that they appear as part of the callers
10293 ** transaction, these accesses need to be made via the same database
10294 ** connection as that used to execute SQL operations on the virtual table.
10295 **
10296 ** All VTable objects that correspond to a single table in a shared
10297 ** database schema are initially stored in a linked-list pointed to by
10298 ** the Table.pVTable member variable of the corresponding Table object.
10299 ** When an sqlite3_prepare() operation is required to access the virtual
10300 ** table, it searches the list for the VTable that corresponds to the
10301 ** database connection doing the preparing so as to use the correct
10302 ** sqlite3_vtab* handle in the compiled query.
10303 **
10304 ** When an in-memory Table object is deleted (for example when the
10305 ** schema is being reloaded for some reason), the VTable objects are not
10306 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10307 ** immediately. Instead, they are moved from the Table.pVTable list to
10308 ** another linked list headed by the sqlite3.pDisconnect member of the
10309 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
10310 ** next time a statement is prepared using said sqlite3*. This is done
10311 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10312 ** Refer to comments above function sqlite3VtabUnlockList() for an
10313 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10314 ** list without holding the corresponding sqlite3.mutex mutex.
10315 **
10316 ** The memory for objects of this type is always allocated by
10317 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10318 ** the first argument.
10319 */
10320 struct VTable {
10321   sqlite3 *db;              /* Database connection associated with this table */
10322   Module *pMod;             /* Pointer to module implementation */
10323   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10324   int nRef;                 /* Number of pointers to this structure */
10325   u8 bConstraint;           /* True if constraints are supported */
10326   int iSavepoint;           /* Depth of the SAVEPOINT stack */
10327   VTable *pNext;            /* Next in linked list (see above) */
10328 };
10329
10330 /*
10331 ** Each SQL table is represented in memory by an instance of the
10332 ** following structure.
10333 **
10334 ** Table.zName is the name of the table.  The case of the original
10335 ** CREATE TABLE statement is stored, but case is not significant for
10336 ** comparisons.
10337 **
10338 ** Table.nCol is the number of columns in this table.  Table.aCol is a
10339 ** pointer to an array of Column structures, one for each column.
10340 **
10341 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10342 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10343 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10344 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10345 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10346 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
10347 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10348 **
10349 ** Table.tnum is the page number for the root BTree page of the table in the
10350 ** database file.  If Table.iDb is the index of the database table backend
10351 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10352 ** holds temporary tables and indices.  If TF_Ephemeral is set
10353 ** then the table is stored in a file that is automatically deleted
10354 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
10355 ** refers VDBE cursor number that holds the table open, not to the root
10356 ** page number.  Transient tables are used to hold the results of a
10357 ** sub-query that appears instead of a real table name in the FROM clause
10358 ** of a SELECT statement.
10359 */
10360 struct Table {
10361   char *zName;         /* Name of the table or view */
10362   Column *aCol;        /* Information about each column */
10363   Index *pIndex;       /* List of SQL indexes on this table. */
10364   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10365   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10366   char *zColAff;       /* String defining the affinity of each column */
10367 #ifndef SQLITE_OMIT_CHECK
10368   ExprList *pCheck;    /* All CHECK constraints */
10369 #endif
10370   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10371   int tnum;            /* Root BTree node for this table (see note above) */
10372   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10373   i16 nCol;            /* Number of columns in this table */
10374   u16 nRef;            /* Number of pointers to this Table */
10375   u8 tabFlags;         /* Mask of TF_* values */
10376   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10377 #ifndef SQLITE_OMIT_ALTERTABLE
10378   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10379 #endif
10380 #ifndef SQLITE_OMIT_VIRTUALTABLE
10381   int nModuleArg;      /* Number of arguments to the module */
10382   char **azModuleArg;  /* Text of all module args. [0] is module name */
10383   VTable *pVTable;     /* List of VTable objects. */
10384 #endif
10385   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10386   Schema *pSchema;     /* Schema that contains this table */
10387   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10388 };
10389
10390 /*
10391 ** Allowed values for Tabe.tabFlags.
10392 */
10393 #define TF_Readonly        0x01    /* Read-only system table */
10394 #define TF_Ephemeral       0x02    /* An ephemeral table */
10395 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10396 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10397 #define TF_Virtual         0x10    /* Is a virtual table */
10398
10399
10400 /*
10401 ** Test to see whether or not a table is a virtual table.  This is
10402 ** done as a macro so that it will be optimized out when virtual
10403 ** table support is omitted from the build.
10404 */
10405 #ifndef SQLITE_OMIT_VIRTUALTABLE
10406 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10407 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10408 #else
10409 #  define IsVirtual(X)      0
10410 #  define IsHiddenColumn(X) 0
10411 #endif
10412
10413 /*
10414 ** Each foreign key constraint is an instance of the following structure.
10415 **
10416 ** A foreign key is associated with two tables.  The "from" table is
10417 ** the table that contains the REFERENCES clause that creates the foreign
10418 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10419 ** Consider this example:
10420 **
10421 **     CREATE TABLE ex1(
10422 **       a INTEGER PRIMARY KEY,
10423 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10424 **     );
10425 **
10426 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10427 **
10428 ** Each REFERENCES clause generates an instance of the following structure
10429 ** which is attached to the from-table.  The to-table need not exist when
10430 ** the from-table is created.  The existence of the to-table is not checked.
10431 */
10432 struct FKey {
10433   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10434   FKey *pNextFrom;  /* Next foreign key in pFrom */
10435   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10436   FKey *pNextTo;    /* Next foreign key on table named zTo */
10437   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10438   int nCol;         /* Number of columns in this key */
10439   /* EV: R-30323-21917 */
10440   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10441   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10442   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10443   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10444     int iFrom;         /* Index of column in pFrom */
10445     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10446   } aCol[1];        /* One entry for each of nCol column s */
10447 };
10448
10449 /*
10450 ** SQLite supports many different ways to resolve a constraint
10451 ** error.  ROLLBACK processing means that a constraint violation
10452 ** causes the operation in process to fail and for the current transaction
10453 ** to be rolled back.  ABORT processing means the operation in process
10454 ** fails and any prior changes from that one operation are backed out,
10455 ** but the transaction is not rolled back.  FAIL processing means that
10456 ** the operation in progress stops and returns an error code.  But prior
10457 ** changes due to the same operation are not backed out and no rollback
10458 ** occurs.  IGNORE means that the particular row that caused the constraint
10459 ** error is not inserted or updated.  Processing continues and no error
10460 ** is returned.  REPLACE means that preexisting database rows that caused
10461 ** a UNIQUE constraint violation are removed so that the new insert or
10462 ** update can proceed.  Processing continues and no error is reported.
10463 **
10464 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10465 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10466 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10467 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10468 ** referenced table row is propagated into the row that holds the
10469 ** foreign key.
10470 **
10471 ** The following symbolic values are used to record which type
10472 ** of action to take.
10473 */
10474 #define OE_None     0   /* There is no constraint to check */
10475 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10476 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10477 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10478 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10479 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10480
10481 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10482 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10483 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10484 #define OE_Cascade  9   /* Cascade the changes */
10485
10486 #define OE_Default  99  /* Do whatever the default action is */
10487
10488
10489 /*
10490 ** An instance of the following structure is passed as the first
10491 ** argument to sqlite3VdbeKeyCompare and is used to control the
10492 ** comparison of the two index keys.
10493 */
10494 struct KeyInfo {
10495   sqlite3 *db;        /* The database connection */
10496   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10497   u16 nField;         /* Number of entries in aColl[] */
10498   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10499   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10500 };
10501
10502 /*
10503 ** An instance of the following structure holds information about a
10504 ** single index record that has already been parsed out into individual
10505 ** values.
10506 **
10507 ** A record is an object that contains one or more fields of data.
10508 ** Records are used to store the content of a table row and to store
10509 ** the key of an index.  A blob encoding of a record is created by
10510 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10511 ** OP_Column opcode.
10512 **
10513 ** This structure holds a record that has already been disassembled
10514 ** into its constituent fields.
10515 */
10516 struct UnpackedRecord {
10517   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10518   u16 nField;         /* Number of entries in apMem[] */
10519   u8 flags;           /* Boolean settings.  UNPACKED_... below */
10520   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10521   Mem *aMem;          /* Values */
10522 };
10523
10524 /*
10525 ** Allowed values of UnpackedRecord.flags
10526 */
10527 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10528 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10529 #define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10530
10531 /*
10532 ** Each SQL index is represented in memory by an
10533 ** instance of the following structure.
10534 **
10535 ** The columns of the table that are to be indexed are described
10536 ** by the aiColumn[] field of this structure.  For example, suppose
10537 ** we have the following table and index:
10538 **
10539 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10540 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10541 **
10542 ** In the Table structure describing Ex1, nCol==3 because there are
10543 ** three columns in the table.  In the Index structure describing
10544 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10545 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
10546 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10547 ** The second column to be indexed (c1) has an index of 0 in
10548 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10549 **
10550 ** The Index.onError field determines whether or not the indexed columns
10551 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10552 ** it means this is not a unique index.  Otherwise it is a unique index
10553 ** and the value of Index.onError indicate the which conflict resolution
10554 ** algorithm to employ whenever an attempt is made to insert a non-unique
10555 ** element.
10556 */
10557 struct Index {
10558   char *zName;     /* Name of this index */
10559   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10560   tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10561   Table *pTable;   /* The SQL table being indexed */
10562   char *zColAff;   /* String defining the affinity of each column */
10563   Index *pNext;    /* The next index associated with the same table */
10564   Schema *pSchema; /* Schema containing this index */
10565   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10566   char **azColl;   /* Array of collation sequence names for index */
10567   int nColumn;     /* Number of columns in the table used by this index */
10568   int tnum;        /* Page containing root of this index in database file */
10569   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10570   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10571   u8 bUnordered;   /* Use this index for == or IN queries only */
10572 #ifdef SQLITE_ENABLE_STAT3
10573   int nSample;             /* Number of elements in aSample[] */
10574   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10575   IndexSample *aSample;    /* Samples of the left-most key */
10576 #endif
10577 };
10578
10579 /*
10580 ** Each sample stored in the sqlite_stat3 table is represented in memory
10581 ** using a structure of this type.  See documentation at the top of the
10582 ** analyze.c source file for additional information.
10583 */
10584 struct IndexSample {
10585   union {
10586     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10587     double r;       /* Value if eType is SQLITE_FLOAT */
10588     i64 i;          /* Value if eType is SQLITE_INTEGER */
10589   } u;
10590   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10591   int nByte;        /* Size in byte of text or blob. */
10592   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10593   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10594   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10595 };
10596
10597 /*
10598 ** Each token coming out of the lexer is an instance of
10599 ** this structure.  Tokens are also used as part of an expression.
10600 **
10601 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10602 ** may contain random values.  Do not make any assumptions about Token.dyn
10603 ** and Token.n when Token.z==0.
10604 */
10605 struct Token {
10606   const char *z;     /* Text of the token.  Not NULL-terminated! */
10607   unsigned int n;    /* Number of characters in this token */
10608 };
10609
10610 /*
10611 ** An instance of this structure contains information needed to generate
10612 ** code for a SELECT that contains aggregate functions.
10613 **
10614 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10615 ** pointer to this structure.  The Expr.iColumn field is the index in
10616 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10617 ** code for that node.
10618 **
10619 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10620 ** original Select structure that describes the SELECT statement.  These
10621 ** fields do not need to be freed when deallocating the AggInfo structure.
10622 */
10623 struct AggInfo {
10624   u8 directMode;          /* Direct rendering mode means take data directly
10625                           ** from source tables rather than from accumulators */
10626   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10627                           ** than the source table */
10628   int sortingIdx;         /* Cursor number of the sorting index */
10629   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10630   int nSortingColumn;     /* Number of columns in the sorting index */
10631   ExprList *pGroupBy;     /* The group by clause */
10632   struct AggInfo_col {    /* For each column used in source tables */
10633     Table *pTab;             /* Source table */
10634     int iTable;              /* Cursor number of the source table */
10635     int iColumn;             /* Column number within the source table */
10636     int iSorterColumn;       /* Column number in the sorting index */
10637     int iMem;                /* Memory location that acts as accumulator */
10638     Expr *pExpr;             /* The original expression */
10639   } *aCol;
10640   int nColumn;            /* Number of used entries in aCol[] */
10641   int nAccumulator;       /* Number of columns that show through to the output.
10642                           ** Additional columns are used only as parameters to
10643                           ** aggregate functions */
10644   struct AggInfo_func {   /* For each aggregate function */
10645     Expr *pExpr;             /* Expression encoding the function */
10646     FuncDef *pFunc;          /* The aggregate function implementation */
10647     int iMem;                /* Memory location that acts as accumulator */
10648     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10649   } *aFunc;
10650   int nFunc;              /* Number of entries in aFunc[] */
10651 };
10652
10653 /*
10654 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10655 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10656 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10657 ** it uses less memory in the Expr object, which is a big memory user
10658 ** in systems with lots of prepared statements.  And few applications
10659 ** need more than about 10 or 20 variables.  But some extreme users want
10660 ** to have prepared statements with over 32767 variables, and for them
10661 ** the option is available (at compile-time).
10662 */
10663 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10664 typedef i16 ynVar;
10665 #else
10666 typedef int ynVar;
10667 #endif
10668
10669 /*
10670 ** Each node of an expression in the parse tree is an instance
10671 ** of this structure.
10672 **
10673 ** Expr.op is the opcode. The integer parser token codes are reused
10674 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10675 ** code representing the ">=" operator. This same integer code is reused
10676 ** to represent the greater-than-or-equal-to operator in the expression
10677 ** tree.
10678 **
10679 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10680 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10681 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10682 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10683 ** then Expr.token contains the name of the function.
10684 **
10685 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10686 ** binary operator. Either or both may be NULL.
10687 **
10688 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10689 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10690 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10691 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10692 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10693 ** valid.
10694 **
10695 ** An expression of the form ID or ID.ID refers to a column in a table.
10696 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10697 ** the integer cursor number of a VDBE cursor pointing to that table and
10698 ** Expr.iColumn is the column number for the specific column.  If the
10699 ** expression is used as a result in an aggregate SELECT, then the
10700 ** value is also stored in the Expr.iAgg column in the aggregate so that
10701 ** it can be accessed after all aggregates are computed.
10702 **
10703 ** If the expression is an unbound variable marker (a question mark
10704 ** character '?' in the original SQL) then the Expr.iTable holds the index
10705 ** number for that variable.
10706 **
10707 ** If the expression is a subquery then Expr.iColumn holds an integer
10708 ** register number containing the result of the subquery.  If the
10709 ** subquery gives a constant result, then iTable is -1.  If the subquery
10710 ** gives a different answer at different times during statement processing
10711 ** then iTable is the address of a subroutine that computes the subquery.
10712 **
10713 ** If the Expr is of type OP_Column, and the table it is selecting from
10714 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10715 ** corresponding table definition.
10716 **
10717 ** ALLOCATION NOTES:
10718 **
10719 ** Expr objects can use a lot of memory space in database schema.  To
10720 ** help reduce memory requirements, sometimes an Expr object will be
10721 ** truncated.  And to reduce the number of memory allocations, sometimes
10722 ** two or more Expr objects will be stored in a single memory allocation,
10723 ** together with Expr.zToken strings.
10724 **
10725 ** If the EP_Reduced and EP_TokenOnly flags are set when
10726 ** an Expr object is truncated.  When EP_Reduced is set, then all
10727 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10728 ** are contained within the same memory allocation.  Note, however, that
10729 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10730 ** allocated, regardless of whether or not EP_Reduced is set.
10731 */
10732 struct Expr {
10733   u8 op;                 /* Operation performed by this node */
10734   char affinity;         /* The affinity of the column or 0 if not a column */
10735   u16 flags;             /* Various flags.  EP_* See below */
10736   union {
10737     char *zToken;          /* Token value. Zero terminated and dequoted */
10738     int iValue;            /* Non-negative integer value if EP_IntValue */
10739   } u;
10740
10741   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10742   ** space is allocated for the fields below this point. An attempt to
10743   ** access them will result in a segfault or malfunction.
10744   *********************************************************************/
10745
10746   Expr *pLeft;           /* Left subnode */
10747   Expr *pRight;          /* Right subnode */
10748   union {
10749     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10750     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10751   } x;
10752
10753   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10754   ** space is allocated for the fields below this point. An attempt to
10755   ** access them will result in a segfault or malfunction.
10756   *********************************************************************/
10757
10758 #if SQLITE_MAX_EXPR_DEPTH>0
10759   int nHeight;           /* Height of the tree headed by this node */
10760 #endif
10761   int iTable;            /* TK_COLUMN: cursor number of table holding column
10762                          ** TK_REGISTER: register number
10763                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10764   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10765                          ** TK_VARIABLE: variable number (always >= 1). */
10766   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10767   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10768   u8 flags2;             /* Second set of flags.  EP2_... */
10769   u8 op2;                /* TK_REGISTER: original value of Expr.op
10770                          ** TK_COLUMN: the value of p5 for OP_Column
10771                          ** TK_AGG_FUNCTION: nesting depth */
10772   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10773   Table *pTab;           /* Table for TK_COLUMN expressions. */
10774 };
10775
10776 /*
10777 ** The following are the meanings of bits in the Expr.flags field.
10778 */
10779 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10780 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10781 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10782 #define EP_Error      0x0008  /* Expression contains one or more errors */
10783 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10784 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10785 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10786 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10787 #define EP_Collate    0x0100  /* Tree contains a TK_COLLATE opeartor */
10788 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10789 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10790 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10791 #define EP_Hint       0x1000  /* Not used */
10792 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10793 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10794 #define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10795
10796 /*
10797 ** The following are the meanings of bits in the Expr.flags2 field.
10798 */
10799 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10800 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10801
10802 /*
10803 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10804 ** flag on an expression structure.  This flag is used for VV&A only.  The
10805 ** routine is implemented as a macro that only works when in debugging mode,
10806 ** so as not to burden production code.
10807 */
10808 #ifdef SQLITE_DEBUG
10809 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10810 #else
10811 # define ExprSetIrreducible(X)
10812 #endif
10813
10814 /*
10815 ** These macros can be used to test, set, or clear bits in the
10816 ** Expr.flags field.
10817 */
10818 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10819 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10820 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10821 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10822
10823 /*
10824 ** Macros to determine the number of bytes required by a normal Expr
10825 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10826 ** and an Expr struct with the EP_TokenOnly flag set.
10827 */
10828 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10829 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10830 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10831
10832 /*
10833 ** Flags passed to the sqlite3ExprDup() function. See the header comment
10834 ** above sqlite3ExprDup() for details.
10835 */
10836 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10837
10838 /*
10839 ** A list of expressions.  Each expression may optionally have a
10840 ** name.  An expr/name combination can be used in several ways, such
10841 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10842 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10843 ** also be used as the argument to a function, in which case the a.zName
10844 ** field is not used.
10845 */
10846 struct ExprList {
10847   int nExpr;             /* Number of expressions on the list */
10848   int iECursor;          /* VDBE Cursor associated with this ExprList */
10849   struct ExprList_item { /* For each expression in the list */
10850     Expr *pExpr;           /* The list of expressions */
10851     char *zName;           /* Token associated with this expression */
10852     char *zSpan;           /* Original text of the expression */
10853     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10854     u8 done;               /* A flag to indicate when processing is finished */
10855     u16 iOrderByCol;       /* For ORDER BY, column number in result set */
10856     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10857   } *a;                  /* Alloc a power of two greater or equal to nExpr */
10858 };
10859
10860 /*
10861 ** An instance of this structure is used by the parser to record both
10862 ** the parse tree for an expression and the span of input text for an
10863 ** expression.
10864 */
10865 struct ExprSpan {
10866   Expr *pExpr;          /* The expression parse tree */
10867   const char *zStart;   /* First character of input text */
10868   const char *zEnd;     /* One character past the end of input text */
10869 };
10870
10871 /*
10872 ** An instance of this structure can hold a simple list of identifiers,
10873 ** such as the list "a,b,c" in the following statements:
10874 **
10875 **      INSERT INTO t(a,b,c) VALUES ...;
10876 **      CREATE INDEX idx ON t(a,b,c);
10877 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10878 **
10879 ** The IdList.a.idx field is used when the IdList represents the list of
10880 ** column names after a table name in an INSERT statement.  In the statement
10881 **
10882 **     INSERT INTO t(a,b,c) ...
10883 **
10884 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10885 */
10886 struct IdList {
10887   struct IdList_item {
10888     char *zName;      /* Name of the identifier */
10889     int idx;          /* Index in some Table.aCol[] of a column named zName */
10890   } *a;
10891   int nId;         /* Number of identifiers on the list */
10892 };
10893
10894 /*
10895 ** The bitmask datatype defined below is used for various optimizations.
10896 **
10897 ** Changing this from a 64-bit to a 32-bit type limits the number of
10898 ** tables in a join to 32 instead of 64.  But it also reduces the size
10899 ** of the library by 738 bytes on ix86.
10900 */
10901 typedef u64 Bitmask;
10902
10903 /*
10904 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10905 */
10906 #define BMS  ((int)(sizeof(Bitmask)*8))
10907
10908 /*
10909 ** The following structure describes the FROM clause of a SELECT statement.
10910 ** Each table or subquery in the FROM clause is a separate element of
10911 ** the SrcList.a[] array.
10912 **
10913 ** With the addition of multiple database support, the following structure
10914 ** can also be used to describe a particular table such as the table that
10915 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10916 ** such a table must be a simple name: ID.  But in SQLite, the table can
10917 ** now be identified by a database name, a dot, then the table name: ID.ID.
10918 **
10919 ** The jointype starts out showing the join type between the current table
10920 ** and the next table on the list.  The parser builds the list this way.
10921 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10922 ** jointype expresses the join between the table and the previous table.
10923 **
10924 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10925 ** contains more than 63 columns and the 64-th or later column is used.
10926 */
10927 struct SrcList {
10928   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10929   i16 nAlloc;      /* Number of entries allocated in a[] below */
10930   struct SrcList_item {
10931     Schema *pSchema;  /* Schema to which this item is fixed */
10932     char *zDatabase;  /* Name of database holding this table */
10933     char *zName;      /* Name of the table */
10934     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10935     Table *pTab;      /* An SQL table corresponding to zName */
10936     Select *pSelect;  /* A SELECT statement used in place of a table name */
10937     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10938     int regReturn;    /* Register holding return address of addrFillSub */
10939     u8 jointype;      /* Type of join between this able and the previous */
10940     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
10941     unsigned isCorrelated :1;  /* True if sub-query is correlated */
10942     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
10943 #ifndef SQLITE_OMIT_EXPLAIN
10944     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10945 #endif
10946     int iCursor;      /* The VDBE cursor number used to access this table */
10947     Expr *pOn;        /* The ON clause of a join */
10948     IdList *pUsing;   /* The USING clause of a join */
10949     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10950     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10951     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10952   } a[1];             /* One entry for each identifier on the list */
10953 };
10954
10955 /*
10956 ** Permitted values of the SrcList.a.jointype field
10957 */
10958 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10959 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10960 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10961 #define JT_LEFT      0x0008    /* Left outer join */
10962 #define JT_RIGHT     0x0010    /* Right outer join */
10963 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10964 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10965
10966
10967 /*
10968 ** A WherePlan object holds information that describes a lookup
10969 ** strategy.
10970 **
10971 ** This object is intended to be opaque outside of the where.c module.
10972 ** It is included here only so that that compiler will know how big it
10973 ** is.  None of the fields in this object should be used outside of
10974 ** the where.c module.
10975 **
10976 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10977 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10978 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10979 ** case that more than one of these conditions is true.
10980 */
10981 struct WherePlan {
10982   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10983   u16 nEq;                       /* Number of == constraints */
10984   u16 nOBSat;                    /* Number of ORDER BY terms satisfied */
10985   double nRow;                   /* Estimated number of rows (for EQP) */
10986   union {
10987     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10988     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10989     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10990   } u;
10991 };
10992
10993 /*
10994 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10995 ** structure contains a single instance of this structure.  This structure
10996 ** is intended to be private to the where.c module and should not be
10997 ** access or modified by other modules.
10998 **
10999 ** The pIdxInfo field is used to help pick the best index on a
11000 ** virtual table.  The pIdxInfo pointer contains indexing
11001 ** information for the i-th table in the FROM clause before reordering.
11002 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
11003 ** All other information in the i-th WhereLevel object for the i-th table
11004 ** after FROM clause ordering.
11005 */
11006 struct WhereLevel {
11007   WherePlan plan;       /* query plan for this element of the FROM clause */
11008   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
11009   int iTabCur;          /* The VDBE cursor used to access the table */
11010   int iIdxCur;          /* The VDBE cursor used to access pIdx */
11011   int addrBrk;          /* Jump here to break out of the loop */
11012   int addrNxt;          /* Jump here to start the next IN combination */
11013   int addrCont;         /* Jump here to continue with the next loop cycle */
11014   int addrFirst;        /* First instruction of interior of the loop */
11015   u8 iFrom;             /* Which entry in the FROM clause */
11016   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
11017   int p1, p2;           /* Operands of the opcode used to ends the loop */
11018   union {               /* Information that depends on plan.wsFlags */
11019     struct {
11020       int nIn;              /* Number of entries in aInLoop[] */
11021       struct InLoop {
11022         int iCur;              /* The VDBE cursor used by this IN operator */
11023         int addrInTop;         /* Top of the IN loop */
11024       } *aInLoop;           /* Information about each nested IN operator */
11025     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
11026     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
11027   } u;
11028   double rOptCost;      /* "Optimal" cost for this level */
11029
11030   /* The following field is really not part of the current level.  But
11031   ** we need a place to cache virtual table index information for each
11032   ** virtual table in the FROM clause and the WhereLevel structure is
11033   ** a convenient place since there is one WhereLevel for each FROM clause
11034   ** element.
11035   */
11036   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
11037 };
11038
11039 /*
11040 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11041 ** and the WhereInfo.wctrlFlags member.
11042 */
11043 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11044 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11045 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11046 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11047 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11048 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11049 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11050 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11051 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
11052
11053 /*
11054 ** The WHERE clause processing routine has two halves.  The
11055 ** first part does the start of the WHERE loop and the second
11056 ** half does the tail of the WHERE loop.  An instance of
11057 ** this structure is returned by the first half and passed
11058 ** into the second half to give some continuity.
11059 */
11060 struct WhereInfo {
11061   Parse *pParse;            /* Parsing and code generating context */
11062   SrcList *pTabList;        /* List of tables in the join */
11063   u16 nOBSat;               /* Number of ORDER BY terms satisfied by indices */
11064   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
11065   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
11066   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
11067   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
11068   int iTop;                 /* The very beginning of the WHERE loop */
11069   int iContinue;            /* Jump here to continue with next record */
11070   int iBreak;               /* Jump here to break out of the loop */
11071   int nLevel;               /* Number of nested loop */
11072   struct WhereClause *pWC;  /* Decomposition of the WHERE clause */
11073   double savedNQueryLoop;   /* pParse->nQueryLoop outside the WHERE loop */
11074   double nRowOut;           /* Estimated number of output rows */
11075   WhereLevel a[1];          /* Information about each nest loop in WHERE */
11076 };
11077
11078 /* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
11079 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11080 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11081 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11082 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11083
11084 /*
11085 ** A NameContext defines a context in which to resolve table and column
11086 ** names.  The context consists of a list of tables (the pSrcList) field and
11087 ** a list of named expression (pEList).  The named expression list may
11088 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11089 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11090 ** pEList corresponds to the result set of a SELECT and is NULL for
11091 ** other statements.
11092 **
11093 ** NameContexts can be nested.  When resolving names, the inner-most
11094 ** context is searched first.  If no match is found, the next outer
11095 ** context is checked.  If there is still no match, the next context
11096 ** is checked.  This process continues until either a match is found
11097 ** or all contexts are check.  When a match is found, the nRef member of
11098 ** the context containing the match is incremented.
11099 **
11100 ** Each subquery gets a new NameContext.  The pNext field points to the
11101 ** NameContext in the parent query.  Thus the process of scanning the
11102 ** NameContext list corresponds to searching through successively outer
11103 ** subqueries looking for a match.
11104 */
11105 struct NameContext {
11106   Parse *pParse;       /* The parser */
11107   SrcList *pSrcList;   /* One or more tables used to resolve names */
11108   ExprList *pEList;    /* Optional list of named expressions */
11109   AggInfo *pAggInfo;   /* Information about aggregates at this level */
11110   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11111   int nRef;            /* Number of names resolved by this context */
11112   int nErr;            /* Number of errors encountered while resolving names */
11113   u8 ncFlags;          /* Zero or more NC_* flags defined below */
11114 };
11115
11116 /*
11117 ** Allowed values for the NameContext, ncFlags field.
11118 */
11119 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11120 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11121 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11122 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11123
11124 /*
11125 ** An instance of the following structure contains all information
11126 ** needed to generate code for a single SELECT statement.
11127 **
11128 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11129 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11130 ** limit and nOffset to the value of the offset (or 0 if there is not
11131 ** offset).  But later on, nLimit and nOffset become the memory locations
11132 ** in the VDBE that record the limit and offset counters.
11133 **
11134 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11135 ** These addresses must be stored so that we can go back and fill in
11136 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11137 ** the number of columns in P2 can be computed at the same time
11138 ** as the OP_OpenEphm instruction is coded because not
11139 ** enough information about the compound query is known at that point.
11140 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11141 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11142 ** sequences for the ORDER BY clause.
11143 */
11144 struct Select {
11145   ExprList *pEList;      /* The fields of the result */
11146   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11147   u16 selFlags;          /* Various SF_* values */
11148   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11149   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11150   double nSelectRow;     /* Estimated number of result rows */
11151   SrcList *pSrc;         /* The FROM clause */
11152   Expr *pWhere;          /* The WHERE clause */
11153   ExprList *pGroupBy;    /* The GROUP BY clause */
11154   Expr *pHaving;         /* The HAVING clause */
11155   ExprList *pOrderBy;    /* The ORDER BY clause */
11156   Select *pPrior;        /* Prior select in a compound select statement */
11157   Select *pNext;         /* Next select to the left in a compound */
11158   Select *pRightmost;    /* Right-most select in a compound select statement */
11159   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11160   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11161 };
11162
11163 /*
11164 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11165 ** "Select Flag".
11166 */
11167 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
11168 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
11169 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
11170 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11171 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11172 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11173 #define SF_UseSorter       0x0040  /* Sort using a sorter */
11174 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
11175 #define SF_Materialize     0x0100  /* Force materialization of views */
11176
11177
11178 /*
11179 ** The results of a select can be distributed in several ways.  The
11180 ** "SRT" prefix means "SELECT Result Type".
11181 */
11182 #define SRT_Union        1  /* Store result as keys in an index */
11183 #define SRT_Except       2  /* Remove result from a UNION index */
11184 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11185 #define SRT_Discard      4  /* Do not save the results anywhere */
11186
11187 /* The ORDER BY clause is ignored for all of the above */
11188 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11189
11190 #define SRT_Output       5  /* Output each row of result */
11191 #define SRT_Mem          6  /* Store result in a memory cell */
11192 #define SRT_Set          7  /* Store results as keys in an index */
11193 #define SRT_Table        8  /* Store result as data with an automatic rowid */
11194 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11195 #define SRT_Coroutine   10  /* Generate a single row of result */
11196
11197 /*
11198 ** An instance of this object describes where to put of the results of
11199 ** a SELECT statement.
11200 */
11201 struct SelectDest {
11202   u8 eDest;         /* How to dispose of the results.  On of SRT_* above. */
11203   char affSdst;     /* Affinity used when eDest==SRT_Set */
11204   int iSDParm;      /* A parameter used by the eDest disposal method */
11205   int iSdst;        /* Base register where results are written */
11206   int nSdst;        /* Number of registers allocated */
11207 };
11208
11209 /*
11210 ** During code generation of statements that do inserts into AUTOINCREMENT
11211 ** tables, the following information is attached to the Table.u.autoInc.p
11212 ** pointer of each autoincrement table to record some side information that
11213 ** the code generator needs.  We have to keep per-table autoincrement
11214 ** information in case inserts are down within triggers.  Triggers do not
11215 ** normally coordinate their activities, but we do need to coordinate the
11216 ** loading and saving of autoincrement information.
11217 */
11218 struct AutoincInfo {
11219   AutoincInfo *pNext;   /* Next info block in a list of them all */
11220   Table *pTab;          /* Table this info block refers to */
11221   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11222   int regCtr;           /* Memory register holding the rowid counter */
11223 };
11224
11225 /*
11226 ** Size of the column cache
11227 */
11228 #ifndef SQLITE_N_COLCACHE
11229 # define SQLITE_N_COLCACHE 10
11230 #endif
11231
11232 /*
11233 ** At least one instance of the following structure is created for each
11234 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11235 ** statement. All such objects are stored in the linked list headed at
11236 ** Parse.pTriggerPrg and deleted once statement compilation has been
11237 ** completed.
11238 **
11239 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11240 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11241 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11242 ** The Parse.pTriggerPrg list never contains two entries with the same
11243 ** values for both pTrigger and orconf.
11244 **
11245 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11246 ** accessed (or set to 0 for triggers fired as a result of INSERT
11247 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11248 ** a mask of new.* columns used by the program.
11249 */
11250 struct TriggerPrg {
11251   Trigger *pTrigger;      /* Trigger this program was coded from */
11252   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11253   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11254   int orconf;             /* Default ON CONFLICT policy */
11255   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11256 };
11257
11258 /*
11259 ** The yDbMask datatype for the bitmask of all attached databases.
11260 */
11261 #if SQLITE_MAX_ATTACHED>30
11262   typedef sqlite3_uint64 yDbMask;
11263 #else
11264   typedef unsigned int yDbMask;
11265 #endif
11266
11267 /*
11268 ** An SQL parser context.  A copy of this structure is passed through
11269 ** the parser and down into all the parser action routine in order to
11270 ** carry around information that is global to the entire parse.
11271 **
11272 ** The structure is divided into two parts.  When the parser and code
11273 ** generate call themselves recursively, the first part of the structure
11274 ** is constant but the second part is reset at the beginning and end of
11275 ** each recursion.
11276 **
11277 ** The nTableLock and aTableLock variables are only used if the shared-cache
11278 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11279 ** used to store the set of table-locks required by the statement being
11280 ** compiled. Function sqlite3TableLock() is used to add entries to the
11281 ** list.
11282 */
11283 struct Parse {
11284   sqlite3 *db;         /* The main database structure */
11285   char *zErrMsg;       /* An error message */
11286   Vdbe *pVdbe;         /* An engine for executing database bytecode */
11287   int rc;              /* Return code from execution */
11288   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11289   u8 checkSchema;      /* Causes schema cookie check after an error */
11290   u8 nested;           /* Number of nested calls to the parser/code generator */
11291   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11292   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11293   u8 nColCache;        /* Number of entries in aColCache[] */
11294   u8 iColCache;        /* Next entry in aColCache[] to replace */
11295   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11296   u8 mayAbort;         /* True if statement may throw an ABORT exception */
11297   int aTempReg[8];     /* Holding area for temporary registers */
11298   int nRangeReg;       /* Size of the temporary register block */
11299   int iRangeReg;       /* First register in temporary register block */
11300   int nErr;            /* Number of errors seen */
11301   int nTab;            /* Number of previously allocated VDBE cursors */
11302   int nMem;            /* Number of memory cells used so far */
11303   int nSet;            /* Number of sets used so far */
11304   int nOnce;           /* Number of OP_Once instructions so far */
11305   int ckBase;          /* Base register of data during check constraints */
11306   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11307   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11308   struct yColCache {
11309     int iTable;           /* Table cursor number */
11310     int iColumn;          /* Table column number */
11311     u8 tempReg;           /* iReg is a temp register that needs to be freed */
11312     int iLevel;           /* Nesting level */
11313     int iReg;             /* Reg with value of this column. 0 means none. */
11314     int lru;              /* Least recently used entry has the smallest value */
11315   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11316   yDbMask writeMask;   /* Start a write transaction on these databases */
11317   yDbMask cookieMask;  /* Bitmask of schema verified databases */
11318   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11319   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11320   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11321   int regRoot;         /* Register holding root page number for new objects */
11322   int nMaxArg;         /* Max args passed to user function by sub-program */
11323   Token constraintName;/* Name of the constraint currently being parsed */
11324 #ifndef SQLITE_OMIT_SHARED_CACHE
11325   int nTableLock;        /* Number of locks in aTableLock */
11326   TableLock *aTableLock; /* Required table locks for shared-cache mode */
11327 #endif
11328   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11329
11330   /* Information used while coding trigger programs. */
11331   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11332   Table *pTriggerTab;  /* Table triggers are being coded for */
11333   double nQueryLoop;   /* Estimated number of iterations of a query */
11334   u32 oldmask;         /* Mask of old.* columns referenced */
11335   u32 newmask;         /* Mask of new.* columns referenced */
11336   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11337   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11338   u8 disableTriggers;  /* True to disable triggers */
11339
11340   /* Above is constant between recursions.  Below is reset before and after
11341   ** each recursion */
11342
11343   int nVar;                 /* Number of '?' variables seen in the SQL so far */
11344   int nzVar;                /* Number of available slots in azVar[] */
11345   u8 explain;               /* True if the EXPLAIN flag is found on the query */
11346 #ifndef SQLITE_OMIT_VIRTUALTABLE
11347   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11348   int nVtabLock;            /* Number of virtual tables to lock */
11349 #endif
11350   int nAlias;               /* Number of aliased result set columns */
11351   int nHeight;              /* Expression tree height of current sub-select */
11352 #ifndef SQLITE_OMIT_EXPLAIN
11353   int iSelectId;            /* ID of current select for EXPLAIN output */
11354   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11355 #endif
11356   char **azVar;             /* Pointers to names of parameters */
11357   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11358   int *aAlias;              /* Register used to hold aliased result */
11359   const char *zTail;        /* All SQL text past the last semicolon parsed */
11360   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11361   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11362   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11363   Token sNameToken;         /* Token with unqualified schema object name */
11364   Token sLastToken;         /* The last token parsed */
11365 #ifndef SQLITE_OMIT_VIRTUALTABLE
11366   Token sArg;               /* Complete text of a module argument */
11367   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11368 #endif
11369   Table *pZombieTab;        /* List of Table objects to delete after code gen */
11370   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11371 };
11372
11373 /*
11374 ** Return true if currently inside an sqlite3_declare_vtab() call.
11375 */
11376 #ifdef SQLITE_OMIT_VIRTUALTABLE
11377   #define IN_DECLARE_VTAB 0
11378 #else
11379   #define IN_DECLARE_VTAB (pParse->declareVtab)
11380 #endif
11381
11382 /*
11383 ** An instance of the following structure can be declared on a stack and used
11384 ** to save the Parse.zAuthContext value so that it can be restored later.
11385 */
11386 struct AuthContext {
11387   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11388   Parse *pParse;              /* The Parse structure */
11389 };
11390
11391 /*
11392 ** Bitfield flags for P5 value in various opcodes.
11393 */
11394 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11395 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11396 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11397 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11398 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11399 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11400 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11401 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11402 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
11403 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
11404 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
11405
11406 /*
11407  * Each trigger present in the database schema is stored as an instance of
11408  * struct Trigger.
11409  *
11410  * Pointers to instances of struct Trigger are stored in two ways.
11411  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11412  *    database). This allows Trigger structures to be retrieved by name.
11413  * 2. All triggers associated with a single table form a linked list, using the
11414  *    pNext member of struct Trigger. A pointer to the first element of the
11415  *    linked list is stored as the "pTrigger" member of the associated
11416  *    struct Table.
11417  *
11418  * The "step_list" member points to the first element of a linked list
11419  * containing the SQL statements specified as the trigger program.
11420  */
11421 struct Trigger {
11422   char *zName;            /* The name of the trigger                        */
11423   char *table;            /* The table or view to which the trigger applies */
11424   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11425   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11426   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11427   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11428                              the <column-list> is stored here */
11429   Schema *pSchema;        /* Schema containing the trigger */
11430   Schema *pTabSchema;     /* Schema containing the table */
11431   TriggerStep *step_list; /* Link list of trigger program steps             */
11432   Trigger *pNext;         /* Next trigger associated with the table */
11433 };
11434
11435 /*
11436 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11437 ** determine which.
11438 **
11439 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11440 ** In that cases, the constants below can be ORed together.
11441 */
11442 #define TRIGGER_BEFORE  1
11443 #define TRIGGER_AFTER   2
11444
11445 /*
11446  * An instance of struct TriggerStep is used to store a single SQL statement
11447  * that is a part of a trigger-program.
11448  *
11449  * Instances of struct TriggerStep are stored in a singly linked list (linked
11450  * using the "pNext" member) referenced by the "step_list" member of the
11451  * associated struct Trigger instance. The first element of the linked list is
11452  * the first step of the trigger-program.
11453  *
11454  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11455  * "SELECT" statement. The meanings of the other members is determined by the
11456  * value of "op" as follows:
11457  *
11458  * (op == TK_INSERT)
11459  * orconf    -> stores the ON CONFLICT algorithm
11460  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11461  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11462  * target    -> A token holding the quoted name of the table to insert into.
11463  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11464  *              this stores values to be inserted. Otherwise NULL.
11465  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11466  *              statement, then this stores the column-names to be
11467  *              inserted into.
11468  *
11469  * (op == TK_DELETE)
11470  * target    -> A token holding the quoted name of the table to delete from.
11471  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11472  *              Otherwise NULL.
11473  *
11474  * (op == TK_UPDATE)
11475  * target    -> A token holding the quoted name of the table to update rows of.
11476  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11477  *              Otherwise NULL.
11478  * pExprList -> A list of the columns to update and the expressions to update
11479  *              them to. See sqlite3Update() documentation of "pChanges"
11480  *              argument.
11481  *
11482  */
11483 struct TriggerStep {
11484   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11485   u8 orconf;           /* OE_Rollback etc. */
11486   Trigger *pTrig;      /* The trigger that this step is a part of */
11487   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11488   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11489   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11490   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11491   IdList *pIdList;     /* Column names for INSERT */
11492   TriggerStep *pNext;  /* Next in the link-list */
11493   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11494 };
11495
11496 /*
11497 ** The following structure contains information used by the sqliteFix...
11498 ** routines as they walk the parse tree to make database references
11499 ** explicit.
11500 */
11501 typedef struct DbFixer DbFixer;
11502 struct DbFixer {
11503   Parse *pParse;      /* The parsing context.  Error messages written here */
11504   Schema *pSchema;    /* Fix items to this schema */
11505   const char *zDb;    /* Make sure all objects are contained in this database */
11506   const char *zType;  /* Type of the container - used for error messages */
11507   const Token *pName; /* Name of the container - used for error messages */
11508 };
11509
11510 /*
11511 ** An objected used to accumulate the text of a string where we
11512 ** do not necessarily know how big the string will be in the end.
11513 */
11514 struct StrAccum {
11515   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11516   char *zBase;         /* A base allocation.  Not from malloc. */
11517   char *zText;         /* The string collected so far */
11518   int  nChar;          /* Length of the string so far */
11519   int  nAlloc;         /* Amount of space allocated in zText */
11520   int  mxAlloc;        /* Maximum allowed string length */
11521   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11522   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11523   u8   tooBig;         /* Becomes true if string size exceeds limits */
11524 };
11525
11526 /*
11527 ** A pointer to this structure is used to communicate information
11528 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11529 */
11530 typedef struct {
11531   sqlite3 *db;        /* The database being initialized */
11532   char **pzErrMsg;    /* Error message stored here */
11533   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11534   int rc;             /* Result code stored here */
11535 } InitData;
11536
11537 /*
11538 ** Structure containing global configuration data for the SQLite library.
11539 **
11540 ** This structure also contains some state information.
11541 */
11542 struct Sqlite3Config {
11543   int bMemstat;                     /* True to enable memory status */
11544   int bCoreMutex;                   /* True to enable core mutexing */
11545   int bFullMutex;                   /* True to enable full mutexing */
11546   int bOpenUri;                     /* True to interpret filenames as URIs */
11547   int bUseCis;                      /* Use covering indices for full-scans */
11548   int mxStrlen;                     /* Maximum string length */
11549   int szLookaside;                  /* Default lookaside buffer size */
11550   int nLookaside;                   /* Default lookaside buffer count */
11551   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11552   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11553   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11554   void *pHeap;                      /* Heap storage space */
11555   int nHeap;                        /* Size of pHeap[] */
11556   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11557   void *pScratch;                   /* Scratch memory */
11558   int szScratch;                    /* Size of each scratch buffer */
11559   int nScratch;                     /* Number of scratch buffers */
11560   void *pPage;                      /* Page cache memory */
11561   int szPage;                       /* Size of each page in pPage[] */
11562   int nPage;                        /* Number of pages in pPage[] */
11563   int mxParserStack;                /* maximum depth of the parser stack */
11564   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11565   /* The above might be initialized to non-zero.  The following need to always
11566   ** initially be zero, however. */
11567   int isInit;                       /* True after initialization has finished */
11568   int inProgress;                   /* True while initialization in progress */
11569   int isMutexInit;                  /* True after mutexes are initialized */
11570   int isMallocInit;                 /* True after malloc is initialized */
11571   int isPCacheInit;                 /* True after malloc is initialized */
11572   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11573   int nRefInitMutex;                /* Number of users of pInitMutex */
11574   void (*xLog)(void*,int,const char*); /* Function for logging */
11575   void *pLogArg;                       /* First argument to xLog() */
11576   int bLocaltimeFault;              /* True to fail localtime() calls */
11577 #ifdef SQLITE_ENABLE_SQLLOG
11578   void(*xSqllog)(void*,sqlite3*,const char*, int);
11579   void *pSqllogArg;
11580 #endif
11581 };
11582
11583 /*
11584 ** Context pointer passed down through the tree-walk.
11585 */
11586 struct Walker {
11587   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11588   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11589   Parse *pParse;                            /* Parser context.  */
11590   int walkerDepth;                          /* Number of subqueries */
11591   union {                                   /* Extra data for callback */
11592     NameContext *pNC;                          /* Naming context */
11593     int i;                                     /* Integer value */
11594     SrcList *pSrcList;                         /* FROM clause */
11595     struct SrcCount *pSrcCount;                /* Counting column references */
11596   } u;
11597 };
11598
11599 /* Forward declarations */
11600 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11601 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11602 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11603 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11604 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11605
11606 /*
11607 ** Return code from the parse-tree walking primitives and their
11608 ** callbacks.
11609 */
11610 #define WRC_Continue    0   /* Continue down into children */
11611 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11612 #define WRC_Abort       2   /* Abandon the tree walk */
11613
11614 /*
11615 ** Assuming zIn points to the first byte of a UTF-8 character,
11616 ** advance zIn to point to the first byte of the next UTF-8 character.
11617 */
11618 #define SQLITE_SKIP_UTF8(zIn) {                        \
11619   if( (*(zIn++))>=0xc0 ){                              \
11620     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11621   }                                                    \
11622 }
11623
11624 /*
11625 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11626 ** the same name but without the _BKPT suffix.  These macros invoke
11627 ** routines that report the line-number on which the error originated
11628 ** using sqlite3_log().  The routines also provide a convenient place
11629 ** to set a debugger breakpoint.
11630 */
11631 SQLITE_PRIVATE int sqlite3CorruptError(int);
11632 SQLITE_PRIVATE int sqlite3MisuseError(int);
11633 SQLITE_PRIVATE int sqlite3CantopenError(int);
11634 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11635 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11636 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11637
11638
11639 /*
11640 ** FTS4 is really an extension for FTS3.  It is enabled using the
11641 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11642 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11643 */
11644 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11645 # define SQLITE_ENABLE_FTS3
11646 #endif
11647
11648 /*
11649 ** The ctype.h header is needed for non-ASCII systems.  It is also
11650 ** needed by FTS3 when FTS3 is included in the amalgamation.
11651 */
11652 #if !defined(SQLITE_ASCII) || \
11653     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11654 # include <ctype.h>
11655 #endif
11656
11657 /*
11658 ** The following macros mimic the standard library functions toupper(),
11659 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11660 ** sqlite versions only work for ASCII characters, regardless of locale.
11661 */
11662 #ifdef SQLITE_ASCII
11663 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11664 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11665 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11666 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11667 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11668 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11669 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11670 #else
11671 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11672 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11673 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11674 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11675 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11676 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11677 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11678 #endif
11679
11680 /*
11681 ** Internal function prototypes
11682 */
11683 #define sqlite3StrICmp sqlite3_stricmp
11684 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11685 #define sqlite3StrNICmp sqlite3_strnicmp
11686
11687 SQLITE_PRIVATE int sqlite3MallocInit(void);
11688 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11689 SQLITE_PRIVATE void *sqlite3Malloc(int);
11690 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11691 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11692 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11693 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11694 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11695 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11696 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11697 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11698 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11699 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11700 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11701 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11702 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11703 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11704 SQLITE_PRIVATE void sqlite3PageFree(void*);
11705 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11706 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11707 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11708
11709 /*
11710 ** On systems with ample stack space and that support alloca(), make
11711 ** use of alloca() to obtain space for large automatic objects.  By default,
11712 ** obtain space from malloc().
11713 **
11714 ** The alloca() routine never returns NULL.  This will cause code paths
11715 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11716 */
11717 #ifdef SQLITE_USE_ALLOCA
11718 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11719 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11720 # define sqlite3StackFree(D,P)
11721 #else
11722 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11723 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11724 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11725 #endif
11726
11727 #ifdef SQLITE_ENABLE_MEMSYS3
11728 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11729 #endif
11730 #ifdef SQLITE_ENABLE_MEMSYS5
11731 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11732 #endif
11733
11734
11735 #ifndef SQLITE_MUTEX_OMIT
11736 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11737 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11738 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11739 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11740 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11741 #endif
11742
11743 SQLITE_PRIVATE int sqlite3StatusValue(int);
11744 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11745 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11746
11747 #ifndef SQLITE_OMIT_FLOATING_POINT
11748 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11749 #else
11750 # define sqlite3IsNaN(X)  0
11751 #endif
11752
11753 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11754 #ifndef SQLITE_OMIT_TRACE
11755 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11756 #endif
11757 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11758 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11759 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11760 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11761 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11762 #endif
11763 #if defined(SQLITE_TEST)
11764 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11765 #endif
11766
11767 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11768 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11769 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11770 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11771 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11772 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11773 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11774 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11775 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11776 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11777 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11778 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11779 #else
11780 # define sqlite3ExplainBegin(X)
11781 # define sqlite3ExplainSelect(A,B)
11782 # define sqlite3ExplainExpr(A,B)
11783 # define sqlite3ExplainExprList(A,B)
11784 # define sqlite3ExplainFinish(X)
11785 # define sqlite3VdbeExplanation(X) 0
11786 #endif
11787
11788
11789 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11790 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11791 SQLITE_PRIVATE int sqlite3Dequote(char*);
11792 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11793 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11794 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11795 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11796 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11797 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11798 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11799 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11800 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11801 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11802 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11803 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11804 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11805 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11806 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11807 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11808 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11809 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11810 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11811 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11812 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11813 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11814 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11815 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11816 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11817 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11818 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11819 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11820 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11821 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11822 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11823 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11824 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11825 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11826 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11827 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11828 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11829 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11830 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11831 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11832                     sqlite3_vfs**,char**,char **);
11833 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11834 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11835
11836 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11837 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11838 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11839 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11840 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11841 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11842 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11843
11844 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11845 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11846 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11847 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11848 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11849
11850 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11851
11852 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11853 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11854 #else
11855 # define sqlite3ViewGetColumnNames(A,B) 0
11856 #endif
11857
11858 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11859 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11860 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11861 #ifndef SQLITE_OMIT_AUTOINCREMENT
11862 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11863 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11864 #else
11865 # define sqlite3AutoincrementBegin(X)
11866 # define sqlite3AutoincrementEnd(X)
11867 #endif
11868 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
11869 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11870 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
11871 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11872 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11873 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11874 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11875 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11876                                       Token*, Select*, Expr*, IdList*);
11877 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11878 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11879 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11880 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11881 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11882 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11883 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11884                         Token*, int, int);
11885 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11886 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11887 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11888                          Expr*,ExprList*,int,Expr*,Expr*);
11889 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11890 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11891 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11892 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11893 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11894 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11895 #endif
11896 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11897 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11898 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
11899 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11900 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
11901 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11902 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11903 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11904 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11905 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11906 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11907 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11908 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11909 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11910 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11911 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11912 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11913 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11914 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11915 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11916 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11917 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11918 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11919 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
11920 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11921 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11922 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11923 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11924 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11925 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11926 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11927 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11928 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11929 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11930 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
11931 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11932 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11933 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11934 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11935 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
11936 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11937 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11938 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11939 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11940 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11941 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11942 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11943 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
11944 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11945 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11946 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11947 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11948 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11949 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11950 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11951 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11952 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11953 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11954 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11955 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11956                                      int*,int,int,int,int,int*);
11957 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11958 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11959 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11960 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11961 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11962 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11963 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11964 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11965 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11966 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11967 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11968 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11969 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
11970 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11971 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11972 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11973 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11974 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11975 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11976
11977 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11978 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11979 #endif
11980
11981 #ifndef SQLITE_OMIT_TRIGGER
11982 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11983                            Expr*,int, int);
11984 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11985 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11986 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11987 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11988 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11989 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11990                             int, int, int);
11991 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11992   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11993 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11994 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11995 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11996                                         ExprList*,Select*,u8);
11997 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11998 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11999 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12000 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12001 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12002 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12003 #else
12004 # define sqlite3TriggersExist(B,C,D,E,F) 0
12005 # define sqlite3DeleteTrigger(A,B)
12006 # define sqlite3DropTriggerPtr(A,B)
12007 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12008 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12009 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12010 # define sqlite3TriggerList(X, Y) 0
12011 # define sqlite3ParseToplevel(p) p
12012 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12013 #endif
12014
12015 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12016 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12017 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12018 #ifndef SQLITE_OMIT_AUTHORIZATION
12019 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12020 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12021 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12022 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12023 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12024 #else
12025 # define sqlite3AuthRead(a,b,c,d)
12026 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12027 # define sqlite3AuthContextPush(a,b,c)
12028 # define sqlite3AuthContextPop(a)  ((void)(a))
12029 #endif
12030 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12031 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12032 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12033 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12034 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12035 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12036 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12037 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12038 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12039 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12040 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12041 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12042 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12043 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12044
12045 /*
12046 ** Routines to read and write variable-length integers.  These used to
12047 ** be defined locally, but now we use the varint routines in the util.c
12048 ** file.  Code should use the MACRO forms below, as the Varint32 versions
12049 ** are coded to assume the single byte case is already handled (which
12050 ** the MACRO form does).
12051 */
12052 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12053 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12054 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12055 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12056 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12057
12058 /*
12059 ** The header of a record consists of a sequence variable-length integers.
12060 ** These integers are almost always small and are encoded as a single byte.
12061 ** The following macros take advantage this fact to provide a fast encode
12062 ** and decode of the integers in a record header.  It is faster for the common
12063 ** case where the integer is a single byte.  It is a little slower when the
12064 ** integer is two or more bytes.  But overall it is faster.
12065 **
12066 ** The following expressions are equivalent:
12067 **
12068 **     x = sqlite3GetVarint32( A, &B );
12069 **     x = sqlite3PutVarint32( A, B );
12070 **
12071 **     x = getVarint32( A, B );
12072 **     x = putVarint32( A, B );
12073 **
12074 */
12075 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
12076 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
12077 #define getVarint    sqlite3GetVarint
12078 #define putVarint    sqlite3PutVarint
12079
12080
12081 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12082 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12083 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12084 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12085 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12086 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12087 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12088 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12089 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12090 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12091 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12092 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12093 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12094 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12095 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12096 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12097 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12098 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12099 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12100 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12101 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12102 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12103 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12104 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12105 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12106 #ifdef SQLITE_ENABLE_8_3_NAMES
12107 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12108 #else
12109 # define sqlite3FileSuffix3(X,Y)
12110 #endif
12111 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12112
12113 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12114 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12115 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
12116                         void(*)(void*));
12117 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12118 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12119 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12120 #ifdef SQLITE_ENABLE_STAT3
12121 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
12122 #endif
12123 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12124 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12125 #ifndef SQLITE_AMALGAMATION
12126 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12127 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12128 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12129 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12130 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12131 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12132 #ifndef SQLITE_OMIT_WSD
12133 SQLITE_PRIVATE int sqlite3PendingByte;
12134 #endif
12135 #endif
12136 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12137 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12138 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12139 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12140 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12141 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12142 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12143 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12144 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12145 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12146 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12147 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12148 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12149 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12150 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12151 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12152 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12153 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12154 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12155 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12156 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12157 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12158 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12159 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12160 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12161 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12162 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12163 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12164 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12165 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12166 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12167 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
12168   void (*)(sqlite3_context*,int,sqlite3_value **),
12169   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12170   FuncDestructor *pDestructor
12171 );
12172 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12173 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12174
12175 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12176 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12177 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12178 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12179 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12180 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12181 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12182
12183 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12184 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12185
12186 /*
12187 ** The interface to the LEMON-generated parser
12188 */
12189 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12190 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12191 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12192 #ifdef YYTRACKMAXSTACKDEPTH
12193 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12194 #endif
12195
12196 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12197 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12198 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12199 #else
12200 # define sqlite3CloseExtensions(X)
12201 #endif
12202
12203 #ifndef SQLITE_OMIT_SHARED_CACHE
12204 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12205 #else
12206   #define sqlite3TableLock(v,w,x,y,z)
12207 #endif
12208
12209 #ifdef SQLITE_TEST
12210 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12211 #endif
12212
12213 #ifdef SQLITE_OMIT_VIRTUALTABLE
12214 #  define sqlite3VtabClear(Y)
12215 #  define sqlite3VtabSync(X,Y) SQLITE_OK
12216 #  define sqlite3VtabRollback(X)
12217 #  define sqlite3VtabCommit(X)
12218 #  define sqlite3VtabInSync(db) 0
12219 #  define sqlite3VtabLock(X)
12220 #  define sqlite3VtabUnlock(X)
12221 #  define sqlite3VtabUnlockList(X)
12222 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12223 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12224 #else
12225 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12226 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12227 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12228 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12229 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12230 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12231 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12232 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12233 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12234 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12235 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12236 #endif
12237 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12238 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12239 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12240 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12241 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12242 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12243 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12244 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12245 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12246 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12247 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12248 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12249 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12250 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12251 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12252 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12253 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12254 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12255 #ifndef SQLITE_OMIT_WAL
12256 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12257 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12258 #endif
12259
12260 /* Declarations for functions in fkey.c. All of these are replaced by
12261 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12262 ** key functionality is available. If OMIT_TRIGGER is defined but
12263 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12264 ** this case foreign keys are parsed, but no other functionality is
12265 ** provided (enforcement of FK constraints requires the triggers sub-system).
12266 */
12267 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12268 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12269 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12270 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12271 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12272 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12273 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12274 #else
12275   #define sqlite3FkActions(a,b,c,d)
12276   #define sqlite3FkCheck(a,b,c,d)
12277   #define sqlite3FkDropTable(a,b,c)
12278   #define sqlite3FkOldmask(a,b)      0
12279   #define sqlite3FkRequired(a,b,c,d) 0
12280 #endif
12281 #ifndef SQLITE_OMIT_FOREIGN_KEY
12282 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12283 #else
12284   #define sqlite3FkDelete(a,b)
12285 #endif
12286
12287
12288 /*
12289 ** Available fault injectors.  Should be numbered beginning with 0.
12290 */
12291 #define SQLITE_FAULTINJECTOR_MALLOC     0
12292 #define SQLITE_FAULTINJECTOR_COUNT      1
12293
12294 /*
12295 ** The interface to the code in fault.c used for identifying "benign"
12296 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12297 ** is not defined.
12298 */
12299 #ifndef SQLITE_OMIT_BUILTIN_TEST
12300 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12301 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12302 #else
12303   #define sqlite3BeginBenignMalloc()
12304   #define sqlite3EndBenignMalloc()
12305 #endif
12306
12307 #define IN_INDEX_ROWID           1
12308 #define IN_INDEX_EPH             2
12309 #define IN_INDEX_INDEX           3
12310 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12311
12312 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12313 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12314 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12315 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12316 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
12317 #else
12318   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12319   #define sqlite3JournalExists(p) 1
12320 #endif
12321
12322 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12323 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12324 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12325
12326 #if SQLITE_MAX_EXPR_DEPTH>0
12327 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12328 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12329 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12330 #else
12331   #define sqlite3ExprSetHeight(x,y)
12332   #define sqlite3SelectExprHeight(x) 0
12333   #define sqlite3ExprCheckHeight(x,y)
12334 #endif
12335
12336 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12337 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12338
12339 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12340 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12341 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12342 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12343 #else
12344   #define sqlite3ConnectionBlocked(x,y)
12345   #define sqlite3ConnectionUnlocked(x)
12346   #define sqlite3ConnectionClosed(x)
12347 #endif
12348
12349 #ifdef SQLITE_DEBUG
12350 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12351 #endif
12352
12353 /*
12354 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12355 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12356 ** print I/O tracing messages.
12357 */
12358 #ifdef SQLITE_ENABLE_IOTRACE
12359 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12360 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12361 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12362 #else
12363 # define IOTRACE(A)
12364 # define sqlite3VdbeIOTraceSql(X)
12365 #endif
12366
12367 /*
12368 ** These routines are available for the mem2.c debugging memory allocator
12369 ** only.  They are used to verify that different "types" of memory
12370 ** allocations are properly tracked by the system.
12371 **
12372 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12373 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12374 ** a single bit set.
12375 **
12376 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12377 ** argument match the type set by the previous sqlite3MemdebugSetType().
12378 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12379 **
12380 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12381 ** argument match the type set by the previous sqlite3MemdebugSetType().
12382 **
12383 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12384 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12385 ** it might have been allocated by lookaside, except the allocation was
12386 ** too large or lookaside was already full.  It is important to verify
12387 ** that allocations that might have been satisfied by lookaside are not
12388 ** passed back to non-lookaside free() routines.  Asserts such as the
12389 ** example above are placed on the non-lookaside free() routines to verify
12390 ** this constraint.
12391 **
12392 ** All of this is no-op for a production build.  It only comes into
12393 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12394 */
12395 #ifdef SQLITE_MEMDEBUG
12396 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12397 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12398 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12399 #else
12400 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
12401 # define sqlite3MemdebugHasType(X,Y)  1
12402 # define sqlite3MemdebugNoType(X,Y)   1
12403 #endif
12404 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
12405 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12406 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12407 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12408 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12409
12410 #endif /* _SQLITEINT_H_ */
12411
12412 /************** End of sqliteInt.h *******************************************/
12413 /************** Begin file crypto.c ******************************************/
12414 /*
12415 ** SQLCipher
12416 ** crypto.c developed by Stephen Lombardo (Zetetic LLC)
12417 ** sjlombardo at zetetic dot net
12418 ** http://zetetic.net
12419 **
12420 ** Copyright (c) 2009, ZETETIC LLC
12421 ** All rights reserved.
12422 **
12423 ** Redistribution and use in source and binary forms, with or without
12424 ** modification, are permitted provided that the following conditions are met:
12425 **     * Redistributions of source code must retain the above copyright
12426 **       notice, this list of conditions and the following disclaimer.
12427 **     * Redistributions in binary form must reproduce the above copyright
12428 **       notice, this list of conditions and the following disclaimer in the
12429 **       documentation and/or other materials provided with the distribution.
12430 **     * Neither the name of the ZETETIC LLC nor the
12431 **       names of its contributors may be used to endorse or promote products
12432 **       derived from this software without specific prior written permission.
12433 **
12434 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
12435 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
12436 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12437 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
12438 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
12439 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
12440 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
12441 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12442 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
12443 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12444 **
12445 */
12446 /* BEGIN CRYPTO */
12447 #ifdef SQLITE_HAS_CODEC
12448
12449 /* #include <assert.h> */
12450 /************** Include btreeInt.h in the middle of crypto.c *****************/
12451 /************** Begin file btreeInt.h ****************************************/
12452 /*
12453 ** 2004 April 6
12454 **
12455 ** The author disclaims copyright to this source code.  In place of
12456 ** a legal notice, here is a blessing:
12457 **
12458 **    May you do good and not evil.
12459 **    May you find forgiveness for yourself and forgive others.
12460 **    May you share freely, never taking more than you give.
12461 **
12462 *************************************************************************
12463 ** This file implements a external (disk-based) database using BTrees.
12464 ** For a detailed discussion of BTrees, refer to
12465 **
12466 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
12467 **     "Sorting And Searching", pages 473-480. Addison-Wesley
12468 **     Publishing Company, Reading, Massachusetts.
12469 **
12470 ** The basic idea is that each page of the file contains N database
12471 ** entries and N+1 pointers to subpages.
12472 **
12473 **   ----------------------------------------------------------------
12474 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
12475 **   ----------------------------------------------------------------
12476 **
12477 ** All of the keys on the page that Ptr(0) points to have values less
12478 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
12479 ** values greater than Key(0) and less than Key(1).  All of the keys
12480 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
12481 ** so forth.
12482 **
12483 ** Finding a particular key requires reading O(log(M)) pages from the
12484 ** disk where M is the number of entries in the tree.
12485 **
12486 ** In this implementation, a single file can hold one or more separate
12487 ** BTrees.  Each BTree is identified by the index of its root page.  The
12488 ** key and data for any entry are combined to form the "payload".  A
12489 ** fixed amount of payload can be carried directly on the database
12490 ** page.  If the payload is larger than the preset amount then surplus
12491 ** bytes are stored on overflow pages.  The payload for an entry
12492 ** and the preceding pointer are combined to form a "Cell".  Each
12493 ** page has a small header which contains the Ptr(N) pointer and other
12494 ** information such as the size of key and data.
12495 **
12496 ** FORMAT DETAILS
12497 **
12498 ** The file is divided into pages.  The first page is called page 1,
12499 ** the second is page 2, and so forth.  A page number of zero indicates
12500 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
12501 ** Each page can be either a btree page, a freelist page, an overflow
12502 ** page, or a pointer-map page.
12503 **
12504 ** The first page is always a btree page.  The first 100 bytes of the first
12505 ** page contain a special header (the "file header") that describes the file.
12506 ** The format of the file header is as follows:
12507 **
12508 **   OFFSET   SIZE    DESCRIPTION
12509 **      0      16     Header string: "SQLite format 3\000"
12510 **     16       2     Page size in bytes.
12511 **     18       1     File format write version
12512 **     19       1     File format read version
12513 **     20       1     Bytes of unused space at the end of each page
12514 **     21       1     Max embedded payload fraction
12515 **     22       1     Min embedded payload fraction
12516 **     23       1     Min leaf payload fraction
12517 **     24       4     File change counter
12518 **     28       4     Reserved for future use
12519 **     32       4     First freelist page
12520 **     36       4     Number of freelist pages in the file
12521 **     40      60     15 4-byte meta values passed to higher layers
12522 **
12523 **     40       4     Schema cookie
12524 **     44       4     File format of schema layer
12525 **     48       4     Size of page cache
12526 **     52       4     Largest root-page (auto/incr_vacuum)
12527 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
12528 **     60       4     User version
12529 **     64       4     Incremental vacuum mode
12530 **     68       4     unused
12531 **     72       4     unused
12532 **     76       4     unused
12533 **
12534 ** All of the integer values are big-endian (most significant byte first).
12535 **
12536 ** The file change counter is incremented when the database is changed
12537 ** This counter allows other processes to know when the file has changed
12538 ** and thus when they need to flush their cache.
12539 **
12540 ** The max embedded payload fraction is the amount of the total usable
12541 ** space in a page that can be consumed by a single cell for standard
12542 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
12543 ** is to limit the maximum cell size so that at least 4 cells will fit
12544 ** on one page.  Thus the default max embedded payload fraction is 64.
12545 **
12546 ** If the payload for a cell is larger than the max payload, then extra
12547 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
12548 ** as many bytes as possible are moved into the overflow pages without letting
12549 ** the cell size drop below the min embedded payload fraction.
12550 **
12551 ** The min leaf payload fraction is like the min embedded payload fraction
12552 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
12553 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
12554 ** not specified in the header.
12555 **
12556 ** Each btree pages is divided into three sections:  The header, the
12557 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
12558 ** file header that occurs before the page header.
12559 **
12560 **      |----------------|
12561 **      | file header    |   100 bytes.  Page 1 only.
12562 **      |----------------|
12563 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
12564 **      |----------------|
12565 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
12566 **      | array          |   |  Grows downward
12567 **      |                |   v
12568 **      |----------------|
12569 **      | unallocated    |
12570 **      | space          |
12571 **      |----------------|   ^  Grows upwards
12572 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
12573 **      | area           |   |  and free space fragments.
12574 **      |----------------|
12575 **
12576 ** The page headers looks like this:
12577 **
12578 **   OFFSET   SIZE     DESCRIPTION
12579 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
12580 **      1       2      byte offset to the first freeblock
12581 **      3       2      number of cells on this page
12582 **      5       2      first byte of the cell content area
12583 **      7       1      number of fragmented free bytes
12584 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
12585 **
12586 ** The flags define the format of this btree page.  The leaf flag means that
12587 ** this page has no children.  The zerodata flag means that this page carries
12588 ** only keys and no data.  The intkey flag means that the key is a integer
12589 ** which is stored in the key size entry of the cell header rather than in
12590 ** the payload area.
12591 **
12592 ** The cell pointer array begins on the first byte after the page header.
12593 ** The cell pointer array contains zero or more 2-byte numbers which are
12594 ** offsets from the beginning of the page to the cell content in the cell
12595 ** content area.  The cell pointers occur in sorted order.  The system strives
12596 ** to keep free space after the last cell pointer so that new cells can
12597 ** be easily added without having to defragment the page.
12598 **
12599 ** Cell content is stored at the very end of the page and grows toward the
12600 ** beginning of the page.
12601 **
12602 ** Unused space within the cell content area is collected into a linked list of
12603 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
12604 ** to the first freeblock is given in the header.  Freeblocks occur in
12605 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
12606 ** any group of 3 or fewer unused bytes in the cell content area cannot
12607 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
12608 ** a fragment.  The total number of bytes in all fragments is recorded.
12609 ** in the page header at offset 7.
12610 **
12611 **    SIZE    DESCRIPTION
12612 **      2     Byte offset of the next freeblock
12613 **      2     Bytes in this freeblock
12614 **
12615 ** Cells are of variable length.  Cells are stored in the cell content area at
12616 ** the end of the page.  Pointers to the cells are in the cell pointer array
12617 ** that immediately follows the page header.  Cells is not necessarily
12618 ** contiguous or in order, but cell pointers are contiguous and in order.
12619 **
12620 ** Cell content makes use of variable length integers.  A variable
12621 ** length integer is 1 to 9 bytes where the lower 7 bits of each
12622 ** byte are used.  The integer consists of all bytes that have bit 8 set and
12623 ** the first byte with bit 8 clear.  The most significant byte of the integer
12624 ** appears first.  A variable-length integer may not be more than 9 bytes long.
12625 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
12626 ** allows a 64-bit integer to be encoded in 9 bytes.
12627 **
12628 **    0x00                      becomes  0x00000000
12629 **    0x7f                      becomes  0x0000007f
12630 **    0x81 0x00                 becomes  0x00000080
12631 **    0x82 0x00                 becomes  0x00000100
12632 **    0x80 0x7f                 becomes  0x0000007f
12633 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
12634 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
12635 **
12636 ** Variable length integers are used for rowids and to hold the number of
12637 ** bytes of key and data in a btree cell.
12638 **
12639 ** The content of a cell looks like this:
12640 **
12641 **    SIZE    DESCRIPTION
12642 **      4     Page number of the left child. Omitted if leaf flag is set.
12643 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
12644 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
12645 **      *     Payload
12646 **      4     First page of the overflow chain.  Omitted if no overflow
12647 **
12648 ** Overflow pages form a linked list.  Each page except the last is completely
12649 ** filled with data (pagesize - 4 bytes).  The last page can have as little
12650 ** as 1 byte of data.
12651 **
12652 **    SIZE    DESCRIPTION
12653 **      4     Page number of next overflow page
12654 **      *     Data
12655 **
12656 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
12657 ** file header points to the first in a linked list of trunk page.  Each trunk
12658 ** page points to multiple leaf pages.  The content of a leaf page is
12659 ** unspecified.  A trunk page looks like this:
12660 **
12661 **    SIZE    DESCRIPTION
12662 **      4     Page number of next trunk page
12663 **      4     Number of leaf pointers on this page
12664 **      *     zero or more pages numbers of leaves
12665 */
12666
12667
12668 /* The following value is the maximum cell size assuming a maximum page
12669 ** size give above.
12670 */
12671 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
12672
12673 /* The maximum number of cells on a single page of the database.  This
12674 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
12675 ** plus 2 bytes for the index to the cell in the page header).  Such
12676 ** small cells will be rare, but they are possible.
12677 */
12678 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
12679
12680 /* Forward declarations */
12681 typedef struct MemPage MemPage;
12682 typedef struct BtLock BtLock;
12683
12684 /*
12685 ** This is a magic string that appears at the beginning of every
12686 ** SQLite database in order to identify the file as a real database.
12687 **
12688 ** You can change this value at compile-time by specifying a
12689 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
12690 ** header must be exactly 16 bytes including the zero-terminator so
12691 ** the string itself should be 15 characters long.  If you change
12692 ** the header, then your custom library will not be able to read
12693 ** databases generated by the standard tools and the standard tools
12694 ** will not be able to read databases created by your custom library.
12695 */
12696 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
12697 #  define SQLITE_FILE_HEADER "SQLite format 3"
12698 #endif
12699
12700 /*
12701 ** Page type flags.  An ORed combination of these flags appear as the
12702 ** first byte of on-disk image of every BTree page.
12703 */
12704 #define PTF_INTKEY    0x01
12705 #define PTF_ZERODATA  0x02
12706 #define PTF_LEAFDATA  0x04
12707 #define PTF_LEAF      0x08
12708
12709 /*
12710 ** As each page of the file is loaded into memory, an instance of the following
12711 ** structure is appended and initialized to zero.  This structure stores
12712 ** information about the page that is decoded from the raw file page.
12713 **
12714 ** The pParent field points back to the parent page.  This allows us to
12715 ** walk up the BTree from any leaf to the root.  Care must be taken to
12716 ** unref() the parent page pointer when this page is no longer referenced.
12717 ** The pageDestructor() routine handles that chore.
12718 **
12719 ** Access to all fields of this structure is controlled by the mutex
12720 ** stored in MemPage.pBt->mutex.
12721 */
12722 struct MemPage {
12723   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
12724   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
12725   u8 intKey;           /* True if intkey flag is set */
12726   u8 leaf;             /* True if leaf flag is set */
12727   u8 hasData;          /* True if this page stores data */
12728   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
12729   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
12730   u8 max1bytePayload;  /* min(maxLocal,127) */
12731   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
12732   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
12733   u16 cellOffset;      /* Index in aData of first cell pointer */
12734   u16 nFree;           /* Number of free bytes on the page */
12735   u16 nCell;           /* Number of cells on this page, local and ovfl */
12736   u16 maskPage;        /* Mask for page offset */
12737   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
12738                        ** non-overflow cell */
12739   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
12740   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
12741   u8 *aData;           /* Pointer to disk image of the page data */
12742   u8 *aDataEnd;        /* One byte past the end of usable data */
12743   u8 *aCellIdx;        /* The cell index area */
12744   DbPage *pDbPage;     /* Pager page handle */
12745   Pgno pgno;           /* Page number for this page */
12746 };
12747
12748 /*
12749 ** The in-memory image of a disk page has the auxiliary information appended
12750 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
12751 ** that extra information.
12752 */
12753 #define EXTRA_SIZE sizeof(MemPage)
12754
12755 /*
12756 ** A linked list of the following structures is stored at BtShared.pLock.
12757 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
12758 ** is opened on the table with root page BtShared.iTable. Locks are removed
12759 ** from this list when a transaction is committed or rolled back, or when
12760 ** a btree handle is closed.
12761 */
12762 struct BtLock {
12763   Btree *pBtree;        /* Btree handle holding this lock */
12764   Pgno iTable;          /* Root page of table */
12765   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
12766   BtLock *pNext;        /* Next in BtShared.pLock list */
12767 };
12768
12769 /* Candidate values for BtLock.eLock */
12770 #define READ_LOCK     1
12771 #define WRITE_LOCK    2
12772
12773 /* A Btree handle
12774 **
12775 ** A database connection contains a pointer to an instance of
12776 ** this object for every database file that it has open.  This structure
12777 ** is opaque to the database connection.  The database connection cannot
12778 ** see the internals of this structure and only deals with pointers to
12779 ** this structure.
12780 **
12781 ** For some database files, the same underlying database cache might be
12782 ** shared between multiple connections.  In that case, each connection
12783 ** has it own instance of this object.  But each instance of this object
12784 ** points to the same BtShared object.  The database cache and the
12785 ** schema associated with the database file are all contained within
12786 ** the BtShared object.
12787 **
12788 ** All fields in this structure are accessed under sqlite3.mutex.
12789 ** The pBt pointer itself may not be changed while there exists cursors
12790 ** in the referenced BtShared that point back to this Btree since those
12791 ** cursors have to go through this Btree to find their BtShared and
12792 ** they often do so without holding sqlite3.mutex.
12793 */
12794 struct Btree {
12795   sqlite3 *db;       /* The database connection holding this btree */
12796   BtShared *pBt;     /* Sharable content of this btree */
12797   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
12798   u8 sharable;       /* True if we can share pBt with another db */
12799   u8 locked;         /* True if db currently has pBt locked */
12800   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
12801   int nBackup;       /* Number of backup operations reading this btree */
12802   Btree *pNext;      /* List of other sharable Btrees from the same db */
12803   Btree *pPrev;      /* Back pointer of the same list */
12804 #ifndef SQLITE_OMIT_SHARED_CACHE
12805   BtLock lock;       /* Object used to lock page 1 */
12806 #endif
12807 };
12808
12809 /*
12810 ** Btree.inTrans may take one of the following values.
12811 **
12812 ** If the shared-data extension is enabled, there may be multiple users
12813 ** of the Btree structure. At most one of these may open a write transaction,
12814 ** but any number may have active read transactions.
12815 */
12816 #define TRANS_NONE  0
12817 #define TRANS_READ  1
12818 #define TRANS_WRITE 2
12819
12820 /*
12821 ** An instance of this object represents a single database file.
12822 **
12823 ** A single database file can be in use at the same time by two
12824 ** or more database connections.  When two or more connections are
12825 ** sharing the same database file, each connection has it own
12826 ** private Btree object for the file and each of those Btrees points
12827 ** to this one BtShared object.  BtShared.nRef is the number of
12828 ** connections currently sharing this database file.
12829 **
12830 ** Fields in this structure are accessed under the BtShared.mutex
12831 ** mutex, except for nRef and pNext which are accessed under the
12832 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
12833 ** may not be modified once it is initially set as long as nRef>0.
12834 ** The pSchema field may be set once under BtShared.mutex and
12835 ** thereafter is unchanged as long as nRef>0.
12836 **
12837 ** isPending:
12838 **
12839 **   If a BtShared client fails to obtain a write-lock on a database
12840 **   table (because there exists one or more read-locks on the table),
12841 **   the shared-cache enters 'pending-lock' state and isPending is
12842 **   set to true.
12843 **
12844 **   The shared-cache leaves the 'pending lock' state when either of
12845 **   the following occur:
12846 **
12847 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
12848 **     2) The number of locks held by other connections drops to zero.
12849 **
12850 **   while in the 'pending-lock' state, no connection may start a new
12851 **   transaction.
12852 **
12853 **   This feature is included to help prevent writer-starvation.
12854 */
12855 struct BtShared {
12856   Pager *pPager;        /* The page cache */
12857   sqlite3 *db;          /* Database connection currently using this Btree */
12858   BtCursor *pCursor;    /* A list of all open cursors */
12859   MemPage *pPage1;      /* First page of the database */
12860   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
12861 #ifndef SQLITE_OMIT_AUTOVACUUM
12862   u8 autoVacuum;        /* True if auto-vacuum is enabled */
12863   u8 incrVacuum;        /* True if incr-vacuum is enabled */
12864 #endif
12865   u8 inTransaction;     /* Transaction state */
12866   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
12867   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
12868   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
12869   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
12870   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
12871   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
12872   u32 pageSize;         /* Total number of bytes on a page */
12873   u32 usableSize;       /* Number of usable bytes on each page */
12874   int nTransaction;     /* Number of open transactions (read + write) */
12875   u32 nPage;            /* Number of pages in the database */
12876   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
12877   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
12878   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
12879   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
12880 #ifndef SQLITE_OMIT_SHARED_CACHE
12881   int nRef;             /* Number of references to this structure */
12882   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
12883   BtLock *pLock;        /* List of locks held on this shared-btree struct */
12884   Btree *pWriter;       /* Btree with currently open write transaction */
12885 #endif
12886   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
12887 };
12888
12889 /*
12890 ** Allowed values for BtShared.btsFlags
12891 */
12892 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
12893 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
12894 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
12895 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
12896 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
12897 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
12898 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
12899
12900 /*
12901 ** An instance of the following structure is used to hold information
12902 ** about a cell.  The parseCellPtr() function fills in this structure
12903 ** based on information extract from the raw disk page.
12904 */
12905 typedef struct CellInfo CellInfo;
12906 struct CellInfo {
12907   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
12908   u8 *pCell;     /* Pointer to the start of cell content */
12909   u32 nData;     /* Number of bytes of data */
12910   u32 nPayload;  /* Total amount of payload */
12911   u16 nHeader;   /* Size of the cell content header in bytes */
12912   u16 nLocal;    /* Amount of payload held locally */
12913   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
12914   u16 nSize;     /* Size of the cell content on the main b-tree page */
12915 };
12916
12917 /*
12918 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
12919 ** this will be declared corrupt. This value is calculated based on a
12920 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
12921 ** root-node and 3 for all other internal nodes.
12922 **
12923 ** If a tree that appears to be taller than this is encountered, it is
12924 ** assumed that the database is corrupt.
12925 */
12926 #define BTCURSOR_MAX_DEPTH 20
12927
12928 /*
12929 ** A cursor is a pointer to a particular entry within a particular
12930 ** b-tree within a database file.
12931 **
12932 ** The entry is identified by its MemPage and the index in
12933 ** MemPage.aCell[] of the entry.
12934 **
12935 ** A single database file can be shared by two more database connections,
12936 ** but cursors cannot be shared.  Each cursor is associated with a
12937 ** particular database connection identified BtCursor.pBtree.db.
12938 **
12939 ** Fields in this structure are accessed under the BtShared.mutex
12940 ** found at self->pBt->mutex.
12941 */
12942 struct BtCursor {
12943   Btree *pBtree;            /* The Btree to which this cursor belongs */
12944   BtShared *pBt;            /* The BtShared this cursor points to */
12945   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
12946   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
12947 #ifndef SQLITE_OMIT_INCRBLOB
12948   Pgno *aOverflow;          /* Cache of overflow page locations */
12949 #endif
12950   Pgno pgnoRoot;            /* The root page of this tree */
12951   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
12952   CellInfo info;            /* A parse of the cell we are pointing at */
12953   i64 nKey;        /* Size of pKey, or last integer key */
12954   void *pKey;      /* Saved key that was cursor's last known position */
12955   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
12956   u8 wrFlag;                /* True if writable */
12957   u8 atLast;                /* Cursor pointing to the last entry */
12958   u8 validNKey;             /* True if info.nKey is valid */
12959   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
12960 #ifndef SQLITE_OMIT_INCRBLOB
12961   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
12962 #endif
12963   u8 hints;                             /* As configured by CursorSetHints() */
12964   i16 iPage;                            /* Index of current page in apPage */
12965   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
12966   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
12967 };
12968
12969 /*
12970 ** Potential values for BtCursor.eState.
12971 **
12972 ** CURSOR_VALID:
12973 **   Cursor points to a valid entry. getPayload() etc. may be called.
12974 **
12975 ** CURSOR_INVALID:
12976 **   Cursor does not point to a valid entry. This can happen (for example)
12977 **   because the table is empty or because BtreeCursorFirst() has not been
12978 **   called.
12979 **
12980 ** CURSOR_REQUIRESEEK:
12981 **   The table that this cursor was opened on still exists, but has been
12982 **   modified since the cursor was last used. The cursor position is saved
12983 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
12984 **   this state, restoreCursorPosition() can be called to attempt to
12985 **   seek the cursor to the saved position.
12986 **
12987 ** CURSOR_FAULT:
12988 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
12989 **   on a different connection that shares the BtShared cache with this
12990 **   cursor.  The error has left the cache in an inconsistent state.
12991 **   Do nothing else with this cursor.  Any attempt to use the cursor
12992 **   should return the error code stored in BtCursor.skip
12993 */
12994 #define CURSOR_INVALID           0
12995 #define CURSOR_VALID             1
12996 #define CURSOR_REQUIRESEEK       2
12997 #define CURSOR_FAULT             3
12998
12999 /*
13000 ** The database page the PENDING_BYTE occupies. This page is never used.
13001 */
13002 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
13003
13004 /*
13005 ** These macros define the location of the pointer-map entry for a
13006 ** database page. The first argument to each is the number of usable
13007 ** bytes on each page of the database (often 1024). The second is the
13008 ** page number to look up in the pointer map.
13009 **
13010 ** PTRMAP_PAGENO returns the database page number of the pointer-map
13011 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
13012 ** the offset of the requested map entry.
13013 **
13014 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
13015 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
13016 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
13017 ** this test.
13018 */
13019 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
13020 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
13021 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
13022
13023 /*
13024 ** The pointer map is a lookup table that identifies the parent page for
13025 ** each child page in the database file.  The parent page is the page that
13026 ** contains a pointer to the child.  Every page in the database contains
13027 ** 0 or 1 parent pages.  (In this context 'database page' refers
13028 ** to any page that is not part of the pointer map itself.)  Each pointer map
13029 ** entry consists of a single byte 'type' and a 4 byte parent page number.
13030 ** The PTRMAP_XXX identifiers below are the valid types.
13031 **
13032 ** The purpose of the pointer map is to facility moving pages from one
13033 ** position in the file to another as part of autovacuum.  When a page
13034 ** is moved, the pointer in its parent must be updated to point to the
13035 ** new location.  The pointer map is used to locate the parent page quickly.
13036 **
13037 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
13038 **                  used in this case.
13039 **
13040 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
13041 **                  is not used in this case.
13042 **
13043 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
13044 **                   overflow pages. The page number identifies the page that
13045 **                   contains the cell with a pointer to this overflow page.
13046 **
13047 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
13048 **                   overflow pages. The page-number identifies the previous
13049 **                   page in the overflow page list.
13050 **
13051 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
13052 **               identifies the parent page in the btree.
13053 */
13054 #define PTRMAP_ROOTPAGE 1
13055 #define PTRMAP_FREEPAGE 2
13056 #define PTRMAP_OVERFLOW1 3
13057 #define PTRMAP_OVERFLOW2 4
13058 #define PTRMAP_BTREE 5
13059
13060 /* A bunch of assert() statements to check the transaction state variables
13061 ** of handle p (type Btree*) are internally consistent.
13062 */
13063 #define btreeIntegrity(p) \
13064   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
13065   assert( p->pBt->inTransaction>=p->inTrans );
13066
13067
13068 /*
13069 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
13070 ** if the database supports auto-vacuum or not. Because it is used
13071 ** within an expression that is an argument to another macro
13072 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
13073 ** So, this macro is defined instead.
13074 */
13075 #ifndef SQLITE_OMIT_AUTOVACUUM
13076 #define ISAUTOVACUUM (pBt->autoVacuum)
13077 #else
13078 #define ISAUTOVACUUM 0
13079 #endif
13080
13081
13082 /*
13083 ** This structure is passed around through all the sanity checking routines
13084 ** in order to keep track of some global state information.
13085 **
13086 ** The aRef[] array is allocated so that there is 1 bit for each page in
13087 ** the database. As the integrity-check proceeds, for each page used in
13088 ** the database the corresponding bit is set. This allows integrity-check to
13089 ** detect pages that are used twice and orphaned pages (both of which
13090 ** indicate corruption).
13091 */
13092 typedef struct IntegrityCk IntegrityCk;
13093 struct IntegrityCk {
13094   BtShared *pBt;    /* The tree being checked out */
13095   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
13096   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
13097   Pgno nPage;       /* Number of pages in the database */
13098   int mxErr;        /* Stop accumulating errors when this reaches zero */
13099   int nErr;         /* Number of messages written to zErrMsg so far */
13100   int mallocFailed; /* A memory allocation error has occurred */
13101   StrAccum errMsg;  /* Accumulate the error message text here */
13102 };
13103
13104 /*
13105 ** Routines to read or write a two- and four-byte big-endian integer values.
13106 */
13107 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
13108 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
13109 #define get4byte sqlite3Get4byte
13110 #define put4byte sqlite3Put4byte
13111
13112 /************** End of btreeInt.h ********************************************/
13113 /************** Continuing where we left off in crypto.c *********************/
13114 /************** Include crypto.h in the middle of crypto.c *******************/
13115 /************** Begin file crypto.h ******************************************/
13116 /*
13117 ** SQLCipher
13118 ** crypto.h developed by Stephen Lombardo (Zetetic LLC)
13119 ** sjlombardo at zetetic dot net
13120 ** http://zetetic.net
13121 **
13122 ** Copyright (c) 2008, ZETETIC LLC
13123 ** All rights reserved.
13124 **
13125 ** Redistribution and use in source and binary forms, with or without
13126 ** modification, are permitted provided that the following conditions are met:
13127 **     * Redistributions of source code must retain the above copyright
13128 **       notice, this list of conditions and the following disclaimer.
13129 **     * Redistributions in binary form must reproduce the above copyright
13130 **       notice, this list of conditions and the following disclaimer in the
13131 **       documentation and/or other materials provided with the distribution.
13132 **     * Neither the name of the ZETETIC LLC nor the
13133 **       names of its contributors may be used to endorse or promote products
13134 **       derived from this software without specific prior written permission.
13135 **
13136 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
13137 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
13138 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13139 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
13140 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
13141 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
13142 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
13143 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13144 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
13145 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13146 **
13147 */
13148 /* BEGIN CRYPTO */
13149 #ifdef SQLITE_HAS_CODEC
13150 #ifndef CRYPTO_H
13151 #define CRYPTO_H
13152
13153 #define FILE_HEADER_SZ 16
13154
13155 #ifndef CIPHER_VERSION
13156 #define CIPHER_VERSION "2.1.1"
13157 #endif
13158
13159 #ifndef CIPHER
13160 #define CIPHER "aes-256-cbc"
13161 #endif
13162
13163 #define CIPHER_DECRYPT 0
13164 #define CIPHER_ENCRYPT 1
13165
13166 #define CIPHER_READ_CTX 0
13167 #define CIPHER_WRITE_CTX 1
13168 #define CIPHER_READWRITE_CTX 2
13169
13170 #ifndef PBKDF2_ITER
13171 #define PBKDF2_ITER 4000
13172 #endif
13173
13174 /* possible flags for cipher_ctx->flags */
13175 #define CIPHER_FLAG_HMAC          0x01
13176 #define CIPHER_FLAG_LE_PGNO       0x02
13177 #define CIPHER_FLAG_BE_PGNO       0x04
13178
13179 #ifndef DEFAULT_CIPHER_FLAGS
13180 #define DEFAULT_CIPHER_FLAGS CIPHER_FLAG_HMAC | CIPHER_FLAG_LE_PGNO
13181 #endif
13182
13183
13184 /* by default, sqlcipher will use a reduced number of iterations to generate
13185    the HMAC key / or transform a raw cipher key
13186    */
13187 #ifndef FAST_PBKDF2_ITER
13188 #define FAST_PBKDF2_ITER 2
13189 #endif
13190
13191 /* this if a fixed random array that will be xor'd with the database salt to ensure that the
13192    salt passed to the HMAC key derivation function is not the same as that used to derive
13193    the encryption key. This can be overridden at compile time but it will make the resulting
13194    binary incompatible with the default builds when using HMAC. A future version of SQLcipher
13195    will likely allow this to be defined at runtime via pragma */
13196 #ifndef HMAC_SALT_MASK
13197 #define HMAC_SALT_MASK 0x3a
13198 #endif
13199
13200 #ifdef CODEC_DEBUG
13201 #define CODEC_TRACE(X)  {printf X;fflush(stdout);}
13202 #else
13203 #define CODEC_TRACE(X)
13204 #endif
13205
13206 #ifdef CODEC_DEBUG_PAGEDATA
13207 #define CODEC_HEXDUMP(DESC,BUFFER,LEN)  \
13208   { \
13209     int __pctr; \
13210     printf(DESC); \
13211     for(__pctr=0; __pctr < LEN; __pctr++) { \
13212       if(__pctr % 16 == 0) printf("\n%05x: ",__pctr); \
13213       printf("%02x ",((unsigned char*) BUFFER)[__pctr]); \
13214     } \
13215     printf("\n"); \
13216     fflush(stdout); \
13217   }
13218 #else
13219 #define CODEC_HEXDUMP(DESC,BUFFER,LEN)
13220 #endif
13221
13222 /* extensions defined in pager.c */
13223 SQLITE_PRIVATE void sqlite3pager_get_codec(Pager *pPager, void **ctx);
13224 SQLITE_PRIVATE int sqlite3pager_is_mj_pgno(Pager *pPager, Pgno pgno);
13225 SQLITE_PRIVATE sqlite3_file *sqlite3Pager_get_fd(Pager *pPager);
13226 SQLITE_PRIVATE void sqlite3pager_sqlite3PagerSetCodec(
13227   Pager *pPager,
13228   void *(*xCodec)(void*,void*,Pgno,int),
13229   void (*xCodecSizeChng)(void*,int,int),
13230   void (*xCodecFree)(void*),
13231   void *pCodec
13232 );
13233 SQLITE_PRIVATE void sqlite3pager_sqlite3PagerSetError(Pager *pPager, int error);
13234 /* end extensions defined in pager.c */
13235
13236 /*
13237 **  Simple shared routines for converting hex char strings to binary data
13238  */
13239 static int cipher_hex2int(char c) {
13240   return (c>='0' && c<='9') ? (c)-'0' :
13241          (c>='A' && c<='F') ? (c)-'A'+10 :
13242          (c>='a' && c<='f') ? (c)-'a'+10 : 0;
13243 }
13244
13245 static void cipher_hex2bin(const char *hex, int sz, unsigned char *out){
13246   int i;
13247   for(i = 0; i < sz; i += 2){
13248     out[i/2] = (cipher_hex2int(hex[i])<<4) | cipher_hex2int(hex[i+1]);
13249   }
13250 }
13251
13252 /* extensions defined in crypto_impl.c */
13253
13254 typedef struct codec_ctx codec_ctx;
13255
13256 /* utility functions */
13257 void* sqlcipher_memset(void *v, unsigned char value, int len);
13258 int sqlcipher_ismemset(const void *v, unsigned char value, int len);
13259 int sqlcipher_memcmp(const void *v0, const void *v1, int len);
13260 int sqlcipher_pseudorandom(void *, int);
13261 void sqlcipher_free(void *, int);
13262
13263 /* activation and initialization */
13264 void sqlcipher_activate();
13265 void sqlcipher_deactivate();
13266 int sqlcipher_codec_ctx_init(codec_ctx **, Db *, Pager *, sqlite3_file *, const void *, int);
13267 void sqlcipher_codec_ctx_free(codec_ctx **);
13268 int sqlcipher_codec_key_derive(codec_ctx *);
13269 int sqlcipher_codec_key_copy(codec_ctx *, int);
13270
13271 /* page cipher implementation */
13272 int sqlcipher_page_cipher(codec_ctx *, int, Pgno, int, int, unsigned char *, unsigned char *);
13273
13274 /* context setters & getters */
13275 void sqlcipher_codec_ctx_set_error(codec_ctx *, int);
13276
13277 int sqlcipher_codec_ctx_set_pass(codec_ctx *, const void *, int, int);
13278 void sqlcipher_codec_get_pass(codec_ctx *, void **zKey, int *nKey);
13279
13280 int sqlcipher_codec_ctx_set_pagesize(codec_ctx *, int);
13281 int sqlcipher_codec_ctx_get_pagesize(codec_ctx *);
13282 int sqlcipher_codec_ctx_get_reservesize(codec_ctx *);
13283
13284 int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *, int, int);
13285 int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx, int);
13286
13287 void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx);
13288
13289 int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *, int, int);
13290 int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *, int);
13291
13292 int sqlcipher_codec_ctx_set_cipher(codec_ctx *, const char *, int);
13293 const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx, int for_ctx);
13294
13295 void* sqlcipher_codec_ctx_get_data(codec_ctx *);
13296
13297 void sqlcipher_exportFunc(sqlite3_context *, int, sqlite3_value **);
13298
13299 void sqlcipher_set_default_use_hmac(int use);
13300 int sqlcipher_get_default_use_hmac();
13301
13302 void sqlcipher_set_hmac_salt_mask(unsigned char mask);
13303 unsigned char sqlcipher_get_hmac_salt_mask();
13304
13305 int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use);
13306 int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx, int for_ctx);
13307
13308 int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag);
13309 int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag);
13310 int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag, int for_ctx);
13311
13312 /* end extensions defined in crypto_impl.c */
13313
13314 #endif
13315 #endif
13316 /* END CRYPTO */
13317
13318 /************** End of crypto.h **********************************************/
13319 /************** Continuing where we left off in crypto.c *********************/
13320
13321 const char* codec_get_cipher_version() {
13322   return CIPHER_VERSION;
13323 }
13324
13325 /* Generate code to return a string value */
13326 void codec_vdbe_return_static_string(Parse *pParse, const char *zLabel, const char *value){
13327   Vdbe *v = sqlite3GetVdbe(pParse);
13328   sqlite3VdbeSetNumCols(v, 1);
13329   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
13330   sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, value, 0);
13331   sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
13332 }
13333
13334 static int codec_set_btree_to_codec_pagesize(sqlite3 *db, Db *pDb, codec_ctx *ctx) {
13335   int rc, page_sz, reserve_sz;
13336
13337   page_sz = sqlcipher_codec_ctx_get_pagesize(ctx);
13338   reserve_sz = sqlcipher_codec_ctx_get_reservesize(ctx);
13339
13340   sqlite3_mutex_enter(db->mutex);
13341   db->nextPagesize = page_sz;
13342
13343   /* before forcing the page size we need to unset the BTS_PAGESIZE_FIXED flag, else
13344      sqliteBtreeSetPageSize will block the change  */
13345   pDb->pBt->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
13346   CODEC_TRACE(("codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize() size=%d reserve=%d\n", page_sz, reserve_sz));
13347   rc = sqlite3BtreeSetPageSize(pDb->pBt, page_sz, reserve_sz, 0);
13348   sqlite3_mutex_leave(db->mutex);
13349   return rc;
13350 }
13351
13352 int codec_set_pass_key(sqlite3* db, int nDb, const void *zKey, int nKey, int for_ctx) {
13353   struct Db *pDb = &db->aDb[nDb];
13354   CODEC_TRACE(("codec_set_pass_key: entered db=%p nDb=%d zKey=%s nKey=%d for_ctx=%d\n", db, nDb, (char *)zKey, nKey, for_ctx));
13355   if(pDb->pBt) {
13356     codec_ctx *ctx;
13357     sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13358     if(ctx) return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx);
13359   }
13360   return SQLITE_ERROR;
13361 }
13362
13363 int codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) {
13364   struct Db *pDb = &db->aDb[iDb];
13365   codec_ctx *ctx = NULL;
13366   int rc;
13367
13368   if(pDb->pBt) {
13369     sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13370   }
13371
13372   CODEC_TRACE(("codec_pragma: entered db=%p iDb=%d pParse=%p zLeft=%s zRight=%s ctx=%p\n", db, iDb, pParse, zLeft, zRight, ctx));
13373
13374   if( sqlite3StrICmp(zLeft, "cipher_version")==0 && !zRight ){
13375     codec_vdbe_return_static_string(pParse, "cipher_version", codec_get_cipher_version());
13376   }else
13377   if( sqlite3StrICmp(zLeft, "cipher")==0 ){
13378     if(ctx) {
13379       if( zRight ) {
13380         sqlcipher_codec_ctx_set_cipher(ctx, zRight, 2); // change cipher for both
13381       }else {
13382         codec_vdbe_return_static_string(pParse, "cipher",
13383           sqlcipher_codec_ctx_get_cipher(ctx, 2));
13384       }
13385     }
13386   }else
13387   if( sqlite3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){
13388     if(ctx) sqlcipher_codec_ctx_set_cipher(ctx, zRight, 1); // change write cipher only
13389   }else
13390   if( sqlite3StrICmp(zLeft, "kdf_iter")==0 ){
13391     if(ctx) {
13392       if( zRight ) {
13393         sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration
13394       } else {
13395         char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_kdf_iter(ctx, 2));
13396         codec_vdbe_return_static_string(pParse, "kdf_iter", kdf_iter);
13397         sqlite3_free(kdf_iter);
13398       }
13399     }
13400   }else
13401   if( sqlite3StrICmp(zLeft, "fast_kdf_iter")==0){
13402     if(ctx) {
13403       if( zRight ) {
13404         sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight), 2); // change of RW PBKDF2 iteration
13405       } else {
13406         char *fast_kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_fast_kdf_iter(ctx, 2));
13407         codec_vdbe_return_static_string(pParse, "fast_kdf_iter", fast_kdf_iter);
13408         sqlite3_free(fast_kdf_iter);
13409       }
13410     }
13411   }else
13412   if( sqlite3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){
13413     if(ctx) sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight), 1); // write iterations only
13414   }else
13415   if( sqlite3StrICmp(zLeft,"cipher_page_size")==0 ){
13416     if(ctx) {
13417       if( zRight ) {
13418         int size = atoi(zRight);
13419         rc = sqlcipher_codec_ctx_set_pagesize(ctx, size);
13420         if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
13421         rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
13422         if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
13423       } else {
13424         char * page_size = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_pagesize(ctx));
13425         codec_vdbe_return_static_string(pParse, "cipher_page_size", page_size);
13426         sqlite3_free(page_size);
13427       }
13428     }
13429   }else
13430   if( sqlite3StrICmp(zLeft,"cipher_default_use_hmac")==0 ){
13431     if( zRight ) {
13432       sqlcipher_set_default_use_hmac(sqlite3GetBoolean(zRight,1));
13433     } else {
13434       char *default_use_hmac = sqlite3_mprintf("%d", sqlcipher_get_default_use_hmac());
13435       codec_vdbe_return_static_string(pParse, "cipher_default_use_hmac", default_use_hmac);
13436       sqlite3_free(default_use_hmac);
13437     }
13438   }else
13439   if( sqlite3StrICmp(zLeft,"cipher_use_hmac")==0 ){
13440     if(ctx) {
13441       if( zRight ) {
13442         rc = sqlcipher_codec_ctx_set_use_hmac(ctx, sqlite3GetBoolean(zRight,1));
13443         if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
13444         /* since the use of hmac has changed, the page size may also change */
13445         rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
13446         if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
13447       } else {
13448         char *hmac_flag = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_use_hmac(ctx, 2));
13449         codec_vdbe_return_static_string(pParse, "cipher_use_hmac", hmac_flag);
13450         sqlite3_free(hmac_flag);
13451       }
13452     }
13453   }else
13454   if( sqlite3StrICmp(zLeft,"cipher_hmac_pgno")==0 ){
13455     if(ctx) {
13456       if(zRight) {
13457         // clear both pgno endian flags
13458         if(sqlite3StrICmp(zRight, "le") == 0) {
13459           sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO);
13460           sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_LE_PGNO);
13461         } else if(sqlite3StrICmp(zRight, "be") == 0) {
13462           sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO);
13463           sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_BE_PGNO);
13464         } else if(sqlite3StrICmp(zRight, "native") == 0) {
13465           sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO);
13466           sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO);
13467         }
13468       } else {
13469         if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_LE_PGNO, 2)) {
13470           codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "le");
13471         } else if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_BE_PGNO, 2)) {
13472           codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "be");
13473         } else {
13474           codec_vdbe_return_static_string(pParse, "cipher_hmac_pgno", "native");
13475         }
13476       }
13477     }
13478   }else
13479   if( sqlite3StrICmp(zLeft,"cipher_hmac_salt_mask")==0 ){
13480     if(ctx) {
13481       if(zRight) {
13482         if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == 5) {
13483           unsigned char mask = 0;
13484           const char *hex = zRight+2;
13485           cipher_hex2bin(hex,2,&mask);
13486           sqlcipher_set_hmac_salt_mask(mask);
13487         }
13488       } else {
13489           char *hmac_salt_mask = sqlite3_mprintf("%02x", sqlcipher_get_hmac_salt_mask());
13490           codec_vdbe_return_static_string(pParse, "cipher_hmac_salt_mask", hmac_salt_mask);
13491           sqlite3_free(hmac_salt_mask);
13492       }
13493     }
13494   }else {
13495     return 0;
13496   }
13497   return 1;
13498 }
13499
13500 /*
13501  * sqlite3Codec can be called in multiple modes.
13502  * encrypt mode - expected to return a pointer to the
13503  *   encrypted data without altering pData.
13504  * decrypt mode - expected to return a pointer to pData, with
13505  *   the data decrypted in the input buffer
13506  */
13507 void* sqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) {
13508   codec_ctx *ctx = (codec_ctx *) iCtx;
13509   int offset = 0, rc = 0;
13510   int page_sz = sqlcipher_codec_ctx_get_pagesize(ctx);
13511   unsigned char *pData = (unsigned char *) data;
13512   void *buffer = sqlcipher_codec_ctx_get_data(ctx);
13513   void *kdf_salt = sqlcipher_codec_ctx_get_kdf_salt(ctx);
13514   CODEC_TRACE(("sqlite3Codec: entered pgno=%d, mode=%d, page_sz=%d\n", pgno, mode, page_sz));
13515
13516   /* call to derive keys if not present yet */
13517   if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) {
13518    sqlcipher_codec_ctx_set_error(ctx, rc);
13519    return NULL;
13520   }
13521
13522   if(pgno == 1) offset = FILE_HEADER_SZ; /* adjust starting pointers in data page for header offset on first page*/
13523
13524   CODEC_TRACE(("sqlite3Codec: switch mode=%d offset=%d\n",  mode, offset));
13525   switch(mode) {
13526     case 0: /* decrypt */
13527     case 2:
13528     case 3:
13529       if(pgno == 1) memcpy(buffer, SQLITE_FILE_HEADER, FILE_HEADER_SZ); /* copy file header to the first 16 bytes of the page */
13530       rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
13531       if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
13532       memcpy(pData, buffer, page_sz); /* copy buffer data back to pData and return */
13533       return pData;
13534       break;
13535     case 6: /* encrypt */
13536       if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */
13537       rc = sqlcipher_page_cipher(ctx, CIPHER_WRITE_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
13538       if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
13539       return buffer; /* return persistent buffer data, pData remains intact */
13540       break;
13541     case 7:
13542       if(pgno == 1) memcpy(buffer, kdf_salt, FILE_HEADER_SZ); /* copy salt to output buffer */
13543       rc = sqlcipher_page_cipher(ctx, CIPHER_READ_CTX, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
13544       if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
13545       return buffer; /* return persistent buffer data, pData remains intact */
13546       break;
13547     default:
13548       return pData;
13549       break;
13550   }
13551 }
13552
13553 SQLITE_PRIVATE void sqlite3FreeCodecArg(void *pCodecArg) {
13554   codec_ctx *ctx = (codec_ctx *) pCodecArg;
13555   if(pCodecArg == NULL) return;
13556   sqlcipher_codec_ctx_free(&ctx); // wipe and free allocated memory for the context
13557   sqlcipher_deactivate(); /* cleanup related structures, OpenSSL etc, when codec is detatched */
13558 }
13559
13560 SQLITE_PRIVATE int sqlite3CodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) {
13561   struct Db *pDb = &db->aDb[nDb];
13562
13563   CODEC_TRACE(("sqlite3CodecAttach: entered nDb=%d zKey=%s, nKey=%d\n", nDb, (char *)zKey, nKey));
13564
13565
13566   if(nKey && zKey && pDb->pBt) {
13567     int rc;
13568     Pager *pPager = pDb->pBt->pBt->pPager;
13569     sqlite3_file *fd = sqlite3Pager_get_fd(pPager);
13570     codec_ctx *ctx;
13571
13572     sqlcipher_activate(); /* perform internal initialization for sqlcipher */
13573
13574     /* point the internal codec argument against the contet to be prepared */
13575     rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, fd, zKey, nKey);
13576
13577     if(rc != SQLITE_OK) return rc; /* initialization failed, do not attach potentially corrupted context */
13578
13579     sqlite3_mutex_enter(db->mutex);
13580
13581     sqlite3pager_sqlite3PagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL, sqlite3FreeCodecArg, (void *) ctx);
13582
13583     codec_set_btree_to_codec_pagesize(db, pDb, ctx);
13584
13585     /* force secure delete. This has the benefit of wiping internal data when deleted
13586        and also ensures that all pages are written to disk (i.e. not skipped by
13587        sqlite3PagerDontWrite optimizations) */
13588     sqlite3BtreeSecureDelete(pDb->pBt, 1);
13589
13590     /* if fd is null, then this is an in-memory database and
13591        we dont' want to overwrite the AutoVacuum settings
13592        if not null, then set to the default */
13593     if(fd != NULL) {
13594       sqlite3BtreeSetAutoVacuum(pDb->pBt, SQLITE_DEFAULT_AUTOVACUUM);
13595     }
13596     sqlite3_mutex_leave(db->mutex);
13597   }
13598   return SQLITE_OK;
13599 }
13600
13601 SQLITE_API void sqlite3_activate_see(const char* in) {
13602   /* do nothing, security enhancements are always active */
13603 }
13604
13605 SQLITE_API int sqlite3_key(sqlite3 *db, const void *pKey, int nKey) {
13606   CODEC_TRACE(("sqlite3_key: entered db=%p pKey=%s nKey=%d\n", db, (char *)pKey, nKey));
13607   /* attach key if db and pKey are not null and nKey is > 0 */
13608   if(db && pKey && nKey) {
13609     return sqlite3CodecAttach(db, 0, pKey, nKey); // operate only on the main db
13610   }
13611   return SQLITE_ERROR;
13612 }
13613
13614 /* sqlite3_rekey
13615 ** Given a database, this will reencrypt the database using a new key.
13616 ** There is only one possible modes of operation - to encrypt a database
13617 ** that is already encrpyted. If the database is not already encrypted
13618 ** this should do nothing
13619 ** The proposed logic for this function follows:
13620 ** 1. Determine if the database is already encryptped
13621 ** 2. If there is NOT already a key present do nothing
13622 ** 3. If there is a key present, re-encrypt the database with the new key
13623 */
13624 SQLITE_API int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) {
13625   CODEC_TRACE(("sqlite3_rekey: entered db=%p pKey=%s, nKey=%d\n", db, (char *)pKey, nKey));
13626   if(db && pKey && nKey) {
13627     struct Db *pDb = &db->aDb[0];
13628     CODEC_TRACE(("sqlite3_rekey: database pDb=%p\n", pDb));
13629     if(pDb->pBt) {
13630       codec_ctx *ctx;
13631       int rc, page_count;
13632       Pgno pgno;
13633       PgHdr *page;
13634       Pager *pPager = pDb->pBt->pBt->pPager;
13635
13636       sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13637
13638       if(ctx == NULL) {
13639         /* there was no codec attached to this database, so this should do nothing! */
13640         CODEC_TRACE(("sqlite3_rekey: no codec attached to db, exiting\n"));
13641         return SQLITE_OK;
13642       }
13643
13644       sqlite3_mutex_enter(db->mutex);
13645
13646       codec_set_pass_key(db, 0, pKey, nKey, CIPHER_WRITE_CTX);
13647
13648       /* do stuff here to rewrite the database
13649       ** 1. Create a transaction on the database
13650       ** 2. Iterate through each page, reading it and then writing it.
13651       ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
13652       **    note: don't deallocate rekey since it may be used in a subsequent iteration
13653       */
13654       rc = sqlite3BtreeBeginTrans(pDb->pBt, 1); /* begin write transaction */
13655       sqlite3PagerPagecount(pPager, &page_count);
13656       for(pgno = 1; rc == SQLITE_OK && pgno <= page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
13657         if(!sqlite3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
13658           rc = sqlite3PagerGet(pPager, pgno, &page);
13659           if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */
13660             rc = sqlite3PagerWrite(page);
13661             if(rc == SQLITE_OK) {
13662               sqlite3PagerUnref(page);
13663             } else {
13664              CODEC_TRACE(("sqlite3_rekey: error %d occurred writing page %d\n", rc, pgno));
13665             }
13666           } else {
13667              CODEC_TRACE(("sqlite3_rekey: error %d occurred getting page %d\n", rc, pgno));
13668           }
13669         }
13670       }
13671
13672       /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
13673       if(rc == SQLITE_OK) {
13674         CODEC_TRACE(("sqlite3_rekey: committing\n"));
13675         rc = sqlite3BtreeCommit(pDb->pBt);
13676         sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX);
13677       } else {
13678         CODEC_TRACE(("sqlite3_rekey: rollback\n"));
13679         sqlite3BtreeRollback(pDb->pBt, SQLITE_ABORT_ROLLBACK);
13680       }
13681
13682       sqlite3_mutex_leave(db->mutex);
13683     }
13684     return SQLITE_OK;
13685   }
13686   return SQLITE_ERROR;
13687 }
13688
13689 SQLITE_PRIVATE void sqlite3CodecGetKey(sqlite3* db, int nDb, void **zKey, int *nKey) {
13690   struct Db *pDb = &db->aDb[nDb];
13691   CODEC_TRACE(("sqlite3CodecGetKey: entered db=%p, nDb=%d\n", db, nDb));
13692
13693   if( pDb->pBt ) {
13694     codec_ctx *ctx;
13695     sqlite3pager_get_codec(pDb->pBt->pBt->pPager, (void **) &ctx);
13696
13697     if(ctx) { /* if the codec has an attached codec_context user the raw key data */
13698       sqlcipher_codec_get_pass(ctx, zKey, nKey);
13699     } else {
13700       *zKey = NULL;
13701       *nKey = 0;
13702     }
13703   }
13704 }
13705
13706
13707 /* END CRYPTO */
13708 #endif
13709
13710 /************** End of crypto.c **********************************************/
13711 /************** Begin file crypto_impl.c *************************************/
13712 /*
13713 ** SQLCipher
13714 ** crypto_impl.c developed by Stephen Lombardo (Zetetic LLC)
13715 ** sjlombardo at zetetic dot net
13716 ** http://zetetic.net
13717 **
13718 ** Copyright (c) 2011, ZETETIC LLC
13719 ** All rights reserved.
13720 **
13721 ** Redistribution and use in source and binary forms, with or without
13722 ** modification, are permitted provided that the following conditions are met:
13723 **     * Redistributions of source code must retain the above copyright
13724 **       notice, this list of conditions and the following disclaimer.
13725 **     * Redistributions in binary form must reproduce the above copyright
13726 **       notice, this list of conditions and the following disclaimer in the
13727 **       documentation and/or other materials provided with the distribution.
13728 **     * Neither the name of the ZETETIC LLC nor the
13729 **       names of its contributors may be used to endorse or promote products
13730 **       derived from this software without specific prior written permission.
13731 **
13732 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
13733 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
13734 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
13735 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
13736 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
13737 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
13738 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
13739 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13740 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
13741 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13742 **
13743 */
13744 /* BEGIN CRYPTO */
13745 #ifdef SQLITE_HAS_CODEC
13746
13747 #include <openssl/rand.h>
13748 #include <openssl/evp.h>
13749 #include <openssl/hmac.h>
13750 #ifndef OMIT_MEMLOCK
13751 #if defined(__unix__) || defined(__APPLE__)
13752 #include <sys/mman.h>
13753 #elif defined(_WIN32)
13754 /* # include <windows.h> */
13755 #endif
13756 #endif
13757
13758 /* the default implementation of SQLCipher uses a cipher_ctx
13759    to keep track of read / write state separately. The following
13760    struct and associated functions are defined here */
13761 typedef struct {
13762   int derive_key;
13763   EVP_CIPHER *evp_cipher;
13764   EVP_CIPHER_CTX ectx;
13765   HMAC_CTX hctx;
13766   int kdf_iter;
13767   int fast_kdf_iter;
13768   int key_sz;
13769   int iv_sz;
13770   int block_sz;
13771   int pass_sz;
13772   int reserve_sz;
13773   int hmac_sz;
13774   unsigned int flags;
13775   unsigned char *key;
13776   unsigned char *hmac_key;
13777   char *pass;
13778 } cipher_ctx;
13779
13780 void sqlcipher_cipher_ctx_free(cipher_ctx **);
13781 int sqlcipher_cipher_ctx_cmp(cipher_ctx *, cipher_ctx *);
13782 int sqlcipher_cipher_ctx_copy(cipher_ctx *, cipher_ctx *);
13783 int sqlcipher_cipher_ctx_init(cipher_ctx **);
13784 int sqlcipher_cipher_ctx_set_pass(cipher_ctx *, const void *, int);
13785 int sqlcipher_cipher_ctx_key_derive(codec_ctx *, cipher_ctx *);
13786
13787 /* prototype for pager HMAC function */
13788 int sqlcipher_page_hmac(cipher_ctx *, Pgno, unsigned char *, int, unsigned char *);
13789
13790 static unsigned int default_flags = DEFAULT_CIPHER_FLAGS;
13791 static unsigned char hmac_salt_mask = HMAC_SALT_MASK;
13792
13793 static unsigned int openssl_external_init = 0;
13794 static unsigned int openssl_init_count = 0;
13795
13796 struct codec_ctx {
13797   int kdf_salt_sz;
13798   int page_sz;
13799   unsigned char *kdf_salt;
13800   unsigned char *hmac_kdf_salt;
13801   unsigned char *buffer;
13802   Btree *pBt;
13803   cipher_ctx *read_ctx;
13804   cipher_ctx *write_ctx;
13805 };
13806
13807 /* activate and initialize sqlcipher. Most importantly, this will automatically
13808    intialize OpenSSL's EVP system if it hasn't already be externally. Note that
13809    this function may be called multiple times as new codecs are intiialized.
13810    Thus it performs some basic counting to ensure that only the last and final
13811    sqlcipher_deactivate() will free the EVP structures.
13812 */
13813 void sqlcipher_activate() {
13814   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13815
13816   /* we'll initialize openssl and increment the internal init counter
13817      but only if it hasn't been initalized outside of SQLCipher by this program
13818      e.g. on startup */
13819   if(openssl_init_count == 0 && EVP_get_cipherbyname(CIPHER) != NULL) {
13820     openssl_external_init = 1;
13821   }
13822
13823   if(openssl_external_init == 0) {
13824     if(openssl_init_count == 0)  {
13825       OpenSSL_add_all_algorithms();
13826     }
13827     openssl_init_count++;
13828   }
13829   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13830 }
13831
13832 /* deactivate SQLCipher, most imporantly decremeting the activation count and
13833    freeing the EVP structures on the final deactivation to ensure that
13834    OpenSSL memory is cleaned up */
13835 void sqlcipher_deactivate() {
13836   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13837   /* If it is initialized externally, then the init counter should never be greater than zero.
13838      This should prevent SQLCipher from "cleaning up" openssl
13839      when something else in the program might be using it. */
13840   if(openssl_external_init == 0) {
13841     openssl_init_count--;
13842     /* if the counter reaches zero after it's decremented release EVP memory
13843        Note: this code will only be reached if OpensSSL_add_all_algorithms()
13844        is called by SQLCipher internally. */
13845     if(openssl_init_count == 0) {
13846       EVP_cleanup();
13847     }
13848   }
13849   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13850 }
13851
13852 /* constant time memset using volitile to avoid having the memset
13853    optimized out by the compiler.
13854    Note: As suggested by Joachim Schipper (joachim.schipper@fox-it.com)
13855 */
13856 void* sqlcipher_memset(void *v, unsigned char value, int len) {
13857   int i = 0;
13858   volatile unsigned char *a = v;
13859
13860   if (v == NULL) return v;
13861
13862   for(i = 0; i < len; i++) {
13863     a[i] = value;
13864   }
13865
13866   return v;
13867 }
13868
13869 /* constant time memory check tests every position of a memory segement
13870    matches a single value (i.e. the memory is all zeros)
13871    returns 0 if match, 1 of no match */
13872 int sqlcipher_ismemset(const void *v, unsigned char value, int len) {
13873   const unsigned char *a = v;
13874   int i = 0, result = 0;
13875
13876   for(i = 0; i < len; i++) {
13877     result |= a[i] ^ value;
13878   }
13879
13880   return (result != 0);
13881 }
13882
13883 /* constant time memory comparison routine.
13884    returns 0 if match, 1 if no match */
13885 int sqlcipher_memcmp(const void *v0, const void *v1, int len) {
13886   const unsigned char *a0 = v0, *a1 = v1;
13887   int i = 0, result = 0;
13888
13889   for(i = 0; i < len; i++) {
13890     result |= a0[i] ^ a1[i];
13891   }
13892
13893   return (result != 0);
13894 }
13895
13896 /* generate a defined number of pseudorandom bytes */
13897 int sqlcipher_random (void *buffer, int length) {
13898   return RAND_bytes((unsigned char *)buffer, length);
13899 }
13900
13901 /**
13902   * Free and wipe memory. Uses SQLites internal sqlite3_free so that memory
13903   * can be countend and memory leak detection works in the test suite.
13904   * If ptr is not null memory will be freed.
13905   * If sz is greater than zero, the memory will be overwritten with zero before it is freed
13906   * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the
13907   * memory segment so it can be paged
13908   */
13909 void sqlcipher_free(void *ptr, int sz) {
13910   if(ptr) {
13911     if(sz > 0) {
13912       sqlcipher_memset(ptr, 0, sz);
13913 #ifndef OMIT_MEMLOCK
13914 #if defined(__unix__) || defined(__APPLE__)
13915       munlock(ptr, sz);
13916 #elif defined(_WIN32)
13917       VirtualUnlock(ptr, sz);
13918 #endif
13919 #endif
13920     }
13921     sqlite3_free(ptr);
13922   }
13923 }
13924
13925 /**
13926   * allocate memory. Uses sqlite's internall malloc wrapper so memory can be
13927   * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK
13928   * attempts to lock the memory pages so sensitive information won't be swapped
13929   */
13930 void* sqlcipher_malloc(int sz) {
13931   void *ptr = sqlite3Malloc(sz);
13932   sqlcipher_memset(ptr, 0, sz);
13933 #ifndef OMIT_MEMLOCK
13934   if(ptr) {
13935 #if defined(__unix__) || defined(__APPLE__)
13936     mlock(ptr, sz);
13937 #elif defined(_WIN32)
13938     VirtualLock(ptr, sz);
13939 #endif
13940   }
13941 #endif
13942   return ptr;
13943 }
13944
13945
13946 /**
13947   * Initialize new cipher_ctx struct. This function will allocate memory
13948   * for the cipher context and for the key
13949   *
13950   * returns SQLITE_OK if initialization was successful
13951   * returns SQLITE_NOMEM if an error occured allocating memory
13952   */
13953 int sqlcipher_cipher_ctx_init(cipher_ctx **iCtx) {
13954   cipher_ctx *ctx;
13955   *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx));
13956   ctx = *iCtx;
13957   if(ctx == NULL) return SQLITE_NOMEM;
13958
13959   ctx->key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH);
13960   ctx->hmac_key = (unsigned char *) sqlcipher_malloc(EVP_MAX_KEY_LENGTH);
13961   if(ctx->key == NULL) return SQLITE_NOMEM;
13962   if(ctx->hmac_key == NULL) return SQLITE_NOMEM;
13963
13964   /* setup default flags */
13965   ctx->flags = default_flags;
13966
13967   return SQLITE_OK;
13968 }
13969
13970 /**
13971   * Free and wipe memory associated with a cipher_ctx
13972   */
13973 void sqlcipher_cipher_ctx_free(cipher_ctx **iCtx) {
13974   cipher_ctx *ctx = *iCtx;
13975   CODEC_TRACE(("cipher_ctx_free: entered iCtx=%p\n", iCtx));
13976   sqlcipher_free(ctx->key, ctx->key_sz);
13977   sqlcipher_free(ctx->hmac_key, ctx->key_sz);
13978   sqlcipher_free(ctx->pass, ctx->pass_sz);
13979   sqlcipher_free(ctx, sizeof(cipher_ctx));
13980 }
13981
13982 /**
13983   * Compare one cipher_ctx to another.
13984   *
13985   * returns 0 if all the parameters (except the derived key data) are the same
13986   * returns 1 otherwise
13987   */
13988 int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) {
13989   CODEC_TRACE(("sqlcipher_cipher_ctx_cmp: entered c1=%p c2=%p\n", c1, c2));
13990
13991   if(
13992     c1->evp_cipher == c2->evp_cipher
13993     && c1->iv_sz == c2->iv_sz
13994     && c1->kdf_iter == c2->kdf_iter
13995     && c1->fast_kdf_iter == c2->fast_kdf_iter
13996     && c1->key_sz == c2->key_sz
13997     && c1->pass_sz == c2->pass_sz
13998     && c1->flags == c2->flags
13999     && c1->hmac_sz == c2->hmac_sz
14000     && (
14001       c1->pass == c2->pass
14002       || !sqlcipher_memcmp((const unsigned char*)c1->pass,
14003                            (const unsigned char*)c2->pass,
14004                            c1->pass_sz)
14005     )
14006   ) return 0;
14007   return 1;
14008 }
14009
14010 /**
14011   * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a
14012   * fully initialized context, you could copy it to write_ctx and all yet data
14013   * and pass information across
14014   *
14015   * returns SQLITE_OK if initialization was successful
14016   * returns SQLITE_NOMEM if an error occured allocating memory
14017   */
14018 int sqlcipher_cipher_ctx_copy(cipher_ctx *target, cipher_ctx *source) {
14019   void *key = target->key;
14020   void *hmac_key = target->hmac_key;
14021
14022   CODEC_TRACE(("sqlcipher_cipher_ctx_copy: entered target=%p, source=%p\n", target, source));
14023   sqlcipher_free(target->pass, target->pass_sz);
14024   memcpy(target, source, sizeof(cipher_ctx));
14025
14026   target->key = key; //restore pointer to previously allocated key data
14027   memcpy(target->key, source->key, EVP_MAX_KEY_LENGTH);
14028
14029   target->hmac_key = hmac_key; //restore pointer to previously allocated hmac key data
14030   memcpy(target->hmac_key, source->hmac_key, EVP_MAX_KEY_LENGTH);
14031
14032   target->pass = sqlcipher_malloc(source->pass_sz);
14033   if(target->pass == NULL) return SQLITE_NOMEM;
14034   memcpy(target->pass, source->pass, source->pass_sz);
14035
14036   return SQLITE_OK;
14037 }
14038
14039
14040 /**
14041   * Set the raw password / key data for a cipher context
14042   *
14043   * returns SQLITE_OK if assignment was successfull
14044   * returns SQLITE_NOMEM if an error occured allocating memory
14045   * returns SQLITE_ERROR if the key couldn't be set because the pass was null or size was zero
14046   */
14047 int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) {
14048   sqlcipher_free(ctx->pass, ctx->pass_sz);
14049   ctx->pass_sz = nKey;
14050   if(zKey && nKey) {
14051     ctx->pass = sqlcipher_malloc(nKey);
14052     if(ctx->pass == NULL) return SQLITE_NOMEM;
14053     memcpy(ctx->pass, zKey, nKey);
14054     return SQLITE_OK;
14055   }
14056   return SQLITE_ERROR;
14057 }
14058
14059 int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) {
14060   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14061   int rc;
14062
14063   if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLITE_OK) return rc;
14064   c_ctx->derive_key = 1;
14065
14066   if(for_ctx == 2)
14067     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
14068       return rc;
14069
14070   return SQLITE_OK;
14071 }
14072
14073 int sqlcipher_codec_ctx_set_cipher(codec_ctx *ctx, const char *cipher_name, int for_ctx) {
14074   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14075   int rc;
14076
14077   c_ctx->evp_cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name);
14078   c_ctx->key_sz = EVP_CIPHER_key_length(c_ctx->evp_cipher);
14079   c_ctx->iv_sz = EVP_CIPHER_iv_length(c_ctx->evp_cipher);
14080   c_ctx->block_sz = EVP_CIPHER_block_size(c_ctx->evp_cipher);
14081   c_ctx->hmac_sz = EVP_MD_size(EVP_sha1());
14082   c_ctx->derive_key = 1;
14083
14084   if(for_ctx == 2)
14085     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
14086       return rc;
14087
14088   return SQLITE_OK;
14089 }
14090
14091 const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx, int for_ctx) {
14092   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14093   EVP_CIPHER *evp_cipher = c_ctx->evp_cipher;
14094   return EVP_CIPHER_name(evp_cipher);
14095 }
14096
14097 int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter, int for_ctx) {
14098   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14099   int rc;
14100
14101   c_ctx->kdf_iter = kdf_iter;
14102   c_ctx->derive_key = 1;
14103
14104   if(for_ctx == 2)
14105     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
14106       return rc;
14107
14108   return SQLITE_OK;
14109 }
14110
14111 int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx, int for_ctx) {
14112   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14113   return c_ctx->kdf_iter;
14114 }
14115
14116 int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter, int for_ctx) {
14117   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14118   int rc;
14119
14120   c_ctx->fast_kdf_iter = fast_kdf_iter;
14121   c_ctx->derive_key = 1;
14122
14123   if(for_ctx == 2)
14124     if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
14125       return rc;
14126
14127   return SQLITE_OK;
14128 }
14129
14130 int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *ctx, int for_ctx) {
14131   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14132   return c_ctx->fast_kdf_iter;
14133 }
14134
14135 /* set the global default flag for HMAC */
14136 void sqlcipher_set_default_use_hmac(int use) {
14137   if(use) default_flags |= CIPHER_FLAG_HMAC;
14138   else default_flags &= ~CIPHER_FLAG_HMAC;
14139 }
14140
14141 int sqlcipher_get_default_use_hmac() {
14142   return (default_flags & CIPHER_FLAG_HMAC) != 0;
14143 }
14144
14145 void sqlcipher_set_hmac_salt_mask(unsigned char mask) {
14146   hmac_salt_mask = mask;
14147 }
14148
14149 unsigned char sqlcipher_get_hmac_salt_mask() {
14150   return hmac_salt_mask;
14151 }
14152
14153 /* set the codec flag for whether this individual database should be using hmac */
14154 int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) {
14155   int reserve = EVP_MAX_IV_LENGTH; /* base reserve size will be IV only */
14156
14157   if(use) reserve += ctx->read_ctx->hmac_sz; /* if reserve will include hmac, update that size */
14158
14159   /* calculate the amount of reserve needed in even increments of the cipher block size */
14160
14161   reserve = ((reserve % ctx->read_ctx->block_sz) == 0) ? reserve :
14162                ((reserve / ctx->read_ctx->block_sz) + 1) * ctx->read_ctx->block_sz;
14163
14164   CODEC_TRACE(("sqlcipher_codec_ctx_set_use_hmac: use=%d block_sz=%d md_size=%d reserve=%d\n",
14165                 use, ctx->read_ctx->block_sz, ctx->read_ctx->hmac_sz, reserve));
14166
14167
14168   if(use) {
14169     sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_HMAC);
14170   } else {
14171     sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_HMAC);
14172   }
14173
14174   ctx->write_ctx->reserve_sz = ctx->read_ctx->reserve_sz = reserve;
14175
14176   return SQLITE_OK;
14177 }
14178
14179 int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx, int for_ctx) {
14180   cipher_ctx * c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14181   return (c_ctx->flags & CIPHER_FLAG_HMAC) != 0;
14182 }
14183
14184 int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag) {
14185   ctx->write_ctx->flags |= flag;
14186   ctx->read_ctx->flags |= flag;
14187   return SQLITE_OK;
14188 }
14189
14190 int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag) {
14191   ctx->write_ctx->flags &= ~flag;
14192   ctx->read_ctx->flags &= ~flag;
14193   return SQLITE_OK;
14194 }
14195
14196 int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag, int for_ctx) {
14197   cipher_ctx * c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14198   return (c_ctx->flags & flag) != 0;
14199 }
14200
14201 void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) {
14202   CODEC_TRACE(("sqlcipher_codec_ctx_set_error: ctx=%p, error=%d\n", ctx, error));
14203   sqlite3pager_sqlite3PagerSetError(ctx->pBt->pBt->pPager, error);
14204   ctx->pBt->pBt->db->errCode = error;
14205 }
14206
14207 int sqlcipher_codec_ctx_get_reservesize(codec_ctx *ctx) {
14208   return ctx->read_ctx->reserve_sz;
14209 }
14210
14211 void* sqlcipher_codec_ctx_get_data(codec_ctx *ctx) {
14212   return ctx->buffer;
14213 }
14214
14215 void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx) {
14216   return ctx->kdf_salt;
14217 }
14218
14219 void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) {
14220   *zKey = ctx->read_ctx->pass;
14221   *nKey = ctx->read_ctx->pass_sz;
14222 }
14223
14224 int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) {
14225   /* attempt to free the existing page buffer */
14226   sqlcipher_free(ctx->buffer,ctx->page_sz);
14227   ctx->page_sz = size;
14228
14229   /* pre-allocate a page buffer of PageSize bytes. This will
14230      be used as a persistent buffer for encryption and decryption
14231      operations to avoid overhead of multiple memory allocations*/
14232   ctx->buffer = sqlcipher_malloc(size);
14233   if(ctx->buffer == NULL) return SQLITE_NOMEM;
14234
14235   return SQLITE_OK;
14236 }
14237
14238 int sqlcipher_codec_ctx_get_pagesize(codec_ctx *ctx) {
14239   return ctx->page_sz;
14240 }
14241
14242 int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_file *fd, const void *zKey, int nKey) {
14243   int rc;
14244   codec_ctx *ctx;
14245   *iCtx = sqlcipher_malloc(sizeof(codec_ctx));
14246   ctx = *iCtx;
14247
14248   if(ctx == NULL) return SQLITE_NOMEM;
14249
14250   ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */
14251
14252   /* allocate space for salt data. Then read the first 16 bytes
14253        directly off the database file. This is the salt for the
14254        key derivation function. If we get a short read allocate
14255        a new random salt value */
14256   ctx->kdf_salt_sz = FILE_HEADER_SZ;
14257   ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
14258   if(ctx->kdf_salt == NULL) return SQLITE_NOMEM;
14259
14260   /* allocate space for separate hmac salt data. We want the
14261      HMAC derivation salt to be different than the encryption
14262      key derivation salt */
14263   ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
14264   if(ctx->hmac_kdf_salt == NULL) return SQLITE_NOMEM;
14265
14266
14267   /*
14268      Always overwrite page size and set to the default because the first page of the database
14269      in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in
14270      cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman
14271   */
14272   if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, SQLITE_DEFAULT_PAGE_SIZE)) != SQLITE_OK) return rc;
14273
14274   if((rc = sqlcipher_cipher_ctx_init(&ctx->read_ctx)) != SQLITE_OK) return rc;
14275   if((rc = sqlcipher_cipher_ctx_init(&ctx->write_ctx)) != SQLITE_OK) return rc;
14276
14277   if(fd == NULL || sqlite3OsRead(fd, ctx->kdf_salt, FILE_HEADER_SZ, 0) != SQLITE_OK) {
14278     /* if unable to read the bytes, generate random salt */
14279     if(sqlcipher_random(ctx->kdf_salt, FILE_HEADER_SZ) != 1) return SQLITE_ERROR;
14280   }
14281
14282   if((rc = sqlcipher_codec_ctx_set_cipher(ctx, CIPHER, 0)) != SQLITE_OK) return rc;
14283   if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, PBKDF2_ITER, 0)) != SQLITE_OK) return rc;
14284   if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER, 0)) != SQLITE_OK) return rc;
14285   if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) return rc;
14286
14287   /* Note that use_hmac is a special case that requires recalculation of page size
14288      so we call set_use_hmac to perform setup */
14289   if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, default_flags & CIPHER_FLAG_HMAC)) != SQLITE_OK) return rc;
14290
14291   if((rc = sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) return rc;
14292
14293   return SQLITE_OK;
14294 }
14295
14296 /**
14297   * Free and wipe memory associated with a cipher_ctx, including the allocated
14298   * read_ctx and write_ctx.
14299   */
14300 void sqlcipher_codec_ctx_free(codec_ctx **iCtx) {
14301   codec_ctx *ctx = *iCtx;
14302   CODEC_TRACE(("codec_ctx_free: entered iCtx=%p\n", iCtx));
14303   sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz);
14304   sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz);
14305   sqlcipher_free(ctx->buffer, 0);
14306   sqlcipher_cipher_ctx_free(&ctx->read_ctx);
14307   sqlcipher_cipher_ctx_free(&ctx->write_ctx);
14308   sqlcipher_free(ctx, sizeof(codec_ctx));
14309 }
14310
14311 /** convert a 32bit unsigned integer to little endian byte ordering */
14312 static void sqlcipher_put4byte_le(unsigned char *p, u32 v) {
14313   p[0] = (u8)v;
14314   p[1] = (u8)(v>>8);
14315   p[2] = (u8)(v>>16);
14316   p[3] = (u8)(v>>24);
14317 }
14318
14319 int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) {
14320   unsigned char pgno_raw[sizeof(pgno)];
14321   /* we may convert page number to consistent representation before calculating MAC for
14322      compatibility across big-endian and little-endian platforms.
14323
14324      Note: The public release of sqlcipher 2.0.0 to 2.0.6 had a bug where the bytes of pgno
14325      were used directly in the MAC. SQLCipher convert's to little endian by default to preserve
14326      backwards compatibility on the most popular platforms, but can optionally be configured
14327      to use either big endian or native byte ordering via pragma. */
14328
14329   if(ctx->flags & CIPHER_FLAG_LE_PGNO) { /* compute hmac using little endian pgno*/
14330     sqlcipher_put4byte_le(pgno_raw, pgno);
14331   } else if(ctx->flags & CIPHER_FLAG_BE_PGNO) { /* compute hmac using big endian pgno */
14332     sqlite3Put4byte(pgno_raw, pgno); /* sqlite3Put4byte converts 32bit uint to big endian  */
14333   } else { /* use native byte ordering */
14334     memcpy(pgno_raw, &pgno, sizeof(pgno));
14335   }
14336
14337   HMAC_CTX_init(&ctx->hctx);
14338   HMAC_Init_ex(&ctx->hctx, ctx->hmac_key, ctx->key_sz, EVP_sha1(), NULL);
14339
14340   /* include the encrypted page data,  initialization vector, and page number in HMAC. This will
14341      prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise
14342      valid pages out of order in a database */
14343   HMAC_Update(&ctx->hctx, in, in_sz);
14344   HMAC_Update(&ctx->hctx, (const unsigned char*) pgno_raw, sizeof(pgno));
14345   HMAC_Final(&ctx->hctx, out, NULL);
14346   HMAC_CTX_cleanup(&ctx->hctx);
14347   return SQLITE_OK;
14348 }
14349
14350 /*
14351  * ctx - codec context
14352  * pgno - page number in database
14353  * size - size in bytes of input and output buffers
14354  * mode - 1 to encrypt, 0 to decrypt
14355  * in - pointer to input bytes
14356  * out - pouter to output bytes
14357  */
14358 int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
14359   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
14360   unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
14361   int tmp_csz, csz, size;
14362
14363   /* calculate some required positions into various buffers */
14364   size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
14365   iv_out = out + size;
14366   iv_in = in + size;
14367
14368   /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain
14369      random bytes. note, these pointers are only valid when using hmac */
14370   hmac_in = in + size + c_ctx->iv_sz;
14371   hmac_out = out + size + c_ctx->iv_sz;
14372   out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */
14373
14374   CODEC_TRACE(("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size));
14375   CODEC_HEXDUMP("codec_cipher: input page data", in, page_sz);
14376
14377   /* the key size should never be zero. If it is, error out. */
14378   if(c_ctx->key_sz == 0) {
14379     CODEC_TRACE(("codec_cipher: error possible context corruption, key_sz is zero for pgno=%d\n", pgno));
14380     sqlcipher_memset(out, 0, page_sz);
14381     return SQLITE_ERROR;
14382   }
14383
14384   if(mode == CIPHER_ENCRYPT) {
14385     /* start at front of the reserve block, write random data to the end */
14386     if(sqlcipher_random(iv_out, c_ctx->reserve_sz) != 1) return SQLITE_ERROR;
14387   } else { /* CIPHER_DECRYPT */
14388     memcpy(iv_out, iv_in, c_ctx->iv_sz); /* copy the iv from the input to output buffer */
14389   }
14390
14391   if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT)) {
14392     if(sqlcipher_page_hmac(c_ctx, pgno, in, size + c_ctx->iv_sz, hmac_out) != SQLITE_OK) {
14393       sqlcipher_memset(out, 0, page_sz);
14394       CODEC_TRACE(("codec_cipher: hmac operations failed for pgno=%d\n", pgno));
14395       return SQLITE_ERROR;
14396     }
14397
14398     CODEC_TRACE(("codec_cipher: comparing hmac on in=%p out=%p hmac_sz=%d\n", hmac_in, hmac_out, c_ctx->hmac_sz));
14399     if(sqlcipher_memcmp(hmac_in, hmac_out, c_ctx->hmac_sz) != 0) { /* the hmac check failed */
14400       if(sqlcipher_ismemset(in, 0, page_sz) == 0) {
14401         /* first check if the entire contents of the page is zeros. If so, this page
14402            resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these
14403            short read failures must be ignored for autovaccum mode to work so wipe the output buffer
14404            and return SQLITE_OK to skip the decryption step. */
14405         CODEC_TRACE(("codec_cipher: zeroed page (short read) for pgno %d, encryption but returning SQLITE_OK\n", pgno));
14406         sqlcipher_memset(out, 0, page_sz);
14407         return SQLITE_OK;
14408       } else {
14409         /* if the page memory is not all zeros, it means the there was data and a hmac on the page.
14410            since the check failed, the page was either tampered with or corrupted. wipe the output buffer,
14411            and return SQLITE_ERROR to the caller */
14412         CODEC_TRACE(("codec_cipher: hmac check failed for pgno=%d returning SQLITE_ERROR\n", pgno));
14413         sqlcipher_memset(out, 0, page_sz);
14414         return SQLITE_ERROR;
14415       }
14416     }
14417   }
14418
14419   EVP_CipherInit(&c_ctx->ectx, c_ctx->evp_cipher, NULL, NULL, mode);
14420   EVP_CIPHER_CTX_set_padding(&c_ctx->ectx, 0);
14421   EVP_CipherInit(&c_ctx->ectx, NULL, c_ctx->key, iv_out, mode);
14422   EVP_CipherUpdate(&c_ctx->ectx, out, &tmp_csz, in, size);
14423   csz = tmp_csz;
14424   out += tmp_csz;
14425   EVP_CipherFinal(&c_ctx->ectx, out, &tmp_csz);
14426   csz += tmp_csz;
14427   EVP_CIPHER_CTX_cleanup(&c_ctx->ectx);
14428   assert(size == csz);
14429
14430   if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) {
14431     sqlcipher_page_hmac(c_ctx, pgno, out_start, size + c_ctx->iv_sz, hmac_out);
14432   }
14433
14434   CODEC_HEXDUMP("codec_cipher: output page data", out_start, page_sz);
14435
14436   return SQLITE_OK;
14437 }
14438
14439 /**
14440   * Derive an encryption key for a cipher contex key based on the raw password.
14441   *
14442   * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
14443   * the key space (i.e 64 hex chars for a 256 bit key) then the key data will be used directly.
14444   *
14445   * Otherwise, a key data will be derived using PBKDF2
14446   *
14447   * returns SQLITE_OK if initialization was successful
14448   * returns SQLITE_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0)
14449   */
14450 int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
14451   CODEC_TRACE(("codec_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \
14452                 ctx->kdf_salt=%p ctx->kdf_salt_sz=%d c_ctx->kdf_iter=%d \
14453                 ctx->hmac_kdf_salt=%p, c_ctx->fast_kdf_iter=%d c_ctx->key_sz=%d\n",
14454                 c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter,
14455                 ctx->hmac_kdf_salt, c_ctx->fast_kdf_iter, c_ctx->key_sz));
14456
14457
14458   if(c_ctx->pass && c_ctx->pass_sz) { // if pass is not null
14459     if (c_ctx->pass_sz == ((c_ctx->key_sz*2)+3) && sqlite3StrNICmp(c_ctx->pass ,"x'", 2) == 0) {
14460       int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */
14461       const char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
14462       CODEC_TRACE(("codec_key_derive: using raw key from hex\n"));
14463       cipher_hex2bin(z, n, c_ctx->key);
14464     } else {
14465       CODEC_TRACE(("codec_key_derive: deriving key using full PBKDF2 with %d iterations\n", c_ctx->kdf_iter));
14466       PKCS5_PBKDF2_HMAC_SHA1( c_ctx->pass, c_ctx->pass_sz,
14467                               ctx->kdf_salt, ctx->kdf_salt_sz,
14468                               c_ctx->kdf_iter, c_ctx->key_sz, c_ctx->key);
14469
14470     }
14471
14472     /* if this context is setup to use hmac checks, generate a seperate and different
14473        key for HMAC. In this case, we use the output of the previous KDF as the input to
14474        this KDF run. This ensures a distinct but predictable HMAC key. */
14475     if(c_ctx->flags & CIPHER_FLAG_HMAC) {
14476       int i;
14477
14478       /* start by copying the kdf key into the hmac salt slot
14479          then XOR it with the fixed hmac salt defined at compile time
14480          this ensures that the salt passed in to derive the hmac key, while
14481          easy to derive and publically known, is not the same as the salt used
14482          to generate the encryption key */
14483       memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz);
14484       for(i = 0; i < ctx->kdf_salt_sz; i++) {
14485         ctx->hmac_kdf_salt[i] ^= hmac_salt_mask;
14486       }
14487
14488       CODEC_TRACE(("codec_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n",
14489         c_ctx->fast_kdf_iter));
14490       PKCS5_PBKDF2_HMAC_SHA1( (const char*)c_ctx->key, c_ctx->key_sz,
14491                               ctx->hmac_kdf_salt, ctx->kdf_salt_sz,
14492                               c_ctx->fast_kdf_iter, c_ctx->key_sz, c_ctx->hmac_key);
14493     }
14494
14495     c_ctx->derive_key = 0;
14496     return SQLITE_OK;
14497   };
14498   return SQLITE_ERROR;
14499 }
14500
14501 int sqlcipher_codec_key_derive(codec_ctx *ctx) {
14502   /* derive key on first use if necessary */
14503   if(ctx->read_ctx->derive_key) {
14504     if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR;
14505   }
14506
14507   if(ctx->write_ctx->derive_key) {
14508     if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) {
14509       // the relevant parameters are the same, just copy read key
14510       if(sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR;
14511     } else {
14512       if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLITE_OK) return SQLITE_ERROR;
14513     }
14514   }
14515   return SQLITE_OK;
14516 }
14517
14518 int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) {
14519   if(source == CIPHER_READ_CTX) {
14520       return sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx);
14521   } else {
14522       return sqlcipher_cipher_ctx_copy(ctx->read_ctx, ctx->write_ctx);
14523   }
14524 }
14525
14526
14527 #ifndef OMIT_EXPORT
14528
14529 /*
14530  * Implementation of an "export" function that allows a caller
14531  * to duplicate the main database to an attached database. This is intended
14532  * as a conveneince for users who need to:
14533  *
14534  *   1. migrate from an non-encrypted database to an encrypted database
14535  *   2. move from an encrypted database to a non-encrypted database
14536  *   3. convert beween the various flavors of encrypted databases.
14537  *
14538  * This implementation is based heavily on the procedure and code used
14539  * in vacuum.c, but is exposed as a function that allows export to any
14540  * named attached database.
14541  */
14542
14543 /*
14544 ** Finalize a prepared statement.  If there was an error, store the
14545 ** text of the error message in *pzErrMsg.  Return the result code.
14546 **
14547 ** Based on vacuumFinalize from vacuum.c
14548 */
14549 static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
14550   int rc;
14551   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
14552   if( rc ){
14553     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
14554   }
14555   return rc;
14556 }
14557
14558 /*
14559 ** Execute zSql on database db. Return an error code.
14560 **
14561 ** Based on execSql from vacuum.c
14562 */
14563 static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
14564   sqlite3_stmt *pStmt;
14565   VVA_ONLY( int rc; )
14566   if( !zSql ){
14567     return SQLITE_NOMEM;
14568   }
14569   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
14570     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
14571     return sqlite3_errcode(db);
14572   }
14573   VVA_ONLY( rc = ) sqlite3_step(pStmt);
14574   assert( rc!=SQLITE_ROW );
14575   return sqlcipher_finalize(db, pStmt, pzErrMsg);
14576 }
14577
14578 /*
14579 ** Execute zSql on database db. The statement returns exactly
14580 ** one column. Execute this as SQL on the same database.
14581 **
14582 ** Based on execExecSql from vacuum.c
14583 */
14584 static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
14585   sqlite3_stmt *pStmt;
14586   int rc;
14587
14588   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
14589   if( rc!=SQLITE_OK ) return rc;
14590
14591   while( SQLITE_ROW==sqlite3_step(pStmt) ){
14592     rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
14593     if( rc!=SQLITE_OK ){
14594       sqlcipher_finalize(db, pStmt, pzErrMsg);
14595       return rc;
14596     }
14597   }
14598
14599   return sqlcipher_finalize(db, pStmt, pzErrMsg);
14600 }
14601
14602 /*
14603  * copy database and schema from the main database to an attached database
14604  *
14605  * Based on sqlite3RunVacuum from vacuum.c
14606 */
14607 void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) {
14608   sqlite3 *db = sqlite3_context_db_handle(context);
14609   const char* attachedDb = (const char*) sqlite3_value_text(argv[0]);
14610   int saved_flags;        /* Saved value of the db->flags */
14611   int saved_nChange;      /* Saved value of db->nChange */
14612   int saved_nTotalChange; /* Saved value of db->nTotalChange */
14613   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
14614   int rc = SQLITE_OK;     /* Return code from service routines */
14615   char *zSql = NULL;         /* SQL statements */
14616   char *pzErrMsg = NULL;
14617
14618   saved_flags = db->flags;
14619   saved_nChange = db->nChange;
14620   saved_nTotalChange = db->nTotalChange;
14621   saved_xTrace = db->xTrace;
14622   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
14623   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
14624   db->xTrace = 0;
14625
14626   /* Query the schema of the main database. Create a mirror schema
14627   ** in the temporary database.
14628   */
14629   zSql = sqlite3_mprintf(
14630     "SELECT 'CREATE TABLE %s.' || substr(sql,14) "
14631     "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
14632     "   AND rootpage>0"
14633   , attachedDb);
14634   rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
14635   if( rc!=SQLITE_OK ) goto end_of_export;
14636   sqlite3_free(zSql);
14637
14638   zSql = sqlite3_mprintf(
14639     "SELECT 'CREATE INDEX %s.' || substr(sql,14)"
14640     "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %%' "
14641   , attachedDb);
14642   rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
14643   if( rc!=SQLITE_OK ) goto end_of_export;
14644   sqlite3_free(zSql);
14645
14646   zSql = sqlite3_mprintf(
14647     "SELECT 'CREATE UNIQUE INDEX %s.' || substr(sql,21) "
14648     "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %%'"
14649   , attachedDb);
14650   rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
14651   if( rc!=SQLITE_OK ) goto end_of_export;
14652   sqlite3_free(zSql);
14653
14654   /* Loop through the tables in the main database. For each, do
14655   ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy
14656   ** the contents to the temporary database.
14657   */
14658   zSql = sqlite3_mprintf(
14659     "SELECT 'INSERT INTO %s.' || quote(name) "
14660     "|| ' SELECT * FROM main.' || quote(name) || ';'"
14661     "FROM main.sqlite_master "
14662     "WHERE type = 'table' AND name!='sqlite_sequence' "
14663     "  AND rootpage>0"
14664   , attachedDb);
14665   rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
14666   if( rc!=SQLITE_OK ) goto end_of_export;
14667   sqlite3_free(zSql);
14668
14669   /* Copy over the sequence table
14670   */
14671   zSql = sqlite3_mprintf(
14672     "SELECT 'DELETE FROM %s.' || quote(name) || ';' "
14673     "FROM %s.sqlite_master WHERE name='sqlite_sequence' "
14674   , attachedDb, attachedDb);
14675   rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
14676   if( rc!=SQLITE_OK ) goto end_of_export;
14677   sqlite3_free(zSql);
14678
14679   zSql = sqlite3_mprintf(
14680     "SELECT 'INSERT INTO %s.' || quote(name) "
14681     "|| ' SELECT * FROM main.' || quote(name) || ';' "
14682     "FROM %s.sqlite_master WHERE name=='sqlite_sequence';"
14683   , attachedDb, attachedDb);
14684   rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
14685   if( rc!=SQLITE_OK ) goto end_of_export;
14686   sqlite3_free(zSql);
14687
14688   /* Copy the triggers, views, and virtual tables from the main database
14689   ** over to the temporary database.  None of these objects has any
14690   ** associated storage, so all we have to do is copy their entries
14691   ** from the SQLITE_MASTER table.
14692   */
14693   zSql = sqlite3_mprintf(
14694     "INSERT INTO %s.sqlite_master "
14695     "  SELECT type, name, tbl_name, rootpage, sql"
14696     "    FROM main.sqlite_master"
14697     "   WHERE type='view' OR type='trigger'"
14698     "      OR (type='table' AND rootpage=0)"
14699   , attachedDb);
14700   rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql);
14701   if( rc!=SQLITE_OK ) goto end_of_export;
14702   sqlite3_free(zSql);
14703
14704   zSql = NULL;
14705 end_of_export:
14706   db->flags = saved_flags;
14707   db->nChange = saved_nChange;
14708   db->nTotalChange = saved_nTotalChange;
14709   db->xTrace = saved_xTrace;
14710
14711   sqlite3_free(zSql);
14712
14713   if(rc) {
14714     if(pzErrMsg != NULL) {
14715       sqlite3_result_error(context, pzErrMsg, -1);
14716       sqlite3DbFree(db, pzErrMsg);
14717     } else {
14718       sqlite3_result_error(context, sqlite3ErrStr(rc), -1);
14719     }
14720   }
14721 }
14722
14723 #endif
14724 #endif
14725
14726 /************** End of crypto_impl.c *****************************************/
14727 /************** Begin file global.c ******************************************/
14728 /*
14729 ** 2008 June 13
14730 **
14731 ** The author disclaims copyright to this source code.  In place of
14732 ** a legal notice, here is a blessing:
14733 **
14734 **    May you do good and not evil.
14735 **    May you find forgiveness for yourself and forgive others.
14736 **    May you share freely, never taking more than you give.
14737 **
14738 *************************************************************************
14739 **
14740 ** This file contains definitions of global variables and contants.
14741 */
14742
14743 /* An array to map all upper-case characters into their corresponding
14744 ** lower-case character.
14745 **
14746 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
14747 ** handle case conversions for the UTF character set since the tables
14748 ** involved are nearly as big or bigger than SQLite itself.
14749 */
14750 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
14751 #ifdef SQLITE_ASCII
14752       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
14753      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
14754      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
14755      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
14756     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
14757     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
14758     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
14759     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
14760     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
14761     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
14762     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
14763     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
14764     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
14765     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
14766     252,253,254,255
14767 #endif
14768 #ifdef SQLITE_EBCDIC
14769       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
14770      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
14771      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
14772      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
14773      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
14774      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
14775      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
14776     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
14777     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
14778     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
14779     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
14780     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
14781     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
14782     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
14783     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
14784     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
14785 #endif
14786 };
14787
14788 /*
14789 ** The following 256 byte lookup table is used to support SQLites built-in
14790 ** equivalents to the following standard library functions:
14791 **
14792 **   isspace()                        0x01
14793 **   isalpha()                        0x02
14794 **   isdigit()                        0x04
14795 **   isalnum()                        0x06
14796 **   isxdigit()                       0x08
14797 **   toupper()                        0x20
14798 **   SQLite identifier character      0x40
14799 **
14800 ** Bit 0x20 is set if the mapped character requires translation to upper
14801 ** case. i.e. if the character is a lower-case ASCII character.
14802 ** If x is a lower-case ASCII character, then its upper-case equivalent
14803 ** is (x - 0x20). Therefore toupper() can be implemented as:
14804 **
14805 **   (x & ~(map[x]&0x20))
14806 **
14807 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
14808 ** array. tolower() is used more often than toupper() by SQLite.
14809 **
14810 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
14811 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
14812 ** non-ASCII UTF character. Hence the test for whether or not a character is
14813 ** part of an identifier is 0x46.
14814 **
14815 ** SQLite's versions are identical to the standard versions assuming a
14816 ** locale of "C". They are implemented as macros in sqliteInt.h.
14817 */
14818 #ifdef SQLITE_ASCII
14819 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
14820   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
14821   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
14822   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
14823   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
14824   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
14825   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
14826   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
14827   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
14828
14829   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
14830   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
14831   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
14832   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
14833   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
14834   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
14835   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
14836   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
14837
14838   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
14839   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
14840   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
14841   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
14842   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
14843   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
14844   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
14845   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
14846
14847   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
14848   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
14849   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
14850   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
14851   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
14852   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
14853   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
14854   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
14855 };
14856 #endif
14857
14858 #ifndef SQLITE_USE_URI
14859 # define  SQLITE_USE_URI 0
14860 #endif
14861
14862 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
14863 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
14864 #endif
14865
14866 /*
14867 ** The following singleton contains the global configuration for
14868 ** the SQLite library.
14869 */
14870 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
14871    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
14872    1,                         /* bCoreMutex */
14873    SQLITE_THREADSAFE==1,      /* bFullMutex */
14874    SQLITE_USE_URI,            /* bOpenUri */
14875    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
14876    0x7ffffffe,                /* mxStrlen */
14877    128,                       /* szLookaside */
14878    500,                       /* nLookaside */
14879    {0,0,0,0,0,0,0,0},         /* m */
14880    {0,0,0,0,0,0,0,0,0},       /* mutex */
14881    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
14882    (void*)0,                  /* pHeap */
14883    0,                         /* nHeap */
14884    0, 0,                      /* mnHeap, mxHeap */
14885    (void*)0,                  /* pScratch */
14886    0,                         /* szScratch */
14887    0,                         /* nScratch */
14888    (void*)0,                  /* pPage */
14889    0,                         /* szPage */
14890    0,                         /* nPage */
14891    0,                         /* mxParserStack */
14892    0,                         /* sharedCacheEnabled */
14893    /* All the rest should always be initialized to zero */
14894    0,                         /* isInit */
14895    0,                         /* inProgress */
14896    0,                         /* isMutexInit */
14897    0,                         /* isMallocInit */
14898    0,                         /* isPCacheInit */
14899    0,                         /* pInitMutex */
14900    0,                         /* nRefInitMutex */
14901    0,                         /* xLog */
14902    0,                         /* pLogArg */
14903    0,                         /* bLocaltimeFault */
14904 #ifdef SQLITE_ENABLE_SQLLOG
14905    0,                         /* xSqllog */
14906    0                          /* pSqllogArg */
14907 #endif
14908 };
14909
14910
14911 /*
14912 ** Hash table for global functions - functions common to all
14913 ** database connections.  After initialization, this table is
14914 ** read-only.
14915 */
14916 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
14917
14918 /*
14919 ** Constant tokens for values 0 and 1.
14920 */
14921 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
14922    { "0", 1 },
14923    { "1", 1 }
14924 };
14925
14926
14927 /*
14928 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
14929 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
14930 ** the database page that contains the pending byte.  It never attempts
14931 ** to read or write that page.  The pending byte page is set assign
14932 ** for use by the VFS layers as space for managing file locks.
14933 **
14934 ** During testing, it is often desirable to move the pending byte to
14935 ** a different position in the file.  This allows code that has to
14936 ** deal with the pending byte to run on files that are much smaller
14937 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
14938 ** move the pending byte.
14939 **
14940 ** IMPORTANT:  Changing the pending byte to any value other than
14941 ** 0x40000000 results in an incompatible database file format!
14942 ** Changing the pending byte during operating results in undefined
14943 ** and dileterious behavior.
14944 */
14945 #ifndef SQLITE_OMIT_WSD
14946 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
14947 #endif
14948
14949 /*
14950 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
14951 ** created by mkopcodeh.awk during compilation.  Data is obtained
14952 ** from the comments following the "case OP_xxxx:" statements in
14953 ** the vdbe.c file.
14954 */
14955 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
14956
14957 /************** End of global.c **********************************************/
14958 /************** Begin file ctime.c *******************************************/
14959 /*
14960 ** 2010 February 23
14961 **
14962 ** The author disclaims copyright to this source code.  In place of
14963 ** a legal notice, here is a blessing:
14964 **
14965 **    May you do good and not evil.
14966 **    May you find forgiveness for yourself and forgive others.
14967 **    May you share freely, never taking more than you give.
14968 **
14969 *************************************************************************
14970 **
14971 ** This file implements routines used to report what compile-time options
14972 ** SQLite was built with.
14973 */
14974
14975 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
14976
14977
14978 /*
14979 ** An array of names of all compile-time options.  This array should
14980 ** be sorted A-Z.
14981 **
14982 ** This array looks large, but in a typical installation actually uses
14983 ** only a handful of compile-time options, so most times this array is usually
14984 ** rather short and uses little memory space.
14985 */
14986 static const char * const azCompileOpt[] = {
14987
14988 /* These macros are provided to "stringify" the value of the define
14989 ** for those options in which the value is meaningful. */
14990 #define CTIMEOPT_VAL_(opt) #opt
14991 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
14992
14993 #ifdef SQLITE_32BIT_ROWID
14994   "32BIT_ROWID",
14995 #endif
14996 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
14997   "4_BYTE_ALIGNED_MALLOC",
14998 #endif
14999 #ifdef SQLITE_CASE_SENSITIVE_LIKE
15000   "CASE_SENSITIVE_LIKE",
15001 #endif
15002 #ifdef SQLITE_CHECK_PAGES
15003   "CHECK_PAGES",
15004 #endif
15005 #ifdef SQLITE_COVERAGE_TEST
15006   "COVERAGE_TEST",
15007 #endif
15008 #ifdef SQLITE_CURDIR
15009   "CURDIR",
15010 #endif
15011 #ifdef SQLITE_DEBUG
15012   "DEBUG",
15013 #endif
15014 #ifdef SQLITE_DEFAULT_LOCKING_MODE
15015   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
15016 #endif
15017 #ifdef SQLITE_DISABLE_DIRSYNC
15018   "DISABLE_DIRSYNC",
15019 #endif
15020 #ifdef SQLITE_DISABLE_LFS
15021   "DISABLE_LFS",
15022 #endif
15023 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
15024   "ENABLE_ATOMIC_WRITE",
15025 #endif
15026 #ifdef SQLITE_ENABLE_CEROD
15027   "ENABLE_CEROD",
15028 #endif
15029 #ifdef SQLITE_ENABLE_COLUMN_METADATA
15030   "ENABLE_COLUMN_METADATA",
15031 #endif
15032 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
15033   "ENABLE_EXPENSIVE_ASSERT",
15034 #endif
15035 #ifdef SQLITE_ENABLE_FTS1
15036   "ENABLE_FTS1",
15037 #endif
15038 #ifdef SQLITE_ENABLE_FTS2
15039   "ENABLE_FTS2",
15040 #endif
15041 #ifdef SQLITE_ENABLE_FTS3
15042   "ENABLE_FTS3",
15043 #endif
15044 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
15045   "ENABLE_FTS3_PARENTHESIS",
15046 #endif
15047 #ifdef SQLITE_ENABLE_FTS4
15048   "ENABLE_FTS4",
15049 #endif
15050 #ifdef SQLITE_ENABLE_ICU
15051   "ENABLE_ICU",
15052 #endif
15053 #ifdef SQLITE_ENABLE_IOTRACE
15054   "ENABLE_IOTRACE",
15055 #endif
15056 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
15057   "ENABLE_LOAD_EXTENSION",
15058 #endif
15059 #ifdef SQLITE_ENABLE_LOCKING_STYLE
15060   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
15061 #endif
15062 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15063   "ENABLE_MEMORY_MANAGEMENT",
15064 #endif
15065 #ifdef SQLITE_ENABLE_MEMSYS3
15066   "ENABLE_MEMSYS3",
15067 #endif
15068 #ifdef SQLITE_ENABLE_MEMSYS5
15069   "ENABLE_MEMSYS5",
15070 #endif
15071 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
15072   "ENABLE_OVERSIZE_CELL_CHECK",
15073 #endif
15074 #ifdef SQLITE_ENABLE_RTREE
15075   "ENABLE_RTREE",
15076 #endif
15077 #ifdef SQLITE_ENABLE_STAT3
15078   "ENABLE_STAT3",
15079 #endif
15080 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
15081   "ENABLE_UNLOCK_NOTIFY",
15082 #endif
15083 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
15084   "ENABLE_UPDATE_DELETE_LIMIT",
15085 #endif
15086 #ifdef SQLITE_HAS_CODEC
15087   "HAS_CODEC",
15088 #endif
15089 #ifdef SQLITE_HAVE_ISNAN
15090   "HAVE_ISNAN",
15091 #endif
15092 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15093   "HOMEGROWN_RECURSIVE_MUTEX",
15094 #endif
15095 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
15096   "IGNORE_AFP_LOCK_ERRORS",
15097 #endif
15098 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
15099   "IGNORE_FLOCK_LOCK_ERRORS",
15100 #endif
15101 #ifdef SQLITE_INT64_TYPE
15102   "INT64_TYPE",
15103 #endif
15104 #ifdef SQLITE_LOCK_TRACE
15105   "LOCK_TRACE",
15106 #endif
15107 #ifdef SQLITE_MAX_SCHEMA_RETRY
15108   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
15109 #endif
15110 #ifdef SQLITE_MEMDEBUG
15111   "MEMDEBUG",
15112 #endif
15113 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
15114   "MIXED_ENDIAN_64BIT_FLOAT",
15115 #endif
15116 #ifdef SQLITE_NO_SYNC
15117   "NO_SYNC",
15118 #endif
15119 #ifdef SQLITE_OMIT_ALTERTABLE
15120   "OMIT_ALTERTABLE",
15121 #endif
15122 #ifdef SQLITE_OMIT_ANALYZE
15123   "OMIT_ANALYZE",
15124 #endif
15125 #ifdef SQLITE_OMIT_ATTACH
15126   "OMIT_ATTACH",
15127 #endif
15128 #ifdef SQLITE_OMIT_AUTHORIZATION
15129   "OMIT_AUTHORIZATION",
15130 #endif
15131 #ifdef SQLITE_OMIT_AUTOINCREMENT
15132   "OMIT_AUTOINCREMENT",
15133 #endif
15134 #ifdef SQLITE_OMIT_AUTOINIT
15135   "OMIT_AUTOINIT",
15136 #endif
15137 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
15138   "OMIT_AUTOMATIC_INDEX",
15139 #endif
15140 #ifdef SQLITE_OMIT_AUTORESET
15141   "OMIT_AUTORESET",
15142 #endif
15143 #ifdef SQLITE_OMIT_AUTOVACUUM
15144   "OMIT_AUTOVACUUM",
15145 #endif
15146 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
15147   "OMIT_BETWEEN_OPTIMIZATION",
15148 #endif
15149 #ifdef SQLITE_OMIT_BLOB_LITERAL
15150   "OMIT_BLOB_LITERAL",
15151 #endif
15152 #ifdef SQLITE_OMIT_BTREECOUNT
15153   "OMIT_BTREECOUNT",
15154 #endif
15155 #ifdef SQLITE_OMIT_BUILTIN_TEST
15156   "OMIT_BUILTIN_TEST",
15157 #endif
15158 #ifdef SQLITE_OMIT_CAST
15159   "OMIT_CAST",
15160 #endif
15161 #ifdef SQLITE_OMIT_CHECK
15162   "OMIT_CHECK",
15163 #endif
15164 /* // redundant
15165 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
15166 **   "OMIT_COMPILEOPTION_DIAGS",
15167 ** #endif
15168 */
15169 #ifdef SQLITE_OMIT_COMPLETE
15170   "OMIT_COMPLETE",
15171 #endif
15172 #ifdef SQLITE_OMIT_COMPOUND_SELECT
15173   "OMIT_COMPOUND_SELECT",
15174 #endif
15175 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15176   "OMIT_DATETIME_FUNCS",
15177 #endif
15178 #ifdef SQLITE_OMIT_DECLTYPE
15179   "OMIT_DECLTYPE",
15180 #endif
15181 #ifdef SQLITE_OMIT_DEPRECATED
15182   "OMIT_DEPRECATED",
15183 #endif
15184 #ifdef SQLITE_OMIT_DISKIO
15185   "OMIT_DISKIO",
15186 #endif
15187 #ifdef SQLITE_OMIT_EXPLAIN
15188   "OMIT_EXPLAIN",
15189 #endif
15190 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
15191   "OMIT_FLAG_PRAGMAS",
15192 #endif
15193 #ifdef SQLITE_OMIT_FLOATING_POINT
15194   "OMIT_FLOATING_POINT",
15195 #endif
15196 #ifdef SQLITE_OMIT_FOREIGN_KEY
15197   "OMIT_FOREIGN_KEY",
15198 #endif
15199 #ifdef SQLITE_OMIT_GET_TABLE
15200   "OMIT_GET_TABLE",
15201 #endif
15202 #ifdef SQLITE_OMIT_INCRBLOB
15203   "OMIT_INCRBLOB",
15204 #endif
15205 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
15206   "OMIT_INTEGRITY_CHECK",
15207 #endif
15208 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
15209   "OMIT_LIKE_OPTIMIZATION",
15210 #endif
15211 #ifdef SQLITE_OMIT_LOAD_EXTENSION
15212   "OMIT_LOAD_EXTENSION",
15213 #endif
15214 #ifdef SQLITE_OMIT_LOCALTIME
15215   "OMIT_LOCALTIME",
15216 #endif
15217 #ifdef SQLITE_OMIT_LOOKASIDE
15218   "OMIT_LOOKASIDE",
15219 #endif
15220 #ifdef SQLITE_OMIT_MEMORYDB
15221   "OMIT_MEMORYDB",
15222 #endif
15223 #ifdef SQLITE_OMIT_MERGE_SORT
15224   "OMIT_MERGE_SORT",
15225 #endif
15226 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
15227   "OMIT_OR_OPTIMIZATION",
15228 #endif
15229 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
15230   "OMIT_PAGER_PRAGMAS",
15231 #endif
15232 #ifdef SQLITE_OMIT_PRAGMA
15233   "OMIT_PRAGMA",
15234 #endif
15235 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
15236   "OMIT_PROGRESS_CALLBACK",
15237 #endif
15238 #ifdef SQLITE_OMIT_QUICKBALANCE
15239   "OMIT_QUICKBALANCE",
15240 #endif
15241 #ifdef SQLITE_OMIT_REINDEX
15242   "OMIT_REINDEX",
15243 #endif
15244 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
15245   "OMIT_SCHEMA_PRAGMAS",
15246 #endif
15247 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
15248   "OMIT_SCHEMA_VERSION_PRAGMAS",
15249 #endif
15250 #ifdef SQLITE_OMIT_SHARED_CACHE
15251   "OMIT_SHARED_CACHE",
15252 #endif
15253 #ifdef SQLITE_OMIT_SUBQUERY
15254   "OMIT_SUBQUERY",
15255 #endif
15256 #ifdef SQLITE_OMIT_TCL_VARIABLE
15257   "OMIT_TCL_VARIABLE",
15258 #endif
15259 #ifdef SQLITE_OMIT_TEMPDB
15260   "OMIT_TEMPDB",
15261 #endif
15262 #ifdef SQLITE_OMIT_TRACE
15263   "OMIT_TRACE",
15264 #endif
15265 #ifdef SQLITE_OMIT_TRIGGER
15266   "OMIT_TRIGGER",
15267 #endif
15268 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
15269   "OMIT_TRUNCATE_OPTIMIZATION",
15270 #endif
15271 #ifdef SQLITE_OMIT_UTF16
15272   "OMIT_UTF16",
15273 #endif
15274 #ifdef SQLITE_OMIT_VACUUM
15275   "OMIT_VACUUM",
15276 #endif
15277 #ifdef SQLITE_OMIT_VIEW
15278   "OMIT_VIEW",
15279 #endif
15280 #ifdef SQLITE_OMIT_VIRTUALTABLE
15281   "OMIT_VIRTUALTABLE",
15282 #endif
15283 #ifdef SQLITE_OMIT_WAL
15284   "OMIT_WAL",
15285 #endif
15286 #ifdef SQLITE_OMIT_WSD
15287   "OMIT_WSD",
15288 #endif
15289 #ifdef SQLITE_OMIT_XFER_OPT
15290   "OMIT_XFER_OPT",
15291 #endif
15292 #ifdef SQLITE_PERFORMANCE_TRACE
15293   "PERFORMANCE_TRACE",
15294 #endif
15295 #ifdef SQLITE_PROXY_DEBUG
15296   "PROXY_DEBUG",
15297 #endif
15298 #ifdef SQLITE_RTREE_INT_ONLY
15299   "RTREE_INT_ONLY",
15300 #endif
15301 #ifdef SQLITE_SECURE_DELETE
15302   "SECURE_DELETE",
15303 #endif
15304 #ifdef SQLITE_SMALL_STACK
15305   "SMALL_STACK",
15306 #endif
15307 #ifdef SQLITE_SOUNDEX
15308   "SOUNDEX",
15309 #endif
15310 #ifdef SQLITE_TCL
15311   "TCL",
15312 #endif
15313 #ifdef SQLITE_TEMP_STORE
15314   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
15315 #endif
15316 #ifdef SQLITE_TEST
15317   "TEST",
15318 #endif
15319 #ifdef SQLITE_THREADSAFE
15320   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
15321 #endif
15322 #ifdef SQLITE_USE_ALLOCA
15323   "USE_ALLOCA",
15324 #endif
15325 #ifdef SQLITE_ZERO_MALLOC
15326   "ZERO_MALLOC"
15327 #endif
15328 };
15329
15330 /*
15331 ** Given the name of a compile-time option, return true if that option
15332 ** was used and false if not.
15333 **
15334 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
15335 ** is not required for a match.
15336 */
15337 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
15338   int i, n;
15339   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
15340   n = sqlite3Strlen30(zOptName);
15341
15342   /* Since ArraySize(azCompileOpt) is normally in single digits, a
15343   ** linear search is adequate.  No need for a binary search. */
15344   for(i=0; i<ArraySize(azCompileOpt); i++){
15345     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
15346        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
15347   }
15348   return 0;
15349 }
15350
15351 /*
15352 ** Return the N-th compile-time option string.  If N is out of range,
15353 ** return a NULL pointer.
15354 */
15355 SQLITE_API const char *sqlite3_compileoption_get(int N){
15356   if( N>=0 && N<ArraySize(azCompileOpt) ){
15357     return azCompileOpt[N];
15358   }
15359   return 0;
15360 }
15361
15362 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
15363
15364 /************** End of ctime.c ***********************************************/
15365 /************** Begin file status.c ******************************************/
15366 /*
15367 ** 2008 June 18
15368 **
15369 ** The author disclaims copyright to this source code.  In place of
15370 ** a legal notice, here is a blessing:
15371 **
15372 **    May you do good and not evil.
15373 **    May you find forgiveness for yourself and forgive others.
15374 **    May you share freely, never taking more than you give.
15375 **
15376 *************************************************************************
15377 **
15378 ** This module implements the sqlite3_status() interface and related
15379 ** functionality.
15380 */
15381 /************** Include vdbeInt.h in the middle of status.c ******************/
15382 /************** Begin file vdbeInt.h *****************************************/
15383 /*
15384 ** 2003 September 6
15385 **
15386 ** The author disclaims copyright to this source code.  In place of
15387 ** a legal notice, here is a blessing:
15388 **
15389 **    May you do good and not evil.
15390 **    May you find forgiveness for yourself and forgive others.
15391 **    May you share freely, never taking more than you give.
15392 **
15393 *************************************************************************
15394 ** This is the header file for information that is private to the
15395 ** VDBE.  This information used to all be at the top of the single
15396 ** source code file "vdbe.c".  When that file became too big (over
15397 ** 6000 lines long) it was split up into several smaller files and
15398 ** this header information was factored out.
15399 */
15400 #ifndef _VDBEINT_H_
15401 #define _VDBEINT_H_
15402
15403 /*
15404 ** SQL is translated into a sequence of instructions to be
15405 ** executed by a virtual machine.  Each instruction is an instance
15406 ** of the following structure.
15407 */
15408 typedef struct VdbeOp Op;
15409
15410 /*
15411 ** Boolean values
15412 */
15413 typedef unsigned char Bool;
15414
15415 /* Opaque type used by code in vdbesort.c */
15416 typedef struct VdbeSorter VdbeSorter;
15417
15418 /* Opaque type used by the explainer */
15419 typedef struct Explain Explain;
15420
15421 /*
15422 ** A cursor is a pointer into a single BTree within a database file.
15423 ** The cursor can seek to a BTree entry with a particular key, or
15424 ** loop over all entries of the Btree.  You can also insert new BTree
15425 ** entries or retrieve the key or data from the entry that the cursor
15426 ** is currently pointing to.
15427 **
15428 ** Every cursor that the virtual machine has open is represented by an
15429 ** instance of the following structure.
15430 */
15431 struct VdbeCursor {
15432   BtCursor *pCursor;    /* The cursor structure of the backend */
15433   Btree *pBt;           /* Separate file holding temporary table */
15434   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
15435   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
15436   int pseudoTableReg;   /* Register holding pseudotable content. */
15437   int nField;           /* Number of fields in the header */
15438   Bool zeroed;          /* True if zeroed out and ready for reuse */
15439   Bool rowidIsValid;    /* True if lastRowid is valid */
15440   Bool atFirst;         /* True if pointing to first entry */
15441   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
15442   Bool nullRow;         /* True if pointing to a row with no data */
15443   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
15444   Bool isTable;         /* True if a table requiring integer keys */
15445   Bool isIndex;         /* True if an index containing keys only - no data */
15446   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
15447   Bool isSorter;        /* True if a new-style sorter */
15448   Bool multiPseudo;     /* Multi-register pseudo-cursor */
15449   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
15450   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
15451   i64 seqCount;         /* Sequence counter */
15452   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
15453   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
15454   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
15455
15456   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
15457   ** OP_IsUnique opcode on this cursor. */
15458   int seekResult;
15459
15460   /* Cached information about the header for the data record that the
15461   ** cursor is currently pointing to.  Only valid if cacheStatus matches
15462   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
15463   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
15464   ** the cache is out of date.
15465   **
15466   ** aRow might point to (ephemeral) data for the current row, or it might
15467   ** be NULL.
15468   */
15469   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
15470   int payloadSize;      /* Total number of bytes in the record */
15471   u32 *aType;           /* Type values for all entries in the record */
15472   u32 *aOffset;         /* Cached offsets to the start of each columns data */
15473   u8 *aRow;             /* Data for the current row, if all on one page */
15474 };
15475 typedef struct VdbeCursor VdbeCursor;
15476
15477 /*
15478 ** When a sub-program is executed (OP_Program), a structure of this type
15479 ** is allocated to store the current value of the program counter, as
15480 ** well as the current memory cell array and various other frame specific
15481 ** values stored in the Vdbe struct. When the sub-program is finished,
15482 ** these values are copied back to the Vdbe from the VdbeFrame structure,
15483 ** restoring the state of the VM to as it was before the sub-program
15484 ** began executing.
15485 **
15486 ** The memory for a VdbeFrame object is allocated and managed by a memory
15487 ** cell in the parent (calling) frame. When the memory cell is deleted or
15488 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
15489 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
15490 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
15491 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
15492 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
15493 ** child frame are released.
15494 **
15495 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
15496 ** set to NULL if the currently executing frame is the main program.
15497 */
15498 typedef struct VdbeFrame VdbeFrame;
15499 struct VdbeFrame {
15500   Vdbe *v;                /* VM this frame belongs to */
15501   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
15502   Op *aOp;                /* Program instructions for parent frame */
15503   Mem *aMem;              /* Array of memory cells for parent frame */
15504   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
15505   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
15506   void *token;            /* Copy of SubProgram.token */
15507   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
15508   u16 nCursor;            /* Number of entries in apCsr */
15509   int pc;                 /* Program Counter in parent (calling) frame */
15510   int nOp;                /* Size of aOp array */
15511   int nMem;               /* Number of entries in aMem */
15512   int nOnceFlag;          /* Number of entries in aOnceFlag */
15513   int nChildMem;          /* Number of memory cells for child frame */
15514   int nChildCsr;          /* Number of cursors for child frame */
15515   int nChange;            /* Statement changes (Vdbe.nChanges)     */
15516 };
15517
15518 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
15519
15520 /*
15521 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
15522 */
15523 #define CACHE_STALE 0
15524
15525 /*
15526 ** Internally, the vdbe manipulates nearly all SQL values as Mem
15527 ** structures. Each Mem struct may cache multiple representations (string,
15528 ** integer etc.) of the same value.
15529 */
15530 struct Mem {
15531   sqlite3 *db;        /* The associated database connection */
15532   char *z;            /* String or BLOB value */
15533   double r;           /* Real value */
15534   union {
15535     i64 i;              /* Integer value used when MEM_Int is set in flags */
15536     int nZero;          /* Used when bit MEM_Zero is set in flags */
15537     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
15538     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
15539     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
15540   } u;
15541   int n;              /* Number of characters in string value, excluding '\0' */
15542   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
15543   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
15544   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
15545 #ifdef SQLITE_DEBUG
15546   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
15547   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
15548 #endif
15549   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
15550   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
15551 };
15552
15553 /* One or more of the following flags are set to indicate the validOK
15554 ** representations of the value stored in the Mem struct.
15555 **
15556 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
15557 ** No other flags may be set in this case.
15558 **
15559 ** If the MEM_Str flag is set then Mem.z points at a string representation.
15560 ** Usually this is encoded in the same unicode encoding as the main
15561 ** database (see below for exceptions). If the MEM_Term flag is also
15562 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
15563 ** flags may coexist with the MEM_Str flag.
15564 */
15565 #define MEM_Null      0x0001   /* Value is NULL */
15566 #define MEM_Str       0x0002   /* Value is a string */
15567 #define MEM_Int       0x0004   /* Value is an integer */
15568 #define MEM_Real      0x0008   /* Value is a real number */
15569 #define MEM_Blob      0x0010   /* Value is a BLOB */
15570 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
15571 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
15572 #define MEM_Invalid   0x0080   /* Value is undefined */
15573 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
15574 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
15575
15576
15577 /* Whenever Mem contains a valid string or blob representation, one of
15578 ** the following flags must be set to determine the memory management
15579 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
15580 ** string is \000 or \u0000 terminated
15581 */
15582 #define MEM_Term      0x0200   /* String rep is nul terminated */
15583 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
15584 #define MEM_Static    0x0800   /* Mem.z points to a static string */
15585 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
15586 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
15587 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
15588 #ifdef SQLITE_OMIT_INCRBLOB
15589   #undef MEM_Zero
15590   #define MEM_Zero 0x0000
15591 #endif
15592
15593 /*
15594 ** Clear any existing type flags from a Mem and replace them with f
15595 */
15596 #define MemSetTypeFlag(p, f) \
15597    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
15598
15599 /*
15600 ** Return true if a memory cell is not marked as invalid.  This macro
15601 ** is for use inside assert() statements only.
15602 */
15603 #ifdef SQLITE_DEBUG
15604 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
15605 #endif
15606
15607
15608 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
15609 ** additional information about auxiliary information bound to arguments
15610 ** of the function.  This is used to implement the sqlite3_get_auxdata()
15611 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
15612 ** that can be associated with a constant argument to a function.  This
15613 ** allows functions such as "regexp" to compile their constant regular
15614 ** expression argument once and reused the compiled code for multiple
15615 ** invocations.
15616 */
15617 struct VdbeFunc {
15618   FuncDef *pFunc;               /* The definition of the function */
15619   int nAux;                     /* Number of entries allocated for apAux[] */
15620   struct AuxData {
15621     void *pAux;                   /* Aux data for the i-th argument */
15622     void (*xDelete)(void *);      /* Destructor for the aux data */
15623   } apAux[1];                   /* One slot for each function argument */
15624 };
15625
15626 /*
15627 ** The "context" argument for a installable function.  A pointer to an
15628 ** instance of this structure is the first argument to the routines used
15629 ** implement the SQL functions.
15630 **
15631 ** There is a typedef for this structure in sqlite.h.  So all routines,
15632 ** even the public interface to SQLite, can use a pointer to this structure.
15633 ** But this file is the only place where the internal details of this
15634 ** structure are known.
15635 **
15636 ** This structure is defined inside of vdbeInt.h because it uses substructures
15637 ** (Mem) which are only defined there.
15638 */
15639 struct sqlite3_context {
15640   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
15641   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
15642   Mem s;                /* The return value is stored here */
15643   Mem *pMem;            /* Memory cell used to store aggregate context */
15644   CollSeq *pColl;       /* Collating sequence */
15645   int isError;          /* Error code returned by the function. */
15646   int skipFlag;         /* Skip skip accumulator loading if true */
15647 };
15648
15649 /*
15650 ** An Explain object accumulates indented output which is helpful
15651 ** in describing recursive data structures.
15652 */
15653 struct Explain {
15654   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
15655   StrAccum str;      /* The string being accumulated */
15656   int nIndent;       /* Number of elements in aIndent */
15657   u16 aIndent[100];  /* Levels of indentation */
15658   char zBase[100];   /* Initial space */
15659 };
15660
15661 /* A bitfield type for use inside of structures.  Always follow with :N where
15662 ** N is the number of bits.
15663 */
15664 typedef unsigned bft;  /* Bit Field Type */
15665
15666 /*
15667 ** An instance of the virtual machine.  This structure contains the complete
15668 ** state of the virtual machine.
15669 **
15670 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
15671 ** is really a pointer to an instance of this structure.
15672 **
15673 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
15674 ** any virtual table method invocations made by the vdbe program. It is
15675 ** set to 2 for xDestroy method calls and 1 for all other methods. This
15676 ** variable is used for two purposes: to allow xDestroy methods to execute
15677 ** "DROP TABLE" statements and to prevent some nasty side effects of
15678 ** malloc failure when SQLite is invoked recursively by a virtual table
15679 ** method function.
15680 */
15681 struct Vdbe {
15682   sqlite3 *db;            /* The database connection that owns this statement */
15683   Op *aOp;                /* Space to hold the virtual machine's program */
15684   Mem *aMem;              /* The memory locations */
15685   Mem **apArg;            /* Arguments to currently executing user function */
15686   Mem *aColName;          /* Column names to return */
15687   Mem *pResultSet;        /* Pointer to an array of results */
15688   int nMem;               /* Number of memory locations currently allocated */
15689   int nOp;                /* Number of instructions in the program */
15690   int nOpAlloc;           /* Number of slots allocated for aOp[] */
15691   int nLabel;             /* Number of labels used */
15692   int *aLabel;            /* Space to hold the labels */
15693   u16 nResColumn;         /* Number of columns in one row of the result set */
15694   u16 nCursor;            /* Number of slots in apCsr[] */
15695   u32 magic;              /* Magic number for sanity checking */
15696   char *zErrMsg;          /* Error message written here */
15697   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
15698   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
15699   Mem *aVar;              /* Values for the OP_Variable opcode. */
15700   char **azVar;           /* Name of variables */
15701   ynVar nVar;             /* Number of entries in aVar[] */
15702   ynVar nzVar;            /* Number of entries in azVar[] */
15703   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
15704   int pc;                 /* The program counter */
15705   int rc;                 /* Value to return */
15706   u8 errorAction;         /* Recovery action to do in case of an error */
15707   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
15708   bft explain:2;          /* True if EXPLAIN present on SQL command */
15709   bft inVtabMethod:2;     /* See comments above */
15710   bft changeCntOn:1;      /* True to update the change-counter */
15711   bft expired:1;          /* True if the VM needs to be recompiled */
15712   bft runOnlyOnce:1;      /* Automatically expire on reset */
15713   bft usesStmtJournal:1;  /* True if uses a statement journal */
15714   bft readOnly:1;         /* True for read-only statements */
15715   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
15716   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
15717   int nChange;            /* Number of db changes made since last reset */
15718   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
15719   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
15720   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
15721   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
15722 #ifndef SQLITE_OMIT_TRACE
15723   i64 startTime;          /* Time when query started - used for profiling */
15724 #endif
15725   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
15726   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
15727   char *zSql;             /* Text of the SQL statement that generated this */
15728   void *pFree;            /* Free this when deleting the vdbe */
15729 #ifdef SQLITE_DEBUG
15730   FILE *trace;            /* Write an execution trace here, if not NULL */
15731 #endif
15732 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
15733   Explain *pExplain;      /* The explainer */
15734   char *zExplain;         /* Explanation of data structures */
15735 #endif
15736   VdbeFrame *pFrame;      /* Parent frame */
15737   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
15738   int nFrame;             /* Number of frames in pFrame list */
15739   u32 expmask;            /* Binding to these vars invalidates VM */
15740   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
15741   int nOnceFlag;          /* Size of array aOnceFlag[] */
15742   u8 *aOnceFlag;          /* Flags for OP_Once */
15743 };
15744
15745 /*
15746 ** The following are allowed values for Vdbe.magic
15747 */
15748 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
15749 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
15750 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
15751 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
15752
15753 /*
15754 ** Function prototypes
15755 */
15756 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
15757 void sqliteVdbePopStack(Vdbe*,int);
15758 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
15759 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
15760 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
15761 #endif
15762 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
15763 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
15764 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
15765 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
15766 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
15767
15768 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
15769 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
15770 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
15771 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
15772 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
15773 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
15774 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
15775 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
15776 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
15777 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
15778 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
15779 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
15780 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
15781 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
15782 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
15783 #ifdef SQLITE_OMIT_FLOATING_POINT
15784 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
15785 #else
15786 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
15787 #endif
15788 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
15789 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
15790 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
15791 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
15792 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
15793 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
15794 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
15795 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
15796 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
15797 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
15798 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
15799 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
15800 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
15801 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
15802 #define VdbeMemRelease(X)  \
15803   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
15804     sqlite3VdbeMemReleaseExternal(X);
15805 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
15806 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
15807 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
15808 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
15809 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
15810 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
15811 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
15812 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
15813
15814 #ifdef SQLITE_OMIT_MERGE_SORT
15815 # define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
15816 # define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
15817 # define sqlite3VdbeSorterClose(Y,Z)
15818 # define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
15819 # define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
15820 # define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
15821 # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
15822 #else
15823 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
15824 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
15825 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
15826 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
15827 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
15828 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
15829 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
15830 #endif
15831
15832 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
15833 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
15834 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
15835 #else
15836 # define sqlite3VdbeEnter(X)
15837 # define sqlite3VdbeLeave(X)
15838 #endif
15839
15840 #ifdef SQLITE_DEBUG
15841 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
15842 #endif
15843
15844 #ifndef SQLITE_OMIT_FOREIGN_KEY
15845 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
15846 #else
15847 # define sqlite3VdbeCheckFk(p,i) 0
15848 #endif
15849
15850 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
15851 #ifdef SQLITE_DEBUG
15852 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
15853 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
15854 #endif
15855 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
15856
15857 #ifndef SQLITE_OMIT_INCRBLOB
15858 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
15859   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
15860 #else
15861   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
15862   #define ExpandBlob(P) SQLITE_OK
15863 #endif
15864
15865 #endif /* !defined(_VDBEINT_H_) */
15866
15867 /************** End of vdbeInt.h *********************************************/
15868 /************** Continuing where we left off in status.c *********************/
15869
15870 /*
15871 ** Variables in which to record status information.
15872 */
15873 typedef struct sqlite3StatType sqlite3StatType;
15874 static SQLITE_WSD struct sqlite3StatType {
15875   int nowValue[10];         /* Current value */
15876   int mxValue[10];          /* Maximum value */
15877 } sqlite3Stat = { {0,}, {0,} };
15878
15879
15880 /* The "wsdStat" macro will resolve to the status information
15881 ** state vector.  If writable static data is unsupported on the target,
15882 ** we have to locate the state vector at run-time.  In the more common
15883 ** case where writable static data is supported, wsdStat can refer directly
15884 ** to the "sqlite3Stat" state vector declared above.
15885 */
15886 #ifdef SQLITE_OMIT_WSD
15887 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
15888 # define wsdStat x[0]
15889 #else
15890 # define wsdStatInit
15891 # define wsdStat sqlite3Stat
15892 #endif
15893
15894 /*
15895 ** Return the current value of a status parameter.
15896 */
15897 SQLITE_PRIVATE int sqlite3StatusValue(int op){
15898   wsdStatInit;
15899   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15900   return wsdStat.nowValue[op];
15901 }
15902
15903 /*
15904 ** Add N to the value of a status record.  It is assumed that the
15905 ** caller holds appropriate locks.
15906 */
15907 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
15908   wsdStatInit;
15909   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15910   wsdStat.nowValue[op] += N;
15911   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15912     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15913   }
15914 }
15915
15916 /*
15917 ** Set the value of a status to X.
15918 */
15919 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
15920   wsdStatInit;
15921   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15922   wsdStat.nowValue[op] = X;
15923   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15924     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15925   }
15926 }
15927
15928 /*
15929 ** Query status information.
15930 **
15931 ** This implementation assumes that reading or writing an aligned
15932 ** 32-bit integer is an atomic operation.  If that assumption is not true,
15933 ** then this routine is not threadsafe.
15934 */
15935 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
15936   wsdStatInit;
15937   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
15938     return SQLITE_MISUSE_BKPT;
15939   }
15940   *pCurrent = wsdStat.nowValue[op];
15941   *pHighwater = wsdStat.mxValue[op];
15942   if( resetFlag ){
15943     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15944   }
15945   return SQLITE_OK;
15946 }
15947
15948 /*
15949 ** Query status information for a single database connection
15950 */
15951 SQLITE_API int sqlite3_db_status(
15952   sqlite3 *db,          /* The database connection whose status is desired */
15953   int op,               /* Status verb */
15954   int *pCurrent,        /* Write current value here */
15955   int *pHighwater,      /* Write high-water mark here */
15956   int resetFlag         /* Reset high-water mark if true */
15957 ){
15958   int rc = SQLITE_OK;   /* Return code */
15959   sqlite3_mutex_enter(db->mutex);
15960   switch( op ){
15961     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
15962       *pCurrent = db->lookaside.nOut;
15963       *pHighwater = db->lookaside.mxOut;
15964       if( resetFlag ){
15965         db->lookaside.mxOut = db->lookaside.nOut;
15966       }
15967       break;
15968     }
15969
15970     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
15971     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
15972     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
15973       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
15974       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
15975       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
15976       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
15977       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
15978       *pCurrent = 0;
15979       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
15980       if( resetFlag ){
15981         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
15982       }
15983       break;
15984     }
15985
15986     /*
15987     ** Return an approximation for the amount of memory currently used
15988     ** by all pagers associated with the given database connection.  The
15989     ** highwater mark is meaningless and is returned as zero.
15990     */
15991     case SQLITE_DBSTATUS_CACHE_USED: {
15992       int totalUsed = 0;
15993       int i;
15994       sqlite3BtreeEnterAll(db);
15995       for(i=0; i<db->nDb; i++){
15996         Btree *pBt = db->aDb[i].pBt;
15997         if( pBt ){
15998           Pager *pPager = sqlite3BtreePager(pBt);
15999           totalUsed += sqlite3PagerMemUsed(pPager);
16000         }
16001       }
16002       sqlite3BtreeLeaveAll(db);
16003       *pCurrent = totalUsed;
16004       *pHighwater = 0;
16005       break;
16006     }
16007
16008     /*
16009     ** *pCurrent gets an accurate estimate of the amount of memory used
16010     ** to store the schema for all databases (main, temp, and any ATTACHed
16011     ** databases.  *pHighwater is set to zero.
16012     */
16013     case SQLITE_DBSTATUS_SCHEMA_USED: {
16014       int i;                      /* Used to iterate through schemas */
16015       int nByte = 0;              /* Used to accumulate return value */
16016
16017       sqlite3BtreeEnterAll(db);
16018       db->pnBytesFreed = &nByte;
16019       for(i=0; i<db->nDb; i++){
16020         Schema *pSchema = db->aDb[i].pSchema;
16021         if( ALWAYS(pSchema!=0) ){
16022           HashElem *p;
16023
16024           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
16025               pSchema->tblHash.count
16026             + pSchema->trigHash.count
16027             + pSchema->idxHash.count
16028             + pSchema->fkeyHash.count
16029           );
16030           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
16031           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
16032           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
16033           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
16034
16035           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
16036             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
16037           }
16038           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
16039             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
16040           }
16041         }
16042       }
16043       db->pnBytesFreed = 0;
16044       sqlite3BtreeLeaveAll(db);
16045
16046       *pHighwater = 0;
16047       *pCurrent = nByte;
16048       break;
16049     }
16050
16051     /*
16052     ** *pCurrent gets an accurate estimate of the amount of memory used
16053     ** to store all prepared statements.
16054     ** *pHighwater is set to zero.
16055     */
16056     case SQLITE_DBSTATUS_STMT_USED: {
16057       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
16058       int nByte = 0;              /* Used to accumulate return value */
16059
16060       db->pnBytesFreed = &nByte;
16061       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
16062         sqlite3VdbeClearObject(db, pVdbe);
16063         sqlite3DbFree(db, pVdbe);
16064       }
16065       db->pnBytesFreed = 0;
16066
16067       *pHighwater = 0;
16068       *pCurrent = nByte;
16069
16070       break;
16071     }
16072
16073     /*
16074     ** Set *pCurrent to the total cache hits or misses encountered by all
16075     ** pagers the database handle is connected to. *pHighwater is always set
16076     ** to zero.
16077     */
16078     case SQLITE_DBSTATUS_CACHE_HIT:
16079     case SQLITE_DBSTATUS_CACHE_MISS:
16080     case SQLITE_DBSTATUS_CACHE_WRITE:{
16081       int i;
16082       int nRet = 0;
16083       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
16084       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
16085
16086       for(i=0; i<db->nDb; i++){
16087         if( db->aDb[i].pBt ){
16088           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
16089           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
16090         }
16091       }
16092       *pHighwater = 0;
16093       *pCurrent = nRet;
16094       break;
16095     }
16096
16097     default: {
16098       rc = SQLITE_ERROR;
16099     }
16100   }
16101   sqlite3_mutex_leave(db->mutex);
16102   return rc;
16103 }
16104
16105 /************** End of status.c **********************************************/
16106 /************** Begin file date.c ********************************************/
16107 /*
16108 ** 2003 October 31
16109 **
16110 ** The author disclaims copyright to this source code.  In place of
16111 ** a legal notice, here is a blessing:
16112 **
16113 **    May you do good and not evil.
16114 **    May you find forgiveness for yourself and forgive others.
16115 **    May you share freely, never taking more than you give.
16116 **
16117 *************************************************************************
16118 ** This file contains the C functions that implement date and time
16119 ** functions for SQLite.
16120 **
16121 ** There is only one exported symbol in this file - the function
16122 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
16123 ** All other code has file scope.
16124 **
16125 ** SQLite processes all times and dates as Julian Day numbers.  The
16126 ** dates and times are stored as the number of days since noon
16127 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
16128 ** calendar system.
16129 **
16130 ** 1970-01-01 00:00:00 is JD 2440587.5
16131 ** 2000-01-01 00:00:00 is JD 2451544.5
16132 **
16133 ** This implemention requires years to be expressed as a 4-digit number
16134 ** which means that only dates between 0000-01-01 and 9999-12-31 can
16135 ** be represented, even though julian day numbers allow a much wider
16136 ** range of dates.
16137 **
16138 ** The Gregorian calendar system is used for all dates and times,
16139 ** even those that predate the Gregorian calendar.  Historians usually
16140 ** use the Julian calendar for dates prior to 1582-10-15 and for some
16141 ** dates afterwards, depending on locale.  Beware of this difference.
16142 **
16143 ** The conversion algorithms are implemented based on descriptions
16144 ** in the following text:
16145 **
16146 **      Jean Meeus
16147 **      Astronomical Algorithms, 2nd Edition, 1998
16148 **      ISBM 0-943396-61-1
16149 **      Willmann-Bell, Inc
16150 **      Richmond, Virginia (USA)
16151 */
16152 /* #include <stdlib.h> */
16153 /* #include <assert.h> */
16154 #include <time.h>
16155
16156 #ifndef SQLITE_OMIT_DATETIME_FUNCS
16157
16158
16159 /*
16160 ** A structure for holding a single date and time.
16161 */
16162 typedef struct DateTime DateTime;
16163 struct DateTime {
16164   sqlite3_int64 iJD; /* The julian day number times 86400000 */
16165   int Y, M, D;       /* Year, month, and day */
16166   int h, m;          /* Hour and minutes */
16167   int tz;            /* Timezone offset in minutes */
16168   double s;          /* Seconds */
16169   char validYMD;     /* True (1) if Y,M,D are valid */
16170   char validHMS;     /* True (1) if h,m,s are valid */
16171   char validJD;      /* True (1) if iJD is valid */
16172   char validTZ;      /* True (1) if tz is valid */
16173 };
16174
16175
16176 /*
16177 ** Convert zDate into one or more integers.  Additional arguments
16178 ** come in groups of 5 as follows:
16179 **
16180 **       N       number of digits in the integer
16181 **       min     minimum allowed value of the integer
16182 **       max     maximum allowed value of the integer
16183 **       nextC   first character after the integer
16184 **       pVal    where to write the integers value.
16185 **
16186 ** Conversions continue until one with nextC==0 is encountered.
16187 ** The function returns the number of successful conversions.
16188 */
16189 static int getDigits(const char *zDate, ...){
16190   va_list ap;
16191   int val;
16192   int N;
16193   int min;
16194   int max;
16195   int nextC;
16196   int *pVal;
16197   int cnt = 0;
16198   va_start(ap, zDate);
16199   do{
16200     N = va_arg(ap, int);
16201     min = va_arg(ap, int);
16202     max = va_arg(ap, int);
16203     nextC = va_arg(ap, int);
16204     pVal = va_arg(ap, int*);
16205     val = 0;
16206     while( N-- ){
16207       if( !sqlite3Isdigit(*zDate) ){
16208         goto end_getDigits;
16209       }
16210       val = val*10 + *zDate - '0';
16211       zDate++;
16212     }
16213     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
16214       goto end_getDigits;
16215     }
16216     *pVal = val;
16217     zDate++;
16218     cnt++;
16219   }while( nextC );
16220 end_getDigits:
16221   va_end(ap);
16222   return cnt;
16223 }
16224
16225 /*
16226 ** Parse a timezone extension on the end of a date-time.
16227 ** The extension is of the form:
16228 **
16229 **        (+/-)HH:MM
16230 **
16231 ** Or the "zulu" notation:
16232 **
16233 **        Z
16234 **
16235 ** If the parse is successful, write the number of minutes
16236 ** of change in p->tz and return 0.  If a parser error occurs,
16237 ** return non-zero.
16238 **
16239 ** A missing specifier is not considered an error.
16240 */
16241 static int parseTimezone(const char *zDate, DateTime *p){
16242   int sgn = 0;
16243   int nHr, nMn;
16244   int c;
16245   while( sqlite3Isspace(*zDate) ){ zDate++; }
16246   p->tz = 0;
16247   c = *zDate;
16248   if( c=='-' ){
16249     sgn = -1;
16250   }else if( c=='+' ){
16251     sgn = +1;
16252   }else if( c=='Z' || c=='z' ){
16253     zDate++;
16254     goto zulu_time;
16255   }else{
16256     return c!=0;
16257   }
16258   zDate++;
16259   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
16260     return 1;
16261   }
16262   zDate += 5;
16263   p->tz = sgn*(nMn + nHr*60);
16264 zulu_time:
16265   while( sqlite3Isspace(*zDate) ){ zDate++; }
16266   return *zDate!=0;
16267 }
16268
16269 /*
16270 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
16271 ** The HH, MM, and SS must each be exactly 2 digits.  The
16272 ** fractional seconds FFFF can be one or more digits.
16273 **
16274 ** Return 1 if there is a parsing error and 0 on success.
16275 */
16276 static int parseHhMmSs(const char *zDate, DateTime *p){
16277   int h, m, s;
16278   double ms = 0.0;
16279   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
16280     return 1;
16281   }
16282   zDate += 5;
16283   if( *zDate==':' ){
16284     zDate++;
16285     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
16286       return 1;
16287     }
16288     zDate += 2;
16289     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
16290       double rScale = 1.0;
16291       zDate++;
16292       while( sqlite3Isdigit(*zDate) ){
16293         ms = ms*10.0 + *zDate - '0';
16294         rScale *= 10.0;
16295         zDate++;
16296       }
16297       ms /= rScale;
16298     }
16299   }else{
16300     s = 0;
16301   }
16302   p->validJD = 0;
16303   p->validHMS = 1;
16304   p->h = h;
16305   p->m = m;
16306   p->s = s + ms;
16307   if( parseTimezone(zDate, p) ) return 1;
16308   p->validTZ = (p->tz!=0)?1:0;
16309   return 0;
16310 }
16311
16312 /*
16313 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
16314 ** that the YYYY-MM-DD is according to the Gregorian calendar.
16315 **
16316 ** Reference:  Meeus page 61
16317 */
16318 static void computeJD(DateTime *p){
16319   int Y, M, D, A, B, X1, X2;
16320
16321   if( p->validJD ) return;
16322   if( p->validYMD ){
16323     Y = p->Y;
16324     M = p->M;
16325     D = p->D;
16326   }else{
16327     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
16328     M = 1;
16329     D = 1;
16330   }
16331   if( M<=2 ){
16332     Y--;
16333     M += 12;
16334   }
16335   A = Y/100;
16336   B = 2 - A + (A/4);
16337   X1 = 36525*(Y+4716)/100;
16338   X2 = 306001*(M+1)/10000;
16339   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
16340   p->validJD = 1;
16341   if( p->validHMS ){
16342     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
16343     if( p->validTZ ){
16344       p->iJD -= p->tz*60000;
16345       p->validYMD = 0;
16346       p->validHMS = 0;
16347       p->validTZ = 0;
16348     }
16349   }
16350 }
16351
16352 /*
16353 ** Parse dates of the form
16354 **
16355 **     YYYY-MM-DD HH:MM:SS.FFF
16356 **     YYYY-MM-DD HH:MM:SS
16357 **     YYYY-MM-DD HH:MM
16358 **     YYYY-MM-DD
16359 **
16360 ** Write the result into the DateTime structure and return 0
16361 ** on success and 1 if the input string is not a well-formed
16362 ** date.
16363 */
16364 static int parseYyyyMmDd(const char *zDate, DateTime *p){
16365   int Y, M, D, neg;
16366
16367   if( zDate[0]=='-' ){
16368     zDate++;
16369     neg = 1;
16370   }else{
16371     neg = 0;
16372   }
16373   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
16374     return 1;
16375   }
16376   zDate += 10;
16377   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
16378   if( parseHhMmSs(zDate, p)==0 ){
16379     /* We got the time */
16380   }else if( *zDate==0 ){
16381     p->validHMS = 0;
16382   }else{
16383     return 1;
16384   }
16385   p->validJD = 0;
16386   p->validYMD = 1;
16387   p->Y = neg ? -Y : Y;
16388   p->M = M;
16389   p->D = D;
16390   if( p->validTZ ){
16391     computeJD(p);
16392   }
16393   return 0;
16394 }
16395
16396 /*
16397 ** Set the time to the current time reported by the VFS.
16398 **
16399 ** Return the number of errors.
16400 */
16401 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
16402   sqlite3 *db = sqlite3_context_db_handle(context);
16403   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
16404     p->validJD = 1;
16405     return 0;
16406   }else{
16407     return 1;
16408   }
16409 }
16410
16411 /*
16412 ** Attempt to parse the given string into a Julian Day Number.  Return
16413 ** the number of errors.
16414 **
16415 ** The following are acceptable forms for the input string:
16416 **
16417 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
16418 **      DDDD.DD
16419 **      now
16420 **
16421 ** In the first form, the +/-HH:MM is always optional.  The fractional
16422 ** seconds extension (the ".FFF") is optional.  The seconds portion
16423 ** (":SS.FFF") is option.  The year and date can be omitted as long
16424 ** as there is a time string.  The time string can be omitted as long
16425 ** as there is a year and date.
16426 */
16427 static int parseDateOrTime(
16428   sqlite3_context *context,
16429   const char *zDate,
16430   DateTime *p
16431 ){
16432   double r;
16433   if( parseYyyyMmDd(zDate,p)==0 ){
16434     return 0;
16435   }else if( parseHhMmSs(zDate, p)==0 ){
16436     return 0;
16437   }else if( sqlite3StrICmp(zDate,"now")==0){
16438     return setDateTimeToCurrent(context, p);
16439   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
16440     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
16441     p->validJD = 1;
16442     return 0;
16443   }
16444   return 1;
16445 }
16446
16447 /*
16448 ** Compute the Year, Month, and Day from the julian day number.
16449 */
16450 static void computeYMD(DateTime *p){
16451   int Z, A, B, C, D, E, X1;
16452   if( p->validYMD ) return;
16453   if( !p->validJD ){
16454     p->Y = 2000;
16455     p->M = 1;
16456     p->D = 1;
16457   }else{
16458     Z = (int)((p->iJD + 43200000)/86400000);
16459     A = (int)((Z - 1867216.25)/36524.25);
16460     A = Z + 1 + A - (A/4);
16461     B = A + 1524;
16462     C = (int)((B - 122.1)/365.25);
16463     D = (36525*C)/100;
16464     E = (int)((B-D)/30.6001);
16465     X1 = (int)(30.6001*E);
16466     p->D = B - D - X1;
16467     p->M = E<14 ? E-1 : E-13;
16468     p->Y = p->M>2 ? C - 4716 : C - 4715;
16469   }
16470   p->validYMD = 1;
16471 }
16472
16473 /*
16474 ** Compute the Hour, Minute, and Seconds from the julian day number.
16475 */
16476 static void computeHMS(DateTime *p){
16477   int s;
16478   if( p->validHMS ) return;
16479   computeJD(p);
16480   s = (int)((p->iJD + 43200000) % 86400000);
16481   p->s = s/1000.0;
16482   s = (int)p->s;
16483   p->s -= s;
16484   p->h = s/3600;
16485   s -= p->h*3600;
16486   p->m = s/60;
16487   p->s += s - p->m*60;
16488   p->validHMS = 1;
16489 }
16490
16491 /*
16492 ** Compute both YMD and HMS
16493 */
16494 static void computeYMD_HMS(DateTime *p){
16495   computeYMD(p);
16496   computeHMS(p);
16497 }
16498
16499 /*
16500 ** Clear the YMD and HMS and the TZ
16501 */
16502 static void clearYMD_HMS_TZ(DateTime *p){
16503   p->validYMD = 0;
16504   p->validHMS = 0;
16505   p->validTZ = 0;
16506 }
16507
16508 /*
16509 ** On recent Windows platforms, the localtime_s() function is available
16510 ** as part of the "Secure CRT". It is essentially equivalent to
16511 ** localtime_r() available under most POSIX platforms, except that the
16512 ** order of the parameters is reversed.
16513 **
16514 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
16515 **
16516 ** If the user has not indicated to use localtime_r() or localtime_s()
16517 ** already, check for an MSVC build environment that provides
16518 ** localtime_s().
16519 */
16520 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
16521      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
16522 #define HAVE_LOCALTIME_S 1
16523 #endif
16524
16525 #ifndef SQLITE_OMIT_LOCALTIME
16526 /*
16527 ** The following routine implements the rough equivalent of localtime_r()
16528 ** using whatever operating-system specific localtime facility that
16529 ** is available.  This routine returns 0 on success and
16530 ** non-zero on any kind of error.
16531 **
16532 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
16533 ** routine will always fail.
16534 */
16535 static int osLocaltime(time_t *t, struct tm *pTm){
16536   int rc;
16537 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
16538       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
16539   struct tm *pX;
16540 #if SQLITE_THREADSAFE>0
16541   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16542 #endif
16543   sqlite3_mutex_enter(mutex);
16544   pX = localtime(t);
16545 #ifndef SQLITE_OMIT_BUILTIN_TEST
16546   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
16547 #endif
16548   if( pX ) *pTm = *pX;
16549   sqlite3_mutex_leave(mutex);
16550   rc = pX==0;
16551 #else
16552 #ifndef SQLITE_OMIT_BUILTIN_TEST
16553   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
16554 #endif
16555 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
16556   rc = localtime_r(t, pTm)==0;
16557 #else
16558   rc = localtime_s(pTm, t);
16559 #endif /* HAVE_LOCALTIME_R */
16560 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
16561   return rc;
16562 }
16563 #endif /* SQLITE_OMIT_LOCALTIME */
16564
16565
16566 #ifndef SQLITE_OMIT_LOCALTIME
16567 /*
16568 ** Compute the difference (in milliseconds) between localtime and UTC
16569 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
16570 ** return this value and set *pRc to SQLITE_OK.
16571 **
16572 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
16573 ** is undefined in this case.
16574 */
16575 static sqlite3_int64 localtimeOffset(
16576   DateTime *p,                    /* Date at which to calculate offset */
16577   sqlite3_context *pCtx,          /* Write error here if one occurs */
16578   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
16579 ){
16580   DateTime x, y;
16581   time_t t;
16582   struct tm sLocal;
16583
16584   /* Initialize the contents of sLocal to avoid a compiler warning. */
16585   memset(&sLocal, 0, sizeof(sLocal));
16586
16587   x = *p;
16588   computeYMD_HMS(&x);
16589   if( x.Y<1971 || x.Y>=2038 ){
16590     x.Y = 2000;
16591     x.M = 1;
16592     x.D = 1;
16593     x.h = 0;
16594     x.m = 0;
16595     x.s = 0.0;
16596   } else {
16597     int s = (int)(x.s + 0.5);
16598     x.s = s;
16599   }
16600   x.tz = 0;
16601   x.validJD = 0;
16602   computeJD(&x);
16603   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
16604   if( osLocaltime(&t, &sLocal) ){
16605     sqlite3_result_error(pCtx, "local time unavailable", -1);
16606     *pRc = SQLITE_ERROR;
16607     return 0;
16608   }
16609   y.Y = sLocal.tm_year + 1900;
16610   y.M = sLocal.tm_mon + 1;
16611   y.D = sLocal.tm_mday;
16612   y.h = sLocal.tm_hour;
16613   y.m = sLocal.tm_min;
16614   y.s = sLocal.tm_sec;
16615   y.validYMD = 1;
16616   y.validHMS = 1;
16617   y.validJD = 0;
16618   y.validTZ = 0;
16619   computeJD(&y);
16620   *pRc = SQLITE_OK;
16621   return y.iJD - x.iJD;
16622 }
16623 #endif /* SQLITE_OMIT_LOCALTIME */
16624
16625 /*
16626 ** Process a modifier to a date-time stamp.  The modifiers are
16627 ** as follows:
16628 **
16629 **     NNN days
16630 **     NNN hours
16631 **     NNN minutes
16632 **     NNN.NNNN seconds
16633 **     NNN months
16634 **     NNN years
16635 **     start of month
16636 **     start of year
16637 **     start of week
16638 **     start of day
16639 **     weekday N
16640 **     unixepoch
16641 **     localtime
16642 **     utc
16643 **
16644 ** Return 0 on success and 1 if there is any kind of error. If the error
16645 ** is in a system call (i.e. localtime()), then an error message is written
16646 ** to context pCtx. If the error is an unrecognized modifier, no error is
16647 ** written to pCtx.
16648 */
16649 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
16650   int rc = 1;
16651   int n;
16652   double r;
16653   char *z, zBuf[30];
16654   z = zBuf;
16655   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
16656     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
16657   }
16658   z[n] = 0;
16659   switch( z[0] ){
16660 #ifndef SQLITE_OMIT_LOCALTIME
16661     case 'l': {
16662       /*    localtime
16663       **
16664       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
16665       ** show local time.
16666       */
16667       if( strcmp(z, "localtime")==0 ){
16668         computeJD(p);
16669         p->iJD += localtimeOffset(p, pCtx, &rc);
16670         clearYMD_HMS_TZ(p);
16671       }
16672       break;
16673     }
16674 #endif
16675     case 'u': {
16676       /*
16677       **    unixepoch
16678       **
16679       ** Treat the current value of p->iJD as the number of
16680       ** seconds since 1970.  Convert to a real julian day number.
16681       */
16682       if( strcmp(z, "unixepoch")==0 && p->validJD ){
16683         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
16684         clearYMD_HMS_TZ(p);
16685         rc = 0;
16686       }
16687 #ifndef SQLITE_OMIT_LOCALTIME
16688       else if( strcmp(z, "utc")==0 ){
16689         sqlite3_int64 c1;
16690         computeJD(p);
16691         c1 = localtimeOffset(p, pCtx, &rc);
16692         if( rc==SQLITE_OK ){
16693           p->iJD -= c1;
16694           clearYMD_HMS_TZ(p);
16695           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
16696         }
16697       }
16698 #endif
16699       break;
16700     }
16701     case 'w': {
16702       /*
16703       **    weekday N
16704       **
16705       ** Move the date to the same time on the next occurrence of
16706       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
16707       ** date is already on the appropriate weekday, this is a no-op.
16708       */
16709       if( strncmp(z, "weekday ", 8)==0
16710                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
16711                && (n=(int)r)==r && n>=0 && r<7 ){
16712         sqlite3_int64 Z;
16713         computeYMD_HMS(p);
16714         p->validTZ = 0;
16715         p->validJD = 0;
16716         computeJD(p);
16717         Z = ((p->iJD + 129600000)/86400000) % 7;
16718         if( Z>n ) Z -= 7;
16719         p->iJD += (n - Z)*86400000;
16720         clearYMD_HMS_TZ(p);
16721         rc = 0;
16722       }
16723       break;
16724     }
16725     case 's': {
16726       /*
16727       **    start of TTTTT
16728       **
16729       ** Move the date backwards to the beginning of the current day,
16730       ** or month or year.
16731       */
16732       if( strncmp(z, "start of ", 9)!=0 ) break;
16733       z += 9;
16734       computeYMD(p);
16735       p->validHMS = 1;
16736       p->h = p->m = 0;
16737       p->s = 0.0;
16738       p->validTZ = 0;
16739       p->validJD = 0;
16740       if( strcmp(z,"month")==0 ){
16741         p->D = 1;
16742         rc = 0;
16743       }else if( strcmp(z,"year")==0 ){
16744         computeYMD(p);
16745         p->M = 1;
16746         p->D = 1;
16747         rc = 0;
16748       }else if( strcmp(z,"day")==0 ){
16749         rc = 0;
16750       }
16751       break;
16752     }
16753     case '+':
16754     case '-':
16755     case '0':
16756     case '1':
16757     case '2':
16758     case '3':
16759     case '4':
16760     case '5':
16761     case '6':
16762     case '7':
16763     case '8':
16764     case '9': {
16765       double rRounder;
16766       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
16767       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
16768         rc = 1;
16769         break;
16770       }
16771       if( z[n]==':' ){
16772         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
16773         ** specified number of hours, minutes, seconds, and fractional seconds
16774         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
16775         ** omitted.
16776         */
16777         const char *z2 = z;
16778         DateTime tx;
16779         sqlite3_int64 day;
16780         if( !sqlite3Isdigit(*z2) ) z2++;
16781         memset(&tx, 0, sizeof(tx));
16782         if( parseHhMmSs(z2, &tx) ) break;
16783         computeJD(&tx);
16784         tx.iJD -= 43200000;
16785         day = tx.iJD/86400000;
16786         tx.iJD -= day*86400000;
16787         if( z[0]=='-' ) tx.iJD = -tx.iJD;
16788         computeJD(p);
16789         clearYMD_HMS_TZ(p);
16790         p->iJD += tx.iJD;
16791         rc = 0;
16792         break;
16793       }
16794       z += n;
16795       while( sqlite3Isspace(*z) ) z++;
16796       n = sqlite3Strlen30(z);
16797       if( n>10 || n<3 ) break;
16798       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
16799       computeJD(p);
16800       rc = 0;
16801       rRounder = r<0 ? -0.5 : +0.5;
16802       if( n==3 && strcmp(z,"day")==0 ){
16803         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
16804       }else if( n==4 && strcmp(z,"hour")==0 ){
16805         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
16806       }else if( n==6 && strcmp(z,"minute")==0 ){
16807         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
16808       }else if( n==6 && strcmp(z,"second")==0 ){
16809         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
16810       }else if( n==5 && strcmp(z,"month")==0 ){
16811         int x, y;
16812         computeYMD_HMS(p);
16813         p->M += (int)r;
16814         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
16815         p->Y += x;
16816         p->M -= x*12;
16817         p->validJD = 0;
16818         computeJD(p);
16819         y = (int)r;
16820         if( y!=r ){
16821           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
16822         }
16823       }else if( n==4 && strcmp(z,"year")==0 ){
16824         int y = (int)r;
16825         computeYMD_HMS(p);
16826         p->Y += y;
16827         p->validJD = 0;
16828         computeJD(p);
16829         if( y!=r ){
16830           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
16831         }
16832       }else{
16833         rc = 1;
16834       }
16835       clearYMD_HMS_TZ(p);
16836       break;
16837     }
16838     default: {
16839       break;
16840     }
16841   }
16842   return rc;
16843 }
16844
16845 /*
16846 ** Process time function arguments.  argv[0] is a date-time stamp.
16847 ** argv[1] and following are modifiers.  Parse them all and write
16848 ** the resulting time into the DateTime structure p.  Return 0
16849 ** on success and 1 if there are any errors.
16850 **
16851 ** If there are zero parameters (if even argv[0] is undefined)
16852 ** then assume a default value of "now" for argv[0].
16853 */
16854 static int isDate(
16855   sqlite3_context *context,
16856   int argc,
16857   sqlite3_value **argv,
16858   DateTime *p
16859 ){
16860   int i;
16861   const unsigned char *z;
16862   int eType;
16863   memset(p, 0, sizeof(*p));
16864   if( argc==0 ){
16865     return setDateTimeToCurrent(context, p);
16866   }
16867   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
16868                    || eType==SQLITE_INTEGER ){
16869     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
16870     p->validJD = 1;
16871   }else{
16872     z = sqlite3_value_text(argv[0]);
16873     if( !z || parseDateOrTime(context, (char*)z, p) ){
16874       return 1;
16875     }
16876   }
16877   for(i=1; i<argc; i++){
16878     z = sqlite3_value_text(argv[i]);
16879     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
16880   }
16881   return 0;
16882 }
16883
16884
16885 /*
16886 ** The following routines implement the various date and time functions
16887 ** of SQLite.
16888 */
16889
16890 /*
16891 **    julianday( TIMESTRING, MOD, MOD, ...)
16892 **
16893 ** Return the julian day number of the date specified in the arguments
16894 */
16895 static void juliandayFunc(
16896   sqlite3_context *context,
16897   int argc,
16898   sqlite3_value **argv
16899 ){
16900   DateTime x;
16901   if( isDate(context, argc, argv, &x)==0 ){
16902     computeJD(&x);
16903     sqlite3_result_double(context, x.iJD/86400000.0);
16904   }
16905 }
16906
16907 /*
16908 **    datetime( TIMESTRING, MOD, MOD, ...)
16909 **
16910 ** Return YYYY-MM-DD HH:MM:SS
16911 */
16912 static void datetimeFunc(
16913   sqlite3_context *context,
16914   int argc,
16915   sqlite3_value **argv
16916 ){
16917   DateTime x;
16918   if( isDate(context, argc, argv, &x)==0 ){
16919     char zBuf[100];
16920     computeYMD_HMS(&x);
16921     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
16922                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
16923     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16924   }
16925 }
16926
16927 /*
16928 **    time( TIMESTRING, MOD, MOD, ...)
16929 **
16930 ** Return HH:MM:SS
16931 */
16932 static void timeFunc(
16933   sqlite3_context *context,
16934   int argc,
16935   sqlite3_value **argv
16936 ){
16937   DateTime x;
16938   if( isDate(context, argc, argv, &x)==0 ){
16939     char zBuf[100];
16940     computeHMS(&x);
16941     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
16942     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16943   }
16944 }
16945
16946 /*
16947 **    date( TIMESTRING, MOD, MOD, ...)
16948 **
16949 ** Return YYYY-MM-DD
16950 */
16951 static void dateFunc(
16952   sqlite3_context *context,
16953   int argc,
16954   sqlite3_value **argv
16955 ){
16956   DateTime x;
16957   if( isDate(context, argc, argv, &x)==0 ){
16958     char zBuf[100];
16959     computeYMD(&x);
16960     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
16961     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16962   }
16963 }
16964
16965 /*
16966 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
16967 **
16968 ** Return a string described by FORMAT.  Conversions as follows:
16969 **
16970 **   %d  day of month
16971 **   %f  ** fractional seconds  SS.SSS
16972 **   %H  hour 00-24
16973 **   %j  day of year 000-366
16974 **   %J  ** Julian day number
16975 **   %m  month 01-12
16976 **   %M  minute 00-59
16977 **   %s  seconds since 1970-01-01
16978 **   %S  seconds 00-59
16979 **   %w  day of week 0-6  sunday==0
16980 **   %W  week of year 00-53
16981 **   %Y  year 0000-9999
16982 **   %%  %
16983 */
16984 static void strftimeFunc(
16985   sqlite3_context *context,
16986   int argc,
16987   sqlite3_value **argv
16988 ){
16989   DateTime x;
16990   u64 n;
16991   size_t i,j;
16992   char *z;
16993   sqlite3 *db;
16994   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
16995   char zBuf[100];
16996   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
16997   db = sqlite3_context_db_handle(context);
16998   for(i=0, n=1; zFmt[i]; i++, n++){
16999     if( zFmt[i]=='%' ){
17000       switch( zFmt[i+1] ){
17001         case 'd':
17002         case 'H':
17003         case 'm':
17004         case 'M':
17005         case 'S':
17006         case 'W':
17007           n++;
17008           /* fall thru */
17009         case 'w':
17010         case '%':
17011           break;
17012         case 'f':
17013           n += 8;
17014           break;
17015         case 'j':
17016           n += 3;
17017           break;
17018         case 'Y':
17019           n += 8;
17020           break;
17021         case 's':
17022         case 'J':
17023           n += 50;
17024           break;
17025         default:
17026           return;  /* ERROR.  return a NULL */
17027       }
17028       i++;
17029     }
17030   }
17031   testcase( n==sizeof(zBuf)-1 );
17032   testcase( n==sizeof(zBuf) );
17033   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
17034   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
17035   if( n<sizeof(zBuf) ){
17036     z = zBuf;
17037   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
17038     sqlite3_result_error_toobig(context);
17039     return;
17040   }else{
17041     z = sqlite3DbMallocRaw(db, (int)n);
17042     if( z==0 ){
17043       sqlite3_result_error_nomem(context);
17044       return;
17045     }
17046   }
17047   computeJD(&x);
17048   computeYMD_HMS(&x);
17049   for(i=j=0; zFmt[i]; i++){
17050     if( zFmt[i]!='%' ){
17051       z[j++] = zFmt[i];
17052     }else{
17053       i++;
17054       switch( zFmt[i] ){
17055         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
17056         case 'f': {
17057           double s = x.s;
17058           if( s>59.999 ) s = 59.999;
17059           sqlite3_snprintf(7, &z[j],"%06.3f", s);
17060           j += sqlite3Strlen30(&z[j]);
17061           break;
17062         }
17063         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
17064         case 'W': /* Fall thru */
17065         case 'j': {
17066           int nDay;             /* Number of days since 1st day of year */
17067           DateTime y = x;
17068           y.validJD = 0;
17069           y.M = 1;
17070           y.D = 1;
17071           computeJD(&y);
17072           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
17073           if( zFmt[i]=='W' ){
17074             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
17075             wd = (int)(((x.iJD+43200000)/86400000)%7);
17076             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
17077             j += 2;
17078           }else{
17079             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
17080             j += 3;
17081           }
17082           break;
17083         }
17084         case 'J': {
17085           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
17086           j+=sqlite3Strlen30(&z[j]);
17087           break;
17088         }
17089         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
17090         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
17091         case 's': {
17092           sqlite3_snprintf(30,&z[j],"%lld",
17093                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
17094           j += sqlite3Strlen30(&z[j]);
17095           break;
17096         }
17097         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
17098         case 'w': {
17099           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
17100           break;
17101         }
17102         case 'Y': {
17103           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
17104           break;
17105         }
17106         default:   z[j++] = '%'; break;
17107       }
17108     }
17109   }
17110   z[j] = 0;
17111   sqlite3_result_text(context, z, -1,
17112                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
17113 }
17114
17115 /*
17116 ** current_time()
17117 **
17118 ** This function returns the same value as time('now').
17119 */
17120 static void ctimeFunc(
17121   sqlite3_context *context,
17122   int NotUsed,
17123   sqlite3_value **NotUsed2
17124 ){
17125   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17126   timeFunc(context, 0, 0);
17127 }
17128
17129 /*
17130 ** current_date()
17131 **
17132 ** This function returns the same value as date('now').
17133 */
17134 static void cdateFunc(
17135   sqlite3_context *context,
17136   int NotUsed,
17137   sqlite3_value **NotUsed2
17138 ){
17139   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17140   dateFunc(context, 0, 0);
17141 }
17142
17143 /*
17144 ** current_timestamp()
17145 **
17146 ** This function returns the same value as datetime('now').
17147 */
17148 static void ctimestampFunc(
17149   sqlite3_context *context,
17150   int NotUsed,
17151   sqlite3_value **NotUsed2
17152 ){
17153   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17154   datetimeFunc(context, 0, 0);
17155 }
17156 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
17157
17158 #ifdef SQLITE_OMIT_DATETIME_FUNCS
17159 /*
17160 ** If the library is compiled to omit the full-scale date and time
17161 ** handling (to get a smaller binary), the following minimal version
17162 ** of the functions current_time(), current_date() and current_timestamp()
17163 ** are included instead. This is to support column declarations that
17164 ** include "DEFAULT CURRENT_TIME" etc.
17165 **
17166 ** This function uses the C-library functions time(), gmtime()
17167 ** and strftime(). The format string to pass to strftime() is supplied
17168 ** as the user-data for the function.
17169 */
17170 static void currentTimeFunc(
17171   sqlite3_context *context,
17172   int argc,
17173   sqlite3_value **argv
17174 ){
17175   time_t t;
17176   char *zFormat = (char *)sqlite3_user_data(context);
17177   sqlite3 *db;
17178   sqlite3_int64 iT;
17179   struct tm *pTm;
17180   struct tm sNow;
17181   char zBuf[20];
17182
17183   UNUSED_PARAMETER(argc);
17184   UNUSED_PARAMETER(argv);
17185
17186   db = sqlite3_context_db_handle(context);
17187   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
17188   t = iT/1000 - 10000*(sqlite3_int64)21086676;
17189 #ifdef HAVE_GMTIME_R
17190   pTm = gmtime_r(&t, &sNow);
17191 #else
17192   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
17193   pTm = gmtime(&t);
17194   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
17195   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
17196 #endif
17197   if( pTm ){
17198     strftime(zBuf, 20, zFormat, &sNow);
17199     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
17200   }
17201 }
17202 #endif
17203
17204 /*
17205 ** This function registered all of the above C functions as SQL
17206 ** functions.  This should be the only routine in this file with
17207 ** external linkage.
17208 */
17209 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
17210   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
17211 #ifndef SQLITE_OMIT_DATETIME_FUNCS
17212     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
17213     FUNCTION(date,             -1, 0, 0, dateFunc      ),
17214     FUNCTION(time,             -1, 0, 0, timeFunc      ),
17215     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
17216     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
17217     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
17218     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
17219     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
17220 #else
17221     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
17222     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
17223     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
17224 #endif
17225   };
17226   int i;
17227   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
17228   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
17229
17230   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
17231     sqlite3FuncDefInsert(pHash, &aFunc[i]);
17232   }
17233 }
17234
17235 /************** End of date.c ************************************************/
17236 /************** Begin file os.c **********************************************/
17237 /*
17238 ** 2005 November 29
17239 **
17240 ** The author disclaims copyright to this source code.  In place of
17241 ** a legal notice, here is a blessing:
17242 **
17243 **    May you do good and not evil.
17244 **    May you find forgiveness for yourself and forgive others.
17245 **    May you share freely, never taking more than you give.
17246 **
17247 ******************************************************************************
17248 **
17249 ** This file contains OS interface code that is common to all
17250 ** architectures.
17251 */
17252 #define _SQLITE_OS_C_ 1
17253 #undef _SQLITE_OS_C_
17254
17255 /*
17256 ** The default SQLite sqlite3_vfs implementations do not allocate
17257 ** memory (actually, os_unix.c allocates a small amount of memory
17258 ** from within OsOpen()), but some third-party implementations may.
17259 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
17260 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
17261 **
17262 ** The following functions are instrumented for malloc() failure
17263 ** testing:
17264 **
17265 **     sqlite3OsRead()
17266 **     sqlite3OsWrite()
17267 **     sqlite3OsSync()
17268 **     sqlite3OsFileSize()
17269 **     sqlite3OsLock()
17270 **     sqlite3OsCheckReservedLock()
17271 **     sqlite3OsFileControl()
17272 **     sqlite3OsShmMap()
17273 **     sqlite3OsOpen()
17274 **     sqlite3OsDelete()
17275 **     sqlite3OsAccess()
17276 **     sqlite3OsFullPathname()
17277 **
17278 */
17279 #if defined(SQLITE_TEST)
17280 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
17281   #define DO_OS_MALLOC_TEST(x)                                       \
17282   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
17283     void *pTstAlloc = sqlite3Malloc(10);                             \
17284     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
17285     sqlite3_free(pTstAlloc);                                         \
17286   }
17287 #else
17288   #define DO_OS_MALLOC_TEST(x)
17289 #endif
17290
17291 /*
17292 ** The following routines are convenience wrappers around methods
17293 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
17294 ** of this would be completely automatic if SQLite were coded using
17295 ** C++ instead of plain old C.
17296 */
17297 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
17298   int rc = SQLITE_OK;
17299   if( pId->pMethods ){
17300     rc = pId->pMethods->xClose(pId);
17301     pId->pMethods = 0;
17302   }
17303   return rc;
17304 }
17305 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
17306   DO_OS_MALLOC_TEST(id);
17307   return id->pMethods->xRead(id, pBuf, amt, offset);
17308 }
17309 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
17310   DO_OS_MALLOC_TEST(id);
17311   return id->pMethods->xWrite(id, pBuf, amt, offset);
17312 }
17313 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
17314   return id->pMethods->xTruncate(id, size);
17315 }
17316 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
17317   DO_OS_MALLOC_TEST(id);
17318   return id->pMethods->xSync(id, flags);
17319 }
17320 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
17321   DO_OS_MALLOC_TEST(id);
17322   return id->pMethods->xFileSize(id, pSize);
17323 }
17324 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
17325   DO_OS_MALLOC_TEST(id);
17326   return id->pMethods->xLock(id, lockType);
17327 }
17328 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
17329   return id->pMethods->xUnlock(id, lockType);
17330 }
17331 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
17332   DO_OS_MALLOC_TEST(id);
17333   return id->pMethods->xCheckReservedLock(id, pResOut);
17334 }
17335
17336 /*
17337 ** Use sqlite3OsFileControl() when we are doing something that might fail
17338 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
17339 ** when simply tossing information over the wall to the VFS and we do not
17340 ** really care if the VFS receives and understands the information since it
17341 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
17342 ** routine has no return value since the return value would be meaningless.
17343 */
17344 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
17345   DO_OS_MALLOC_TEST(id);
17346   return id->pMethods->xFileControl(id, op, pArg);
17347 }
17348 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
17349   (void)id->pMethods->xFileControl(id, op, pArg);
17350 }
17351
17352 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
17353   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
17354   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
17355 }
17356 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
17357   return id->pMethods->xDeviceCharacteristics(id);
17358 }
17359 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
17360   return id->pMethods->xShmLock(id, offset, n, flags);
17361 }
17362 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
17363   id->pMethods->xShmBarrier(id);
17364 }
17365 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
17366   return id->pMethods->xShmUnmap(id, deleteFlag);
17367 }
17368 SQLITE_PRIVATE int sqlite3OsShmMap(
17369   sqlite3_file *id,               /* Database file handle */
17370   int iPage,
17371   int pgsz,
17372   int bExtend,                    /* True to extend file if necessary */
17373   void volatile **pp              /* OUT: Pointer to mapping */
17374 ){
17375   DO_OS_MALLOC_TEST(id);
17376   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
17377 }
17378
17379 /*
17380 ** The next group of routines are convenience wrappers around the
17381 ** VFS methods.
17382 */
17383 SQLITE_PRIVATE int sqlite3OsOpen(
17384   sqlite3_vfs *pVfs,
17385   const char *zPath,
17386   sqlite3_file *pFile,
17387   int flags,
17388   int *pFlagsOut
17389 ){
17390   int rc;
17391   DO_OS_MALLOC_TEST(0);
17392   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
17393   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
17394   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
17395   ** reaching the VFS. */
17396   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
17397   assert( rc==SQLITE_OK || pFile->pMethods==0 );
17398   return rc;
17399 }
17400 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
17401   DO_OS_MALLOC_TEST(0);
17402   assert( dirSync==0 || dirSync==1 );
17403   return pVfs->xDelete(pVfs, zPath, dirSync);
17404 }
17405 SQLITE_PRIVATE int sqlite3OsAccess(
17406   sqlite3_vfs *pVfs,
17407   const char *zPath,
17408   int flags,
17409   int *pResOut
17410 ){
17411   DO_OS_MALLOC_TEST(0);
17412   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
17413 }
17414 SQLITE_PRIVATE int sqlite3OsFullPathname(
17415   sqlite3_vfs *pVfs,
17416   const char *zPath,
17417   int nPathOut,
17418   char *zPathOut
17419 ){
17420   DO_OS_MALLOC_TEST(0);
17421   zPathOut[0] = 0;
17422   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
17423 }
17424 #ifndef SQLITE_OMIT_LOAD_EXTENSION
17425 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
17426   return pVfs->xDlOpen(pVfs, zPath);
17427 }
17428 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
17429   pVfs->xDlError(pVfs, nByte, zBufOut);
17430 }
17431 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
17432   return pVfs->xDlSym(pVfs, pHdle, zSym);
17433 }
17434 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
17435   pVfs->xDlClose(pVfs, pHandle);
17436 }
17437 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
17438 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
17439   return pVfs->xRandomness(pVfs, nByte, zBufOut);
17440 }
17441 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
17442   return pVfs->xSleep(pVfs, nMicro);
17443 }
17444 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
17445   int rc;
17446   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
17447   ** method to get the current date and time if that method is available
17448   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
17449   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
17450   ** unavailable.
17451   */
17452   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
17453     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
17454   }else{
17455     double r;
17456     rc = pVfs->xCurrentTime(pVfs, &r);
17457     *pTimeOut = (sqlite3_int64)(r*86400000.0);
17458   }
17459   return rc;
17460 }
17461
17462 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
17463   sqlite3_vfs *pVfs,
17464   const char *zFile,
17465   sqlite3_file **ppFile,
17466   int flags,
17467   int *pOutFlags
17468 ){
17469   int rc = SQLITE_NOMEM;
17470   sqlite3_file *pFile;
17471   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
17472   if( pFile ){
17473     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
17474     if( rc!=SQLITE_OK ){
17475       sqlite3_free(pFile);
17476     }else{
17477       *ppFile = pFile;
17478     }
17479   }
17480   return rc;
17481 }
17482 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
17483   int rc = SQLITE_OK;
17484   assert( pFile );
17485   rc = sqlite3OsClose(pFile);
17486   sqlite3_free(pFile);
17487   return rc;
17488 }
17489
17490 /*
17491 ** This function is a wrapper around the OS specific implementation of
17492 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
17493 ** ability to simulate a malloc failure, so that the handling of an
17494 ** error in sqlite3_os_init() by the upper layers can be tested.
17495 */
17496 SQLITE_PRIVATE int sqlite3OsInit(void){
17497   void *p = sqlite3_malloc(10);
17498   if( p==0 ) return SQLITE_NOMEM;
17499   sqlite3_free(p);
17500   return sqlite3_os_init();
17501 }
17502
17503 /*
17504 ** The list of all registered VFS implementations.
17505 */
17506 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
17507 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
17508
17509 /*
17510 ** Locate a VFS by name.  If no name is given, simply return the
17511 ** first VFS on the list.
17512 */
17513 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
17514   sqlite3_vfs *pVfs = 0;
17515 #if SQLITE_THREADSAFE
17516   sqlite3_mutex *mutex;
17517 #endif
17518 #ifndef SQLITE_OMIT_AUTOINIT
17519   int rc = sqlite3_initialize();
17520   if( rc ) return 0;
17521 #endif
17522 #if SQLITE_THREADSAFE
17523   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
17524 #endif
17525   sqlite3_mutex_enter(mutex);
17526   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
17527     if( zVfs==0 ) break;
17528     if( strcmp(zVfs, pVfs->zName)==0 ) break;
17529   }
17530   sqlite3_mutex_leave(mutex);
17531   return pVfs;
17532 }
17533
17534 /*
17535 ** Unlink a VFS from the linked list
17536 */
17537 static void vfsUnlink(sqlite3_vfs *pVfs){
17538   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
17539   if( pVfs==0 ){
17540     /* No-op */
17541   }else if( vfsList==pVfs ){
17542     vfsList = pVfs->pNext;
17543   }else if( vfsList ){
17544     sqlite3_vfs *p = vfsList;
17545     while( p->pNext && p->pNext!=pVfs ){
17546       p = p->pNext;
17547     }
17548     if( p->pNext==pVfs ){
17549       p->pNext = pVfs->pNext;
17550     }
17551   }
17552 }
17553
17554 /*
17555 ** Register a VFS with the system.  It is harmless to register the same
17556 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
17557 ** true.
17558 */
17559 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
17560   MUTEX_LOGIC(sqlite3_mutex *mutex;)
17561 #ifndef SQLITE_OMIT_AUTOINIT
17562   int rc = sqlite3_initialize();
17563   if( rc ) return rc;
17564 #endif
17565   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
17566   sqlite3_mutex_enter(mutex);
17567   vfsUnlink(pVfs);
17568   if( makeDflt || vfsList==0 ){
17569     pVfs->pNext = vfsList;
17570     vfsList = pVfs;
17571   }else{
17572     pVfs->pNext = vfsList->pNext;
17573     vfsList->pNext = pVfs;
17574   }
17575   assert(vfsList);
17576   sqlite3_mutex_leave(mutex);
17577   return SQLITE_OK;
17578 }
17579
17580 /*
17581 ** Unregister a VFS so that it is no longer accessible.
17582 */
17583 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
17584 #if SQLITE_THREADSAFE
17585   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
17586 #endif
17587   sqlite3_mutex_enter(mutex);
17588   vfsUnlink(pVfs);
17589   sqlite3_mutex_leave(mutex);
17590   return SQLITE_OK;
17591 }
17592
17593 /************** End of os.c **************************************************/
17594 /************** Begin file fault.c *******************************************/
17595 /*
17596 ** 2008 Jan 22
17597 **
17598 ** The author disclaims copyright to this source code.  In place of
17599 ** a legal notice, here is a blessing:
17600 **
17601 **    May you do good and not evil.
17602 **    May you find forgiveness for yourself and forgive others.
17603 **    May you share freely, never taking more than you give.
17604 **
17605 *************************************************************************
17606 **
17607 ** This file contains code to support the concept of "benign"
17608 ** malloc failures (when the xMalloc() or xRealloc() method of the
17609 ** sqlite3_mem_methods structure fails to allocate a block of memory
17610 ** and returns 0).
17611 **
17612 ** Most malloc failures are non-benign. After they occur, SQLite
17613 ** abandons the current operation and returns an error code (usually
17614 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
17615 ** fatal. For example, if a malloc fails while resizing a hash table, this
17616 ** is completely recoverable simply by not carrying out the resize. The
17617 ** hash table will continue to function normally.  So a malloc failure
17618 ** during a hash table resize is a benign fault.
17619 */
17620
17621
17622 #ifndef SQLITE_OMIT_BUILTIN_TEST
17623
17624 /*
17625 ** Global variables.
17626 */
17627 typedef struct BenignMallocHooks BenignMallocHooks;
17628 static SQLITE_WSD struct BenignMallocHooks {
17629   void (*xBenignBegin)(void);
17630   void (*xBenignEnd)(void);
17631 } sqlite3Hooks = { 0, 0 };
17632
17633 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
17634 ** structure.  If writable static data is unsupported on the target,
17635 ** we have to locate the state vector at run-time.  In the more common
17636 ** case where writable static data is supported, wsdHooks can refer directly
17637 ** to the "sqlite3Hooks" state vector declared above.
17638 */
17639 #ifdef SQLITE_OMIT_WSD
17640 # define wsdHooksInit \
17641   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
17642 # define wsdHooks x[0]
17643 #else
17644 # define wsdHooksInit
17645 # define wsdHooks sqlite3Hooks
17646 #endif
17647
17648
17649 /*
17650 ** Register hooks to call when sqlite3BeginBenignMalloc() and
17651 ** sqlite3EndBenignMalloc() are called, respectively.
17652 */
17653 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
17654   void (*xBenignBegin)(void),
17655   void (*xBenignEnd)(void)
17656 ){
17657   wsdHooksInit;
17658   wsdHooks.xBenignBegin = xBenignBegin;
17659   wsdHooks.xBenignEnd = xBenignEnd;
17660 }
17661
17662 /*
17663 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
17664 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
17665 ** indicates that subsequent malloc failures are non-benign.
17666 */
17667 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
17668   wsdHooksInit;
17669   if( wsdHooks.xBenignBegin ){
17670     wsdHooks.xBenignBegin();
17671   }
17672 }
17673 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
17674   wsdHooksInit;
17675   if( wsdHooks.xBenignEnd ){
17676     wsdHooks.xBenignEnd();
17677   }
17678 }
17679
17680 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
17681
17682 /************** End of fault.c ***********************************************/
17683 /************** Begin file mem0.c ********************************************/
17684 /*
17685 ** 2008 October 28
17686 **
17687 ** The author disclaims copyright to this source code.  In place of
17688 ** a legal notice, here is a blessing:
17689 **
17690 **    May you do good and not evil.
17691 **    May you find forgiveness for yourself and forgive others.
17692 **    May you share freely, never taking more than you give.
17693 **
17694 *************************************************************************
17695 **
17696 ** This file contains a no-op memory allocation drivers for use when
17697 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
17698 ** here always fail.  SQLite will not operate with these drivers.  These
17699 ** are merely placeholders.  Real drivers must be substituted using
17700 ** sqlite3_config() before SQLite will operate.
17701 */
17702
17703 /*
17704 ** This version of the memory allocator is the default.  It is
17705 ** used when no other memory allocator is specified using compile-time
17706 ** macros.
17707 */
17708 #ifdef SQLITE_ZERO_MALLOC
17709
17710 /*
17711 ** No-op versions of all memory allocation routines
17712 */
17713 static void *sqlite3MemMalloc(int nByte){ return 0; }
17714 static void sqlite3MemFree(void *pPrior){ return; }
17715 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
17716 static int sqlite3MemSize(void *pPrior){ return 0; }
17717 static int sqlite3MemRoundup(int n){ return n; }
17718 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
17719 static void sqlite3MemShutdown(void *NotUsed){ return; }
17720
17721 /*
17722 ** This routine is the only routine in this file with external linkage.
17723 **
17724 ** Populate the low-level memory allocation function pointers in
17725 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17726 */
17727 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17728   static const sqlite3_mem_methods defaultMethods = {
17729      sqlite3MemMalloc,
17730      sqlite3MemFree,
17731      sqlite3MemRealloc,
17732      sqlite3MemSize,
17733      sqlite3MemRoundup,
17734      sqlite3MemInit,
17735      sqlite3MemShutdown,
17736      0
17737   };
17738   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17739 }
17740
17741 #endif /* SQLITE_ZERO_MALLOC */
17742
17743 /************** End of mem0.c ************************************************/
17744 /************** Begin file mem1.c ********************************************/
17745 /*
17746 ** 2007 August 14
17747 **
17748 ** The author disclaims copyright to this source code.  In place of
17749 ** a legal notice, here is a blessing:
17750 **
17751 **    May you do good and not evil.
17752 **    May you find forgiveness for yourself and forgive others.
17753 **    May you share freely, never taking more than you give.
17754 **
17755 *************************************************************************
17756 **
17757 ** This file contains low-level memory allocation drivers for when
17758 ** SQLite will use the standard C-library malloc/realloc/free interface
17759 ** to obtain the memory it needs.
17760 **
17761 ** This file contains implementations of the low-level memory allocation
17762 ** routines specified in the sqlite3_mem_methods object.  The content of
17763 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
17764 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
17765 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
17766 ** default configuration is to use memory allocation routines in this
17767 ** file.
17768 **
17769 ** C-preprocessor macro summary:
17770 **
17771 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
17772 **                                the malloc_usable_size() interface exists
17773 **                                on the target platform.  Or, this symbol
17774 **                                can be set manually, if desired.
17775 **                                If an equivalent interface exists by
17776 **                                a different name, using a separate -D
17777 **                                option to rename it.
17778 **
17779 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
17780 **                                memory allocator.  Set this symbol to enable
17781 **                                building on older macs.
17782 **
17783 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
17784 **                                _msize() on windows systems.  This might
17785 **                                be necessary when compiling for Delphi,
17786 **                                for example.
17787 */
17788
17789 /*
17790 ** This version of the memory allocator is the default.  It is
17791 ** used when no other memory allocator is specified using compile-time
17792 ** macros.
17793 */
17794 #ifdef SQLITE_SYSTEM_MALLOC
17795
17796 /*
17797 ** The MSVCRT has malloc_usable_size() but it is called _msize().
17798 ** The use of _msize() is automatic, but can be disabled by compiling
17799 ** with -DSQLITE_WITHOUT_MSIZE
17800 */
17801 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
17802 # define SQLITE_MALLOCSIZE _msize
17803 #endif
17804
17805 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
17806
17807 /*
17808 ** Use the zone allocator available on apple products unless the
17809 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
17810 */
17811 #include <sys/sysctl.h>
17812 #include <malloc/malloc.h>
17813 #include <libkern/OSAtomic.h>
17814 static malloc_zone_t* _sqliteZone_;
17815 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
17816 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
17817 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
17818 #define SQLITE_MALLOCSIZE(x) \
17819         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
17820
17821 #else /* if not __APPLE__ */
17822
17823 /*
17824 ** Use standard C library malloc and free on non-Apple systems.
17825 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
17826 */
17827 #define SQLITE_MALLOC(x)    malloc(x)
17828 #define SQLITE_FREE(x)      free(x)
17829 #define SQLITE_REALLOC(x,y) realloc((x),(y))
17830
17831 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
17832       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
17833 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
17834 #endif
17835 #ifdef HAVE_MALLOC_USABLE_SIZE
17836 # ifndef SQLITE_MALLOCSIZE
17837 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
17838 # endif
17839 #else
17840 # undef SQLITE_MALLOCSIZE
17841 #endif
17842
17843 #endif /* __APPLE__ or not __APPLE__ */
17844
17845 /*
17846 ** Like malloc(), but remember the size of the allocation
17847 ** so that we can find it later using sqlite3MemSize().
17848 **
17849 ** For this low-level routine, we are guaranteed that nByte>0 because
17850 ** cases of nByte<=0 will be intercepted and dealt with by higher level
17851 ** routines.
17852 */
17853 static void *sqlite3MemMalloc(int nByte){
17854 #ifdef SQLITE_MALLOCSIZE
17855   void *p = SQLITE_MALLOC( nByte );
17856   if( p==0 ){
17857     testcase( sqlite3GlobalConfig.xLog!=0 );
17858     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17859   }
17860   return p;
17861 #else
17862   sqlite3_int64 *p;
17863   assert( nByte>0 );
17864   nByte = ROUND8(nByte);
17865   p = SQLITE_MALLOC( nByte+8 );
17866   if( p ){
17867     p[0] = nByte;
17868     p++;
17869   }else{
17870     testcase( sqlite3GlobalConfig.xLog!=0 );
17871     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17872   }
17873   return (void *)p;
17874 #endif
17875 }
17876
17877 /*
17878 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
17879 ** or sqlite3MemRealloc().
17880 **
17881 ** For this low-level routine, we already know that pPrior!=0 since
17882 ** cases where pPrior==0 will have been intecepted and dealt with
17883 ** by higher-level routines.
17884 */
17885 static void sqlite3MemFree(void *pPrior){
17886 #ifdef SQLITE_MALLOCSIZE
17887   SQLITE_FREE(pPrior);
17888 #else
17889   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17890   assert( pPrior!=0 );
17891   p--;
17892   SQLITE_FREE(p);
17893 #endif
17894 }
17895
17896 /*
17897 ** Report the allocated size of a prior return from xMalloc()
17898 ** or xRealloc().
17899 */
17900 static int sqlite3MemSize(void *pPrior){
17901 #ifdef SQLITE_MALLOCSIZE
17902   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
17903 #else
17904   sqlite3_int64 *p;
17905   if( pPrior==0 ) return 0;
17906   p = (sqlite3_int64*)pPrior;
17907   p--;
17908   return (int)p[0];
17909 #endif
17910 }
17911
17912 /*
17913 ** Like realloc().  Resize an allocation previously obtained from
17914 ** sqlite3MemMalloc().
17915 **
17916 ** For this low-level interface, we know that pPrior!=0.  Cases where
17917 ** pPrior==0 while have been intercepted by higher-level routine and
17918 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
17919 ** cases where nByte<=0 will have been intercepted by higher-level
17920 ** routines and redirected to xFree.
17921 */
17922 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17923 #ifdef SQLITE_MALLOCSIZE
17924   void *p = SQLITE_REALLOC(pPrior, nByte);
17925   if( p==0 ){
17926     testcase( sqlite3GlobalConfig.xLog!=0 );
17927     sqlite3_log(SQLITE_NOMEM,
17928       "failed memory resize %u to %u bytes",
17929       SQLITE_MALLOCSIZE(pPrior), nByte);
17930   }
17931   return p;
17932 #else
17933   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17934   assert( pPrior!=0 && nByte>0 );
17935   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
17936   p--;
17937   p = SQLITE_REALLOC(p, nByte+8 );
17938   if( p ){
17939     p[0] = nByte;
17940     p++;
17941   }else{
17942     testcase( sqlite3GlobalConfig.xLog!=0 );
17943     sqlite3_log(SQLITE_NOMEM,
17944       "failed memory resize %u to %u bytes",
17945       sqlite3MemSize(pPrior), nByte);
17946   }
17947   return (void*)p;
17948 #endif
17949 }
17950
17951 /*
17952 ** Round up a request size to the next valid allocation size.
17953 */
17954 static int sqlite3MemRoundup(int n){
17955   return ROUND8(n);
17956 }
17957
17958 /*
17959 ** Initialize this module.
17960 */
17961 static int sqlite3MemInit(void *NotUsed){
17962 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
17963   int cpuCount;
17964   size_t len;
17965   if( _sqliteZone_ ){
17966     return SQLITE_OK;
17967   }
17968   len = sizeof(cpuCount);
17969   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
17970   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
17971   if( cpuCount>1 ){
17972     /* defer MT decisions to system malloc */
17973     _sqliteZone_ = malloc_default_zone();
17974   }else{
17975     /* only 1 core, use our own zone to contention over global locks,
17976     ** e.g. we have our own dedicated locks */
17977     bool success;
17978     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
17979     malloc_set_zone_name(newzone, "Sqlite_Heap");
17980     do{
17981       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
17982                                  (void * volatile *)&_sqliteZone_);
17983     }while(!_sqliteZone_);
17984     if( !success ){
17985       /* somebody registered a zone first */
17986       malloc_destroy_zone(newzone);
17987     }
17988   }
17989 #endif
17990   UNUSED_PARAMETER(NotUsed);
17991   return SQLITE_OK;
17992 }
17993
17994 /*
17995 ** Deinitialize this module.
17996 */
17997 static void sqlite3MemShutdown(void *NotUsed){
17998   UNUSED_PARAMETER(NotUsed);
17999   return;
18000 }
18001
18002 /*
18003 ** This routine is the only routine in this file with external linkage.
18004 **
18005 ** Populate the low-level memory allocation function pointers in
18006 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
18007 */
18008 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
18009   static const sqlite3_mem_methods defaultMethods = {
18010      sqlite3MemMalloc,
18011      sqlite3MemFree,
18012      sqlite3MemRealloc,
18013      sqlite3MemSize,
18014      sqlite3MemRoundup,
18015      sqlite3MemInit,
18016      sqlite3MemShutdown,
18017      0
18018   };
18019   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
18020 }
18021
18022 #endif /* SQLITE_SYSTEM_MALLOC */
18023
18024 /************** End of mem1.c ************************************************/
18025 /************** Begin file mem2.c ********************************************/
18026 /*
18027 ** 2007 August 15
18028 **
18029 ** The author disclaims copyright to this source code.  In place of
18030 ** a legal notice, here is a blessing:
18031 **
18032 **    May you do good and not evil.
18033 **    May you find forgiveness for yourself and forgive others.
18034 **    May you share freely, never taking more than you give.
18035 **
18036 *************************************************************************
18037 **
18038 ** This file contains low-level memory allocation drivers for when
18039 ** SQLite will use the standard C-library malloc/realloc/free interface
18040 ** to obtain the memory it needs while adding lots of additional debugging
18041 ** information to each allocation in order to help detect and fix memory
18042 ** leaks and memory usage errors.
18043 **
18044 ** This file contains implementations of the low-level memory allocation
18045 ** routines specified in the sqlite3_mem_methods object.
18046 */
18047
18048 /*
18049 ** This version of the memory allocator is used only if the
18050 ** SQLITE_MEMDEBUG macro is defined
18051 */
18052 #ifdef SQLITE_MEMDEBUG
18053
18054 /*
18055 ** The backtrace functionality is only available with GLIBC
18056 */
18057 #ifdef __GLIBC__
18058   extern int backtrace(void**,int);
18059   extern void backtrace_symbols_fd(void*const*,int,int);
18060 #else
18061 # define backtrace(A,B) 1
18062 # define backtrace_symbols_fd(A,B,C)
18063 #endif
18064 /* #include <stdio.h> */
18065
18066 /*
18067 ** Each memory allocation looks like this:
18068 **
18069 **  ------------------------------------------------------------------------
18070 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
18071 **  ------------------------------------------------------------------------
18072 **
18073 ** The application code sees only a pointer to the allocation.  We have
18074 ** to back up from the allocation pointer to find the MemBlockHdr.  The
18075 ** MemBlockHdr tells us the size of the allocation and the number of
18076 ** backtrace pointers.  There is also a guard word at the end of the
18077 ** MemBlockHdr.
18078 */
18079 struct MemBlockHdr {
18080   i64 iSize;                          /* Size of this allocation */
18081   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
18082   char nBacktrace;                    /* Number of backtraces on this alloc */
18083   char nBacktraceSlots;               /* Available backtrace slots */
18084   u8 nTitle;                          /* Bytes of title; includes '\0' */
18085   u8 eType;                           /* Allocation type code */
18086   int iForeGuard;                     /* Guard word for sanity */
18087 };
18088
18089 /*
18090 ** Guard words
18091 */
18092 #define FOREGUARD 0x80F5E153
18093 #define REARGUARD 0xE4676B53
18094
18095 /*
18096 ** Number of malloc size increments to track.
18097 */
18098 #define NCSIZE  1000
18099
18100 /*
18101 ** All of the static variables used by this module are collected
18102 ** into a single structure named "mem".  This is to keep the
18103 ** static variables organized and to reduce namespace pollution
18104 ** when this module is combined with other in the amalgamation.
18105 */
18106 static struct {
18107
18108   /*
18109   ** Mutex to control access to the memory allocation subsystem.
18110   */
18111   sqlite3_mutex *mutex;
18112
18113   /*
18114   ** Head and tail of a linked list of all outstanding allocations
18115   */
18116   struct MemBlockHdr *pFirst;
18117   struct MemBlockHdr *pLast;
18118
18119   /*
18120   ** The number of levels of backtrace to save in new allocations.
18121   */
18122   int nBacktrace;
18123   void (*xBacktrace)(int, int, void **);
18124
18125   /*
18126   ** Title text to insert in front of each block
18127   */
18128   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
18129   char zTitle[100];  /* The title text */
18130
18131   /*
18132   ** sqlite3MallocDisallow() increments the following counter.
18133   ** sqlite3MallocAllow() decrements it.
18134   */
18135   int disallow; /* Do not allow memory allocation */
18136
18137   /*
18138   ** Gather statistics on the sizes of memory allocations.
18139   ** nAlloc[i] is the number of allocation attempts of i*8
18140   ** bytes.  i==NCSIZE is the number of allocation attempts for
18141   ** sizes more than NCSIZE*8 bytes.
18142   */
18143   int nAlloc[NCSIZE];      /* Total number of allocations */
18144   int nCurrent[NCSIZE];    /* Current number of allocations */
18145   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
18146
18147 } mem;
18148
18149
18150 /*
18151 ** Adjust memory usage statistics
18152 */
18153 static void adjustStats(int iSize, int increment){
18154   int i = ROUND8(iSize)/8;
18155   if( i>NCSIZE-1 ){
18156     i = NCSIZE - 1;
18157   }
18158   if( increment>0 ){
18159     mem.nAlloc[i]++;
18160     mem.nCurrent[i]++;
18161     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
18162       mem.mxCurrent[i] = mem.nCurrent[i];
18163     }
18164   }else{
18165     mem.nCurrent[i]--;
18166     assert( mem.nCurrent[i]>=0 );
18167   }
18168 }
18169
18170 /*
18171 ** Given an allocation, find the MemBlockHdr for that allocation.
18172 **
18173 ** This routine checks the guards at either end of the allocation and
18174 ** if they are incorrect it asserts.
18175 */
18176 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
18177   struct MemBlockHdr *p;
18178   int *pInt;
18179   u8 *pU8;
18180   int nReserve;
18181
18182   p = (struct MemBlockHdr*)pAllocation;
18183   p--;
18184   assert( p->iForeGuard==(int)FOREGUARD );
18185   nReserve = ROUND8(p->iSize);
18186   pInt = (int*)pAllocation;
18187   pU8 = (u8*)pAllocation;
18188   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
18189   /* This checks any of the "extra" bytes allocated due
18190   ** to rounding up to an 8 byte boundary to ensure
18191   ** they haven't been overwritten.
18192   */
18193   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
18194   return p;
18195 }
18196
18197 /*
18198 ** Return the number of bytes currently allocated at address p.
18199 */
18200 static int sqlite3MemSize(void *p){
18201   struct MemBlockHdr *pHdr;
18202   if( !p ){
18203     return 0;
18204   }
18205   pHdr = sqlite3MemsysGetHeader(p);
18206   return pHdr->iSize;
18207 }
18208
18209 /*
18210 ** Initialize the memory allocation subsystem.
18211 */
18212 static int sqlite3MemInit(void *NotUsed){
18213   UNUSED_PARAMETER(NotUsed);
18214   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
18215   if( !sqlite3GlobalConfig.bMemstat ){
18216     /* If memory status is enabled, then the malloc.c wrapper will already
18217     ** hold the STATIC_MEM mutex when the routines here are invoked. */
18218     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18219   }
18220   return SQLITE_OK;
18221 }
18222
18223 /*
18224 ** Deinitialize the memory allocation subsystem.
18225 */
18226 static void sqlite3MemShutdown(void *NotUsed){
18227   UNUSED_PARAMETER(NotUsed);
18228   mem.mutex = 0;
18229 }
18230
18231 /*
18232 ** Round up a request size to the next valid allocation size.
18233 */
18234 static int sqlite3MemRoundup(int n){
18235   return ROUND8(n);
18236 }
18237
18238 /*
18239 ** Fill a buffer with pseudo-random bytes.  This is used to preset
18240 ** the content of a new memory allocation to unpredictable values and
18241 ** to clear the content of a freed allocation to unpredictable values.
18242 */
18243 static void randomFill(char *pBuf, int nByte){
18244   unsigned int x, y, r;
18245   x = SQLITE_PTR_TO_INT(pBuf);
18246   y = nByte | 1;
18247   while( nByte >= 4 ){
18248     x = (x>>1) ^ (-(x&1) & 0xd0000001);
18249     y = y*1103515245 + 12345;
18250     r = x ^ y;
18251     *(int*)pBuf = r;
18252     pBuf += 4;
18253     nByte -= 4;
18254   }
18255   while( nByte-- > 0 ){
18256     x = (x>>1) ^ (-(x&1) & 0xd0000001);
18257     y = y*1103515245 + 12345;
18258     r = x ^ y;
18259     *(pBuf++) = r & 0xff;
18260   }
18261 }
18262
18263 /*
18264 ** Allocate nByte bytes of memory.
18265 */
18266 static void *sqlite3MemMalloc(int nByte){
18267   struct MemBlockHdr *pHdr;
18268   void **pBt;
18269   char *z;
18270   int *pInt;
18271   void *p = 0;
18272   int totalSize;
18273   int nReserve;
18274   sqlite3_mutex_enter(mem.mutex);
18275   assert( mem.disallow==0 );
18276   nReserve = ROUND8(nByte);
18277   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
18278                mem.nBacktrace*sizeof(void*) + mem.nTitle;
18279   p = malloc(totalSize);
18280   if( p ){
18281     z = p;
18282     pBt = (void**)&z[mem.nTitle];
18283     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
18284     pHdr->pNext = 0;
18285     pHdr->pPrev = mem.pLast;
18286     if( mem.pLast ){
18287       mem.pLast->pNext = pHdr;
18288     }else{
18289       mem.pFirst = pHdr;
18290     }
18291     mem.pLast = pHdr;
18292     pHdr->iForeGuard = FOREGUARD;
18293     pHdr->eType = MEMTYPE_HEAP;
18294     pHdr->nBacktraceSlots = mem.nBacktrace;
18295     pHdr->nTitle = mem.nTitle;
18296     if( mem.nBacktrace ){
18297       void *aAddr[40];
18298       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
18299       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
18300       assert(pBt[0]);
18301       if( mem.xBacktrace ){
18302         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
18303       }
18304     }else{
18305       pHdr->nBacktrace = 0;
18306     }
18307     if( mem.nTitle ){
18308       memcpy(z, mem.zTitle, mem.nTitle);
18309     }
18310     pHdr->iSize = nByte;
18311     adjustStats(nByte, +1);
18312     pInt = (int*)&pHdr[1];
18313     pInt[nReserve/sizeof(int)] = REARGUARD;
18314     randomFill((char*)pInt, nByte);
18315     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
18316     p = (void*)pInt;
18317   }
18318   sqlite3_mutex_leave(mem.mutex);
18319   return p;
18320 }
18321
18322 /*
18323 ** Free memory.
18324 */
18325 static void sqlite3MemFree(void *pPrior){
18326   struct MemBlockHdr *pHdr;
18327   void **pBt;
18328   char *z;
18329   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
18330        || mem.mutex!=0 );
18331   pHdr = sqlite3MemsysGetHeader(pPrior);
18332   pBt = (void**)pHdr;
18333   pBt -= pHdr->nBacktraceSlots;
18334   sqlite3_mutex_enter(mem.mutex);
18335   if( pHdr->pPrev ){
18336     assert( pHdr->pPrev->pNext==pHdr );
18337     pHdr->pPrev->pNext = pHdr->pNext;
18338   }else{
18339     assert( mem.pFirst==pHdr );
18340     mem.pFirst = pHdr->pNext;
18341   }
18342   if( pHdr->pNext ){
18343     assert( pHdr->pNext->pPrev==pHdr );
18344     pHdr->pNext->pPrev = pHdr->pPrev;
18345   }else{
18346     assert( mem.pLast==pHdr );
18347     mem.pLast = pHdr->pPrev;
18348   }
18349   z = (char*)pBt;
18350   z -= pHdr->nTitle;
18351   adjustStats(pHdr->iSize, -1);
18352   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
18353                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
18354   free(z);
18355   sqlite3_mutex_leave(mem.mutex);
18356 }
18357
18358 /*
18359 ** Change the size of an existing memory allocation.
18360 **
18361 ** For this debugging implementation, we *always* make a copy of the
18362 ** allocation into a new place in memory.  In this way, if the
18363 ** higher level code is using pointer to the old allocation, it is
18364 ** much more likely to break and we are much more liking to find
18365 ** the error.
18366 */
18367 static void *sqlite3MemRealloc(void *pPrior, int nByte){
18368   struct MemBlockHdr *pOldHdr;
18369   void *pNew;
18370   assert( mem.disallow==0 );
18371   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
18372   pOldHdr = sqlite3MemsysGetHeader(pPrior);
18373   pNew = sqlite3MemMalloc(nByte);
18374   if( pNew ){
18375     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
18376     if( nByte>pOldHdr->iSize ){
18377       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
18378     }
18379     sqlite3MemFree(pPrior);
18380   }
18381   return pNew;
18382 }
18383
18384 /*
18385 ** Populate the low-level memory allocation function pointers in
18386 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
18387 */
18388 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
18389   static const sqlite3_mem_methods defaultMethods = {
18390      sqlite3MemMalloc,
18391      sqlite3MemFree,
18392      sqlite3MemRealloc,
18393      sqlite3MemSize,
18394      sqlite3MemRoundup,
18395      sqlite3MemInit,
18396      sqlite3MemShutdown,
18397      0
18398   };
18399   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
18400 }
18401
18402 /*
18403 ** Set the "type" of an allocation.
18404 */
18405 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
18406   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18407     struct MemBlockHdr *pHdr;
18408     pHdr = sqlite3MemsysGetHeader(p);
18409     assert( pHdr->iForeGuard==FOREGUARD );
18410     pHdr->eType = eType;
18411   }
18412 }
18413
18414 /*
18415 ** Return TRUE if the mask of type in eType matches the type of the
18416 ** allocation p.  Also return true if p==NULL.
18417 **
18418 ** This routine is designed for use within an assert() statement, to
18419 ** verify the type of an allocation.  For example:
18420 **
18421 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18422 */
18423 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
18424   int rc = 1;
18425   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18426     struct MemBlockHdr *pHdr;
18427     pHdr = sqlite3MemsysGetHeader(p);
18428     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
18429     if( (pHdr->eType&eType)==0 ){
18430       rc = 0;
18431     }
18432   }
18433   return rc;
18434 }
18435
18436 /*
18437 ** Return TRUE if the mask of type in eType matches no bits of the type of the
18438 ** allocation p.  Also return true if p==NULL.
18439 **
18440 ** This routine is designed for use within an assert() statement, to
18441 ** verify the type of an allocation.  For example:
18442 **
18443 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18444 */
18445 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
18446   int rc = 1;
18447   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
18448     struct MemBlockHdr *pHdr;
18449     pHdr = sqlite3MemsysGetHeader(p);
18450     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
18451     if( (pHdr->eType&eType)!=0 ){
18452       rc = 0;
18453     }
18454   }
18455   return rc;
18456 }
18457
18458 /*
18459 ** Set the number of backtrace levels kept for each allocation.
18460 ** A value of zero turns off backtracing.  The number is always rounded
18461 ** up to a multiple of 2.
18462 */
18463 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
18464   if( depth<0 ){ depth = 0; }
18465   if( depth>20 ){ depth = 20; }
18466   depth = (depth+1)&0xfe;
18467   mem.nBacktrace = depth;
18468 }
18469
18470 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
18471   mem.xBacktrace = xBacktrace;
18472 }
18473
18474 /*
18475 ** Set the title string for subsequent allocations.
18476 */
18477 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
18478   unsigned int n = sqlite3Strlen30(zTitle) + 1;
18479   sqlite3_mutex_enter(mem.mutex);
18480   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
18481   memcpy(mem.zTitle, zTitle, n);
18482   mem.zTitle[n] = 0;
18483   mem.nTitle = ROUND8(n);
18484   sqlite3_mutex_leave(mem.mutex);
18485 }
18486
18487 SQLITE_PRIVATE void sqlite3MemdebugSync(){
18488   struct MemBlockHdr *pHdr;
18489   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
18490     void **pBt = (void**)pHdr;
18491     pBt -= pHdr->nBacktraceSlots;
18492     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
18493   }
18494 }
18495
18496 /*
18497 ** Open the file indicated and write a log of all unfreed memory
18498 ** allocations into that log.
18499 */
18500 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
18501   FILE *out;
18502   struct MemBlockHdr *pHdr;
18503   void **pBt;
18504   int i;
18505   out = fopen(zFilename, "w");
18506   if( out==0 ){
18507     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18508                     zFilename);
18509     return;
18510   }
18511   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
18512     char *z = (char*)pHdr;
18513     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
18514     fprintf(out, "**** %lld bytes at %p from %s ****\n",
18515             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
18516     if( pHdr->nBacktrace ){
18517       fflush(out);
18518       pBt = (void**)pHdr;
18519       pBt -= pHdr->nBacktraceSlots;
18520       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
18521       fprintf(out, "\n");
18522     }
18523   }
18524   fprintf(out, "COUNTS:\n");
18525   for(i=0; i<NCSIZE-1; i++){
18526     if( mem.nAlloc[i] ){
18527       fprintf(out, "   %5d: %10d %10d %10d\n",
18528             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
18529     }
18530   }
18531   if( mem.nAlloc[NCSIZE-1] ){
18532     fprintf(out, "   %5d: %10d %10d %10d\n",
18533              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
18534              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
18535   }
18536   fclose(out);
18537 }
18538
18539 /*
18540 ** Return the number of times sqlite3MemMalloc() has been called.
18541 */
18542 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
18543   int i;
18544   int nTotal = 0;
18545   for(i=0; i<NCSIZE; i++){
18546     nTotal += mem.nAlloc[i];
18547   }
18548   return nTotal;
18549 }
18550
18551
18552 #endif /* SQLITE_MEMDEBUG */
18553
18554 /************** End of mem2.c ************************************************/
18555 /************** Begin file mem3.c ********************************************/
18556 /*
18557 ** 2007 October 14
18558 **
18559 ** The author disclaims copyright to this source code.  In place of
18560 ** a legal notice, here is a blessing:
18561 **
18562 **    May you do good and not evil.
18563 **    May you find forgiveness for yourself and forgive others.
18564 **    May you share freely, never taking more than you give.
18565 **
18566 *************************************************************************
18567 ** This file contains the C functions that implement a memory
18568 ** allocation subsystem for use by SQLite.
18569 **
18570 ** This version of the memory allocation subsystem omits all
18571 ** use of malloc(). The SQLite user supplies a block of memory
18572 ** before calling sqlite3_initialize() from which allocations
18573 ** are made and returned by the xMalloc() and xRealloc()
18574 ** implementations. Once sqlite3_initialize() has been called,
18575 ** the amount of memory available to SQLite is fixed and cannot
18576 ** be changed.
18577 **
18578 ** This version of the memory allocation subsystem is included
18579 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
18580 */
18581
18582 /*
18583 ** This version of the memory allocator is only built into the library
18584 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
18585 ** mean that the library will use a memory-pool by default, just that
18586 ** it is available. The mempool allocator is activated by calling
18587 ** sqlite3_config().
18588 */
18589 #ifdef SQLITE_ENABLE_MEMSYS3
18590
18591 /*
18592 ** Maximum size (in Mem3Blocks) of a "small" chunk.
18593 */
18594 #define MX_SMALL 10
18595
18596
18597 /*
18598 ** Number of freelist hash slots
18599 */
18600 #define N_HASH  61
18601
18602 /*
18603 ** A memory allocation (also called a "chunk") consists of two or
18604 ** more blocks where each block is 8 bytes.  The first 8 bytes are
18605 ** a header that is not returned to the user.
18606 **
18607 ** A chunk is two or more blocks that is either checked out or
18608 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
18609 ** size of the allocation in blocks if the allocation is free.
18610 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
18611 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
18612 ** is true if the previous chunk is checked out and false if the
18613 ** previous chunk is free.  The u.hdr.prevSize field is the size of
18614 ** the previous chunk in blocks if the previous chunk is on the
18615 ** freelist. If the previous chunk is checked out, then
18616 ** u.hdr.prevSize can be part of the data for that chunk and should
18617 ** not be read or written.
18618 **
18619 ** We often identify a chunk by its index in mem3.aPool[].  When
18620 ** this is done, the chunk index refers to the second block of
18621 ** the chunk.  In this way, the first chunk has an index of 1.
18622 ** A chunk index of 0 means "no such chunk" and is the equivalent
18623 ** of a NULL pointer.
18624 **
18625 ** The second block of free chunks is of the form u.list.  The
18626 ** two fields form a double-linked list of chunks of related sizes.
18627 ** Pointers to the head of the list are stored in mem3.aiSmall[]
18628 ** for smaller chunks and mem3.aiHash[] for larger chunks.
18629 **
18630 ** The second block of a chunk is user data if the chunk is checked
18631 ** out.  If a chunk is checked out, the user data may extend into
18632 ** the u.hdr.prevSize value of the following chunk.
18633 */
18634 typedef struct Mem3Block Mem3Block;
18635 struct Mem3Block {
18636   union {
18637     struct {
18638       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
18639       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
18640     } hdr;
18641     struct {
18642       u32 next;       /* Index in mem3.aPool[] of next free chunk */
18643       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
18644     } list;
18645   } u;
18646 };
18647
18648 /*
18649 ** All of the static variables used by this module are collected
18650 ** into a single structure named "mem3".  This is to keep the
18651 ** static variables organized and to reduce namespace pollution
18652 ** when this module is combined with other in the amalgamation.
18653 */
18654 static SQLITE_WSD struct Mem3Global {
18655   /*
18656   ** Memory available for allocation. nPool is the size of the array
18657   ** (in Mem3Blocks) pointed to by aPool less 2.
18658   */
18659   u32 nPool;
18660   Mem3Block *aPool;
18661
18662   /*
18663   ** True if we are evaluating an out-of-memory callback.
18664   */
18665   int alarmBusy;
18666
18667   /*
18668   ** Mutex to control access to the memory allocation subsystem.
18669   */
18670   sqlite3_mutex *mutex;
18671
18672   /*
18673   ** The minimum amount of free space that we have seen.
18674   */
18675   u32 mnMaster;
18676
18677   /*
18678   ** iMaster is the index of the master chunk.  Most new allocations
18679   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
18680   ** of the current master.  iMaster is 0 if there is not master chunk.
18681   ** The master chunk is not in either the aiHash[] or aiSmall[].
18682   */
18683   u32 iMaster;
18684   u32 szMaster;
18685
18686   /*
18687   ** Array of lists of free blocks according to the block size
18688   ** for smaller chunks, or a hash on the block size for larger
18689   ** chunks.
18690   */
18691   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
18692   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
18693 } mem3 = { 97535575 };
18694
18695 #define mem3 GLOBAL(struct Mem3Global, mem3)
18696
18697 /*
18698 ** Unlink the chunk at mem3.aPool[i] from list it is currently
18699 ** on.  *pRoot is the list that i is a member of.
18700 */
18701 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
18702   u32 next = mem3.aPool[i].u.list.next;
18703   u32 prev = mem3.aPool[i].u.list.prev;
18704   assert( sqlite3_mutex_held(mem3.mutex) );
18705   if( prev==0 ){
18706     *pRoot = next;
18707   }else{
18708     mem3.aPool[prev].u.list.next = next;
18709   }
18710   if( next ){
18711     mem3.aPool[next].u.list.prev = prev;
18712   }
18713   mem3.aPool[i].u.list.next = 0;
18714   mem3.aPool[i].u.list.prev = 0;
18715 }
18716
18717 /*
18718 ** Unlink the chunk at index i from
18719 ** whatever list is currently a member of.
18720 */
18721 static void memsys3Unlink(u32 i){
18722   u32 size, hash;
18723   assert( sqlite3_mutex_held(mem3.mutex) );
18724   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
18725   assert( i>=1 );
18726   size = mem3.aPool[i-1].u.hdr.size4x/4;
18727   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
18728   assert( size>=2 );
18729   if( size <= MX_SMALL ){
18730     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
18731   }else{
18732     hash = size % N_HASH;
18733     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18734   }
18735 }
18736
18737 /*
18738 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
18739 ** at *pRoot.
18740 */
18741 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
18742   assert( sqlite3_mutex_held(mem3.mutex) );
18743   mem3.aPool[i].u.list.next = *pRoot;
18744   mem3.aPool[i].u.list.prev = 0;
18745   if( *pRoot ){
18746     mem3.aPool[*pRoot].u.list.prev = i;
18747   }
18748   *pRoot = i;
18749 }
18750
18751 /*
18752 ** Link the chunk at index i into either the appropriate
18753 ** small chunk list, or into the large chunk hash table.
18754 */
18755 static void memsys3Link(u32 i){
18756   u32 size, hash;
18757   assert( sqlite3_mutex_held(mem3.mutex) );
18758   assert( i>=1 );
18759   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
18760   size = mem3.aPool[i-1].u.hdr.size4x/4;
18761   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
18762   assert( size>=2 );
18763   if( size <= MX_SMALL ){
18764     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
18765   }else{
18766     hash = size % N_HASH;
18767     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
18768   }
18769 }
18770
18771 /*
18772 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18773 ** will already be held (obtained by code in malloc.c) if
18774 ** sqlite3GlobalConfig.bMemStat is true.
18775 */
18776 static void memsys3Enter(void){
18777   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
18778     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18779   }
18780   sqlite3_mutex_enter(mem3.mutex);
18781 }
18782 static void memsys3Leave(void){
18783   sqlite3_mutex_leave(mem3.mutex);
18784 }
18785
18786 /*
18787 ** Called when we are unable to satisfy an allocation of nBytes.
18788 */
18789 static void memsys3OutOfMemory(int nByte){
18790   if( !mem3.alarmBusy ){
18791     mem3.alarmBusy = 1;
18792     assert( sqlite3_mutex_held(mem3.mutex) );
18793     sqlite3_mutex_leave(mem3.mutex);
18794     sqlite3_release_memory(nByte);
18795     sqlite3_mutex_enter(mem3.mutex);
18796     mem3.alarmBusy = 0;
18797   }
18798 }
18799
18800
18801 /*
18802 ** Chunk i is a free chunk that has been unlinked.  Adjust its
18803 ** size parameters for check-out and return a pointer to the
18804 ** user portion of the chunk.
18805 */
18806 static void *memsys3Checkout(u32 i, u32 nBlock){
18807   u32 x;
18808   assert( sqlite3_mutex_held(mem3.mutex) );
18809   assert( i>=1 );
18810   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
18811   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
18812   x = mem3.aPool[i-1].u.hdr.size4x;
18813   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
18814   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
18815   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
18816   return &mem3.aPool[i];
18817 }
18818
18819 /*
18820 ** Carve a piece off of the end of the mem3.iMaster free chunk.
18821 ** Return a pointer to the new allocation.  Or, if the master chunk
18822 ** is not large enough, return 0.
18823 */
18824 static void *memsys3FromMaster(u32 nBlock){
18825   assert( sqlite3_mutex_held(mem3.mutex) );
18826   assert( mem3.szMaster>=nBlock );
18827   if( nBlock>=mem3.szMaster-1 ){
18828     /* Use the entire master */
18829     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
18830     mem3.iMaster = 0;
18831     mem3.szMaster = 0;
18832     mem3.mnMaster = 0;
18833     return p;
18834   }else{
18835     /* Split the master block.  Return the tail. */
18836     u32 newi, x;
18837     newi = mem3.iMaster + mem3.szMaster - nBlock;
18838     assert( newi > mem3.iMaster+1 );
18839     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
18840     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
18841     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
18842     mem3.szMaster -= nBlock;
18843     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
18844     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18845     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18846     if( mem3.szMaster < mem3.mnMaster ){
18847       mem3.mnMaster = mem3.szMaster;
18848     }
18849     return (void*)&mem3.aPool[newi];
18850   }
18851 }
18852
18853 /*
18854 ** *pRoot is the head of a list of free chunks of the same size
18855 ** or same size hash.  In other words, *pRoot is an entry in either
18856 ** mem3.aiSmall[] or mem3.aiHash[].
18857 **
18858 ** This routine examines all entries on the given list and tries
18859 ** to coalesce each entries with adjacent free chunks.
18860 **
18861 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
18862 ** the current mem3.iMaster with the new larger chunk.  In order for
18863 ** this mem3.iMaster replacement to work, the master chunk must be
18864 ** linked into the hash tables.  That is not the normal state of
18865 ** affairs, of course.  The calling routine must link the master
18866 ** chunk before invoking this routine, then must unlink the (possibly
18867 ** changed) master chunk once this routine has finished.
18868 */
18869 static void memsys3Merge(u32 *pRoot){
18870   u32 iNext, prev, size, i, x;
18871
18872   assert( sqlite3_mutex_held(mem3.mutex) );
18873   for(i=*pRoot; i>0; i=iNext){
18874     iNext = mem3.aPool[i].u.list.next;
18875     size = mem3.aPool[i-1].u.hdr.size4x;
18876     assert( (size&1)==0 );
18877     if( (size&2)==0 ){
18878       memsys3UnlinkFromList(i, pRoot);
18879       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
18880       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
18881       if( prev==iNext ){
18882         iNext = mem3.aPool[prev].u.list.next;
18883       }
18884       memsys3Unlink(prev);
18885       size = i + size/4 - prev;
18886       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
18887       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
18888       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
18889       memsys3Link(prev);
18890       i = prev;
18891     }else{
18892       size /= 4;
18893     }
18894     if( size>mem3.szMaster ){
18895       mem3.iMaster = i;
18896       mem3.szMaster = size;
18897     }
18898   }
18899 }
18900
18901 /*
18902 ** Return a block of memory of at least nBytes in size.
18903 ** Return NULL if unable.
18904 **
18905 ** This function assumes that the necessary mutexes, if any, are
18906 ** already held by the caller. Hence "Unsafe".
18907 */
18908 static void *memsys3MallocUnsafe(int nByte){
18909   u32 i;
18910   u32 nBlock;
18911   u32 toFree;
18912
18913   assert( sqlite3_mutex_held(mem3.mutex) );
18914   assert( sizeof(Mem3Block)==8 );
18915   if( nByte<=12 ){
18916     nBlock = 2;
18917   }else{
18918     nBlock = (nByte + 11)/8;
18919   }
18920   assert( nBlock>=2 );
18921
18922   /* STEP 1:
18923   ** Look for an entry of the correct size in either the small
18924   ** chunk table or in the large chunk hash table.  This is
18925   ** successful most of the time (about 9 times out of 10).
18926   */
18927   if( nBlock <= MX_SMALL ){
18928     i = mem3.aiSmall[nBlock-2];
18929     if( i>0 ){
18930       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
18931       return memsys3Checkout(i, nBlock);
18932     }
18933   }else{
18934     int hash = nBlock % N_HASH;
18935     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
18936       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
18937         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18938         return memsys3Checkout(i, nBlock);
18939       }
18940     }
18941   }
18942
18943   /* STEP 2:
18944   ** Try to satisfy the allocation by carving a piece off of the end
18945   ** of the master chunk.  This step usually works if step 1 fails.
18946   */
18947   if( mem3.szMaster>=nBlock ){
18948     return memsys3FromMaster(nBlock);
18949   }
18950
18951
18952   /* STEP 3:
18953   ** Loop through the entire memory pool.  Coalesce adjacent free
18954   ** chunks.  Recompute the master chunk as the largest free chunk.
18955   ** Then try again to satisfy the allocation by carving a piece off
18956   ** of the end of the master chunk.  This step happens very
18957   ** rarely (we hope!)
18958   */
18959   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
18960     memsys3OutOfMemory(toFree);
18961     if( mem3.iMaster ){
18962       memsys3Link(mem3.iMaster);
18963       mem3.iMaster = 0;
18964       mem3.szMaster = 0;
18965     }
18966     for(i=0; i<N_HASH; i++){
18967       memsys3Merge(&mem3.aiHash[i]);
18968     }
18969     for(i=0; i<MX_SMALL-1; i++){
18970       memsys3Merge(&mem3.aiSmall[i]);
18971     }
18972     if( mem3.szMaster ){
18973       memsys3Unlink(mem3.iMaster);
18974       if( mem3.szMaster>=nBlock ){
18975         return memsys3FromMaster(nBlock);
18976       }
18977     }
18978   }
18979
18980   /* If none of the above worked, then we fail. */
18981   return 0;
18982 }
18983
18984 /*
18985 ** Free an outstanding memory allocation.
18986 **
18987 ** This function assumes that the necessary mutexes, if any, are
18988 ** already held by the caller. Hence "Unsafe".
18989 */
18990 static void memsys3FreeUnsafe(void *pOld){
18991   Mem3Block *p = (Mem3Block*)pOld;
18992   int i;
18993   u32 size, x;
18994   assert( sqlite3_mutex_held(mem3.mutex) );
18995   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
18996   i = p - mem3.aPool;
18997   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
18998   size = mem3.aPool[i-1].u.hdr.size4x/4;
18999   assert( i+size<=mem3.nPool+1 );
19000   mem3.aPool[i-1].u.hdr.size4x &= ~1;
19001   mem3.aPool[i+size-1].u.hdr.prevSize = size;
19002   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
19003   memsys3Link(i);
19004
19005   /* Try to expand the master using the newly freed chunk */
19006   if( mem3.iMaster ){
19007     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
19008       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
19009       mem3.iMaster -= size;
19010       mem3.szMaster += size;
19011       memsys3Unlink(mem3.iMaster);
19012       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
19013       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
19014       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
19015     }
19016     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
19017     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
19018       memsys3Unlink(mem3.iMaster+mem3.szMaster);
19019       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
19020       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
19021       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
19022     }
19023   }
19024 }
19025
19026 /*
19027 ** Return the size of an outstanding allocation, in bytes.  The
19028 ** size returned omits the 8-byte header overhead.  This only
19029 ** works for chunks that are currently checked out.
19030 */
19031 static int memsys3Size(void *p){
19032   Mem3Block *pBlock;
19033   if( p==0 ) return 0;
19034   pBlock = (Mem3Block*)p;
19035   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
19036   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
19037 }
19038
19039 /*
19040 ** Round up a request size to the next valid allocation size.
19041 */
19042 static int memsys3Roundup(int n){
19043   if( n<=12 ){
19044     return 12;
19045   }else{
19046     return ((n+11)&~7) - 4;
19047   }
19048 }
19049
19050 /*
19051 ** Allocate nBytes of memory.
19052 */
19053 static void *memsys3Malloc(int nBytes){
19054   sqlite3_int64 *p;
19055   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
19056   memsys3Enter();
19057   p = memsys3MallocUnsafe(nBytes);
19058   memsys3Leave();
19059   return (void*)p;
19060 }
19061
19062 /*
19063 ** Free memory.
19064 */
19065 static void memsys3Free(void *pPrior){
19066   assert( pPrior );
19067   memsys3Enter();
19068   memsys3FreeUnsafe(pPrior);
19069   memsys3Leave();
19070 }
19071
19072 /*
19073 ** Change the size of an existing memory allocation
19074 */
19075 static void *memsys3Realloc(void *pPrior, int nBytes){
19076   int nOld;
19077   void *p;
19078   if( pPrior==0 ){
19079     return sqlite3_malloc(nBytes);
19080   }
19081   if( nBytes<=0 ){
19082     sqlite3_free(pPrior);
19083     return 0;
19084   }
19085   nOld = memsys3Size(pPrior);
19086   if( nBytes<=nOld && nBytes>=nOld-128 ){
19087     return pPrior;
19088   }
19089   memsys3Enter();
19090   p = memsys3MallocUnsafe(nBytes);
19091   if( p ){
19092     if( nOld<nBytes ){
19093       memcpy(p, pPrior, nOld);
19094     }else{
19095       memcpy(p, pPrior, nBytes);
19096     }
19097     memsys3FreeUnsafe(pPrior);
19098   }
19099   memsys3Leave();
19100   return p;
19101 }
19102
19103 /*
19104 ** Initialize this module.
19105 */
19106 static int memsys3Init(void *NotUsed){
19107   UNUSED_PARAMETER(NotUsed);
19108   if( !sqlite3GlobalConfig.pHeap ){
19109     return SQLITE_ERROR;
19110   }
19111
19112   /* Store a pointer to the memory block in global structure mem3. */
19113   assert( sizeof(Mem3Block)==8 );
19114   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
19115   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
19116
19117   /* Initialize the master block. */
19118   mem3.szMaster = mem3.nPool;
19119   mem3.mnMaster = mem3.szMaster;
19120   mem3.iMaster = 1;
19121   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
19122   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
19123   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
19124
19125   return SQLITE_OK;
19126 }
19127
19128 /*
19129 ** Deinitialize this module.
19130 */
19131 static void memsys3Shutdown(void *NotUsed){
19132   UNUSED_PARAMETER(NotUsed);
19133   mem3.mutex = 0;
19134   return;
19135 }
19136
19137
19138
19139 /*
19140 ** Open the file indicated and write a log of all unfreed memory
19141 ** allocations into that log.
19142 */
19143 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
19144 #ifdef SQLITE_DEBUG
19145   FILE *out;
19146   u32 i, j;
19147   u32 size;
19148   if( zFilename==0 || zFilename[0]==0 ){
19149     out = stdout;
19150   }else{
19151     out = fopen(zFilename, "w");
19152     if( out==0 ){
19153       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
19154                       zFilename);
19155       return;
19156     }
19157   }
19158   memsys3Enter();
19159   fprintf(out, "CHUNKS:\n");
19160   for(i=1; i<=mem3.nPool; i+=size/4){
19161     size = mem3.aPool[i-1].u.hdr.size4x;
19162     if( size/4<=1 ){
19163       fprintf(out, "%p size error\n", &mem3.aPool[i]);
19164       assert( 0 );
19165       break;
19166     }
19167     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
19168       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
19169       assert( 0 );
19170       break;
19171     }
19172     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
19173       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
19174       assert( 0 );
19175       break;
19176     }
19177     if( size&1 ){
19178       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
19179     }else{
19180       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
19181                   i==mem3.iMaster ? " **master**" : "");
19182     }
19183   }
19184   for(i=0; i<MX_SMALL-1; i++){
19185     if( mem3.aiSmall[i]==0 ) continue;
19186     fprintf(out, "small(%2d):", i);
19187     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
19188       fprintf(out, " %p(%d)", &mem3.aPool[j],
19189               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
19190     }
19191     fprintf(out, "\n");
19192   }
19193   for(i=0; i<N_HASH; i++){
19194     if( mem3.aiHash[i]==0 ) continue;
19195     fprintf(out, "hash(%2d):", i);
19196     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
19197       fprintf(out, " %p(%d)", &mem3.aPool[j],
19198               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
19199     }
19200     fprintf(out, "\n");
19201   }
19202   fprintf(out, "master=%d\n", mem3.iMaster);
19203   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
19204   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
19205   sqlite3_mutex_leave(mem3.mutex);
19206   if( out==stdout ){
19207     fflush(stdout);
19208   }else{
19209     fclose(out);
19210   }
19211 #else
19212   UNUSED_PARAMETER(zFilename);
19213 #endif
19214 }
19215
19216 /*
19217 ** This routine is the only routine in this file with external
19218 ** linkage.
19219 **
19220 ** Populate the low-level memory allocation function pointers in
19221 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
19222 ** arguments specify the block of memory to manage.
19223 **
19224 ** This routine is only called by sqlite3_config(), and therefore
19225 ** is not required to be threadsafe (it is not).
19226 */
19227 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
19228   static const sqlite3_mem_methods mempoolMethods = {
19229      memsys3Malloc,
19230      memsys3Free,
19231      memsys3Realloc,
19232      memsys3Size,
19233      memsys3Roundup,
19234      memsys3Init,
19235      memsys3Shutdown,
19236      0
19237   };
19238   return &mempoolMethods;
19239 }
19240
19241 #endif /* SQLITE_ENABLE_MEMSYS3 */
19242
19243 /************** End of mem3.c ************************************************/
19244 /************** Begin file mem5.c ********************************************/
19245 /*
19246 ** 2007 October 14
19247 **
19248 ** The author disclaims copyright to this source code.  In place of
19249 ** a legal notice, here is a blessing:
19250 **
19251 **    May you do good and not evil.
19252 **    May you find forgiveness for yourself and forgive others.
19253 **    May you share freely, never taking more than you give.
19254 **
19255 *************************************************************************
19256 ** This file contains the C functions that implement a memory
19257 ** allocation subsystem for use by SQLite.
19258 **
19259 ** This version of the memory allocation subsystem omits all
19260 ** use of malloc(). The application gives SQLite a block of memory
19261 ** before calling sqlite3_initialize() from which allocations
19262 ** are made and returned by the xMalloc() and xRealloc()
19263 ** implementations. Once sqlite3_initialize() has been called,
19264 ** the amount of memory available to SQLite is fixed and cannot
19265 ** be changed.
19266 **
19267 ** This version of the memory allocation subsystem is included
19268 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
19269 **
19270 ** This memory allocator uses the following algorithm:
19271 **
19272 **   1.  All memory allocations sizes are rounded up to a power of 2.
19273 **
19274 **   2.  If two adjacent free blocks are the halves of a larger block,
19275 **       then the two blocks are coalesed into the single larger block.
19276 **
19277 **   3.  New memory is allocated from the first available free block.
19278 **
19279 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
19280 ** Concerning Dynamic Storage Allocation". Journal of the Association for
19281 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
19282 **
19283 ** Let n be the size of the largest allocation divided by the minimum
19284 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
19285 ** be the maximum amount of memory ever outstanding at one time.  Let
19286 ** N be the total amount of memory available for allocation.  Robson
19287 ** proved that this memory allocator will never breakdown due to
19288 ** fragmentation as long as the following constraint holds:
19289 **
19290 **      N >=  M*(1 + log2(n)/2) - n + 1
19291 **
19292 ** The sqlite3_status() logic tracks the maximum values of n and M so
19293 ** that an application can, at any time, verify this constraint.
19294 */
19295
19296 /*
19297 ** This version of the memory allocator is used only when
19298 ** SQLITE_ENABLE_MEMSYS5 is defined.
19299 */
19300 #ifdef SQLITE_ENABLE_MEMSYS5
19301
19302 /*
19303 ** A minimum allocation is an instance of the following structure.
19304 ** Larger allocations are an array of these structures where the
19305 ** size of the array is a power of 2.
19306 **
19307 ** The size of this object must be a power of two.  That fact is
19308 ** verified in memsys5Init().
19309 */
19310 typedef struct Mem5Link Mem5Link;
19311 struct Mem5Link {
19312   int next;       /* Index of next free chunk */
19313   int prev;       /* Index of previous free chunk */
19314 };
19315
19316 /*
19317 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
19318 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
19319 ** it is not actually possible to reach this limit.
19320 */
19321 #define LOGMAX 30
19322
19323 /*
19324 ** Masks used for mem5.aCtrl[] elements.
19325 */
19326 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
19327 #define CTRL_FREE     0x20    /* True if not checked out */
19328
19329 /*
19330 ** All of the static variables used by this module are collected
19331 ** into a single structure named "mem5".  This is to keep the
19332 ** static variables organized and to reduce namespace pollution
19333 ** when this module is combined with other in the amalgamation.
19334 */
19335 static SQLITE_WSD struct Mem5Global {
19336   /*
19337   ** Memory available for allocation
19338   */
19339   int szAtom;      /* Smallest possible allocation in bytes */
19340   int nBlock;      /* Number of szAtom sized blocks in zPool */
19341   u8 *zPool;       /* Memory available to be allocated */
19342
19343   /*
19344   ** Mutex to control access to the memory allocation subsystem.
19345   */
19346   sqlite3_mutex *mutex;
19347
19348   /*
19349   ** Performance statistics
19350   */
19351   u64 nAlloc;         /* Total number of calls to malloc */
19352   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
19353   u64 totalExcess;    /* Total internal fragmentation */
19354   u32 currentOut;     /* Current checkout, including internal fragmentation */
19355   u32 currentCount;   /* Current number of distinct checkouts */
19356   u32 maxOut;         /* Maximum instantaneous currentOut */
19357   u32 maxCount;       /* Maximum instantaneous currentCount */
19358   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
19359
19360   /*
19361   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
19362   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
19363   ** and so forth.
19364   */
19365   int aiFreelist[LOGMAX+1];
19366
19367   /*
19368   ** Space for tracking which blocks are checked out and the size
19369   ** of each block.  One byte per block.
19370   */
19371   u8 *aCtrl;
19372
19373 } mem5;
19374
19375 /*
19376 ** Access the static variable through a macro for SQLITE_OMIT_WSD
19377 */
19378 #define mem5 GLOBAL(struct Mem5Global, mem5)
19379
19380 /*
19381 ** Assuming mem5.zPool is divided up into an array of Mem5Link
19382 ** structures, return a pointer to the idx-th such lik.
19383 */
19384 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
19385
19386 /*
19387 ** Unlink the chunk at mem5.aPool[i] from list it is currently
19388 ** on.  It should be found on mem5.aiFreelist[iLogsize].
19389 */
19390 static void memsys5Unlink(int i, int iLogsize){
19391   int next, prev;
19392   assert( i>=0 && i<mem5.nBlock );
19393   assert( iLogsize>=0 && iLogsize<=LOGMAX );
19394   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
19395
19396   next = MEM5LINK(i)->next;
19397   prev = MEM5LINK(i)->prev;
19398   if( prev<0 ){
19399     mem5.aiFreelist[iLogsize] = next;
19400   }else{
19401     MEM5LINK(prev)->next = next;
19402   }
19403   if( next>=0 ){
19404     MEM5LINK(next)->prev = prev;
19405   }
19406 }
19407
19408 /*
19409 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
19410 ** free list.
19411 */
19412 static void memsys5Link(int i, int iLogsize){
19413   int x;
19414   assert( sqlite3_mutex_held(mem5.mutex) );
19415   assert( i>=0 && i<mem5.nBlock );
19416   assert( iLogsize>=0 && iLogsize<=LOGMAX );
19417   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
19418
19419   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
19420   MEM5LINK(i)->prev = -1;
19421   if( x>=0 ){
19422     assert( x<mem5.nBlock );
19423     MEM5LINK(x)->prev = i;
19424   }
19425   mem5.aiFreelist[iLogsize] = i;
19426 }
19427
19428 /*
19429 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
19430 ** will already be held (obtained by code in malloc.c) if
19431 ** sqlite3GlobalConfig.bMemStat is true.
19432 */
19433 static void memsys5Enter(void){
19434   sqlite3_mutex_enter(mem5.mutex);
19435 }
19436 static void memsys5Leave(void){
19437   sqlite3_mutex_leave(mem5.mutex);
19438 }
19439
19440 /*
19441 ** Return the size of an outstanding allocation, in bytes.  The
19442 ** size returned omits the 8-byte header overhead.  This only
19443 ** works for chunks that are currently checked out.
19444 */
19445 static int memsys5Size(void *p){
19446   int iSize = 0;
19447   if( p ){
19448     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
19449     assert( i>=0 && i<mem5.nBlock );
19450     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
19451   }
19452   return iSize;
19453 }
19454
19455 /*
19456 ** Find the first entry on the freelist iLogsize.  Unlink that
19457 ** entry and return its index.
19458 */
19459 static int memsys5UnlinkFirst(int iLogsize){
19460   int i;
19461   int iFirst;
19462
19463   assert( iLogsize>=0 && iLogsize<=LOGMAX );
19464   i = iFirst = mem5.aiFreelist[iLogsize];
19465   assert( iFirst>=0 );
19466   while( i>0 ){
19467     if( i<iFirst ) iFirst = i;
19468     i = MEM5LINK(i)->next;
19469   }
19470   memsys5Unlink(iFirst, iLogsize);
19471   return iFirst;
19472 }
19473
19474 /*
19475 ** Return a block of memory of at least nBytes in size.
19476 ** Return NULL if unable.  Return NULL if nBytes==0.
19477 **
19478 ** The caller guarantees that nByte positive.
19479 **
19480 ** The caller has obtained a mutex prior to invoking this
19481 ** routine so there is never any chance that two or more
19482 ** threads can be in this routine at the same time.
19483 */
19484 static void *memsys5MallocUnsafe(int nByte){
19485   int i;           /* Index of a mem5.aPool[] slot */
19486   int iBin;        /* Index into mem5.aiFreelist[] */
19487   int iFullSz;     /* Size of allocation rounded up to power of 2 */
19488   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
19489
19490   /* nByte must be a positive */
19491   assert( nByte>0 );
19492
19493   /* Keep track of the maximum allocation request.  Even unfulfilled
19494   ** requests are counted */
19495   if( (u32)nByte>mem5.maxRequest ){
19496     mem5.maxRequest = nByte;
19497   }
19498
19499   /* Abort if the requested allocation size is larger than the largest
19500   ** power of two that we can represent using 32-bit signed integers.
19501   */
19502   if( nByte > 0x40000000 ){
19503     return 0;
19504   }
19505
19506   /* Round nByte up to the next valid power of two */
19507   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
19508
19509   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
19510   ** block.  If not, then split a block of the next larger power of
19511   ** two in order to create a new free block of size iLogsize.
19512   */
19513   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
19514   if( iBin>LOGMAX ){
19515     testcase( sqlite3GlobalConfig.xLog!=0 );
19516     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
19517     return 0;
19518   }
19519   i = memsys5UnlinkFirst(iBin);
19520   while( iBin>iLogsize ){
19521     int newSize;
19522
19523     iBin--;
19524     newSize = 1 << iBin;
19525     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
19526     memsys5Link(i+newSize, iBin);
19527   }
19528   mem5.aCtrl[i] = iLogsize;
19529
19530   /* Update allocator performance statistics. */
19531   mem5.nAlloc++;
19532   mem5.totalAlloc += iFullSz;
19533   mem5.totalExcess += iFullSz - nByte;
19534   mem5.currentCount++;
19535   mem5.currentOut += iFullSz;
19536   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
19537   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
19538
19539   /* Return a pointer to the allocated memory. */
19540   return (void*)&mem5.zPool[i*mem5.szAtom];
19541 }
19542
19543 /*
19544 ** Free an outstanding memory allocation.
19545 */
19546 static void memsys5FreeUnsafe(void *pOld){
19547   u32 size, iLogsize;
19548   int iBlock;
19549
19550   /* Set iBlock to the index of the block pointed to by pOld in
19551   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
19552   */
19553   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
19554
19555   /* Check that the pointer pOld points to a valid, non-free block. */
19556   assert( iBlock>=0 && iBlock<mem5.nBlock );
19557   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
19558   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
19559
19560   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
19561   size = 1<<iLogsize;
19562   assert( iBlock+size-1<(u32)mem5.nBlock );
19563
19564   mem5.aCtrl[iBlock] |= CTRL_FREE;
19565   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
19566   assert( mem5.currentCount>0 );
19567   assert( mem5.currentOut>=(size*mem5.szAtom) );
19568   mem5.currentCount--;
19569   mem5.currentOut -= size*mem5.szAtom;
19570   assert( mem5.currentOut>0 || mem5.currentCount==0 );
19571   assert( mem5.currentCount>0 || mem5.currentOut==0 );
19572
19573   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
19574   while( ALWAYS(iLogsize<LOGMAX) ){
19575     int iBuddy;
19576     if( (iBlock>>iLogsize) & 1 ){
19577       iBuddy = iBlock - size;
19578     }else{
19579       iBuddy = iBlock + size;
19580     }
19581     assert( iBuddy>=0 );
19582     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
19583     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
19584     memsys5Unlink(iBuddy, iLogsize);
19585     iLogsize++;
19586     if( iBuddy<iBlock ){
19587       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
19588       mem5.aCtrl[iBlock] = 0;
19589       iBlock = iBuddy;
19590     }else{
19591       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
19592       mem5.aCtrl[iBuddy] = 0;
19593     }
19594     size *= 2;
19595   }
19596   memsys5Link(iBlock, iLogsize);
19597 }
19598
19599 /*
19600 ** Allocate nBytes of memory
19601 */
19602 static void *memsys5Malloc(int nBytes){
19603   sqlite3_int64 *p = 0;
19604   if( nBytes>0 ){
19605     memsys5Enter();
19606     p = memsys5MallocUnsafe(nBytes);
19607     memsys5Leave();
19608   }
19609   return (void*)p;
19610 }
19611
19612 /*
19613 ** Free memory.
19614 **
19615 ** The outer layer memory allocator prevents this routine from
19616 ** being called with pPrior==0.
19617 */
19618 static void memsys5Free(void *pPrior){
19619   assert( pPrior!=0 );
19620   memsys5Enter();
19621   memsys5FreeUnsafe(pPrior);
19622   memsys5Leave();
19623 }
19624
19625 /*
19626 ** Change the size of an existing memory allocation.
19627 **
19628 ** The outer layer memory allocator prevents this routine from
19629 ** being called with pPrior==0.
19630 **
19631 ** nBytes is always a value obtained from a prior call to
19632 ** memsys5Round().  Hence nBytes is always a non-negative power
19633 ** of two.  If nBytes==0 that means that an oversize allocation
19634 ** (an allocation larger than 0x40000000) was requested and this
19635 ** routine should return 0 without freeing pPrior.
19636 */
19637 static void *memsys5Realloc(void *pPrior, int nBytes){
19638   int nOld;
19639   void *p;
19640   assert( pPrior!=0 );
19641   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
19642   assert( nBytes>=0 );
19643   if( nBytes==0 ){
19644     return 0;
19645   }
19646   nOld = memsys5Size(pPrior);
19647   if( nBytes<=nOld ){
19648     return pPrior;
19649   }
19650   memsys5Enter();
19651   p = memsys5MallocUnsafe(nBytes);
19652   if( p ){
19653     memcpy(p, pPrior, nOld);
19654     memsys5FreeUnsafe(pPrior);
19655   }
19656   memsys5Leave();
19657   return p;
19658 }
19659
19660 /*
19661 ** Round up a request size to the next valid allocation size.  If
19662 ** the allocation is too large to be handled by this allocation system,
19663 ** return 0.
19664 **
19665 ** All allocations must be a power of two and must be expressed by a
19666 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
19667 ** or 1073741824 bytes.
19668 */
19669 static int memsys5Roundup(int n){
19670   int iFullSz;
19671   if( n > 0x40000000 ) return 0;
19672   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
19673   return iFullSz;
19674 }
19675
19676 /*
19677 ** Return the ceiling of the logarithm base 2 of iValue.
19678 **
19679 ** Examples:   memsys5Log(1) -> 0
19680 **             memsys5Log(2) -> 1
19681 **             memsys5Log(4) -> 2
19682 **             memsys5Log(5) -> 3
19683 **             memsys5Log(8) -> 3
19684 **             memsys5Log(9) -> 4
19685 */
19686 static int memsys5Log(int iValue){
19687   int iLog;
19688   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
19689   return iLog;
19690 }
19691
19692 /*
19693 ** Initialize the memory allocator.
19694 **
19695 ** This routine is not threadsafe.  The caller must be holding a mutex
19696 ** to prevent multiple threads from entering at the same time.
19697 */
19698 static int memsys5Init(void *NotUsed){
19699   int ii;            /* Loop counter */
19700   int nByte;         /* Number of bytes of memory available to this allocator */
19701   u8 *zByte;         /* Memory usable by this allocator */
19702   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
19703   int iOffset;       /* An offset into mem5.aCtrl[] */
19704
19705   UNUSED_PARAMETER(NotUsed);
19706
19707   /* For the purposes of this routine, disable the mutex */
19708   mem5.mutex = 0;
19709
19710   /* The size of a Mem5Link object must be a power of two.  Verify that
19711   ** this is case.
19712   */
19713   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
19714
19715   nByte = sqlite3GlobalConfig.nHeap;
19716   zByte = (u8*)sqlite3GlobalConfig.pHeap;
19717   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
19718
19719   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
19720   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
19721   mem5.szAtom = (1<<nMinLog);
19722   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
19723     mem5.szAtom = mem5.szAtom << 1;
19724   }
19725
19726   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
19727   mem5.zPool = zByte;
19728   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
19729
19730   for(ii=0; ii<=LOGMAX; ii++){
19731     mem5.aiFreelist[ii] = -1;
19732   }
19733
19734   iOffset = 0;
19735   for(ii=LOGMAX; ii>=0; ii--){
19736     int nAlloc = (1<<ii);
19737     if( (iOffset+nAlloc)<=mem5.nBlock ){
19738       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
19739       memsys5Link(iOffset, ii);
19740       iOffset += nAlloc;
19741     }
19742     assert((iOffset+nAlloc)>mem5.nBlock);
19743   }
19744
19745   /* If a mutex is required for normal operation, allocate one */
19746   if( sqlite3GlobalConfig.bMemstat==0 ){
19747     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
19748   }
19749
19750   return SQLITE_OK;
19751 }
19752
19753 /*
19754 ** Deinitialize this module.
19755 */
19756 static void memsys5Shutdown(void *NotUsed){
19757   UNUSED_PARAMETER(NotUsed);
19758   mem5.mutex = 0;
19759   return;
19760 }
19761
19762 #ifdef SQLITE_TEST
19763 /*
19764 ** Open the file indicated and write a log of all unfreed memory
19765 ** allocations into that log.
19766 */
19767 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
19768   FILE *out;
19769   int i, j, n;
19770   int nMinLog;
19771
19772   if( zFilename==0 || zFilename[0]==0 ){
19773     out = stdout;
19774   }else{
19775     out = fopen(zFilename, "w");
19776     if( out==0 ){
19777       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
19778                       zFilename);
19779       return;
19780     }
19781   }
19782   memsys5Enter();
19783   nMinLog = memsys5Log(mem5.szAtom);
19784   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
19785     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
19786     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
19787   }
19788   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
19789   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
19790   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
19791   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
19792   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
19793   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
19794   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
19795   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
19796   memsys5Leave();
19797   if( out==stdout ){
19798     fflush(stdout);
19799   }else{
19800     fclose(out);
19801   }
19802 }
19803 #endif
19804
19805 /*
19806 ** This routine is the only routine in this file with external
19807 ** linkage. It returns a pointer to a static sqlite3_mem_methods
19808 ** struct populated with the memsys5 methods.
19809 */
19810 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
19811   static const sqlite3_mem_methods memsys5Methods = {
19812      memsys5Malloc,
19813      memsys5Free,
19814      memsys5Realloc,
19815      memsys5Size,
19816      memsys5Roundup,
19817      memsys5Init,
19818      memsys5Shutdown,
19819      0
19820   };
19821   return &memsys5Methods;
19822 }
19823
19824 #endif /* SQLITE_ENABLE_MEMSYS5 */
19825
19826 /************** End of mem5.c ************************************************/
19827 /************** Begin file mutex.c *******************************************/
19828 /*
19829 ** 2007 August 14
19830 **
19831 ** The author disclaims copyright to this source code.  In place of
19832 ** a legal notice, here is a blessing:
19833 **
19834 **    May you do good and not evil.
19835 **    May you find forgiveness for yourself and forgive others.
19836 **    May you share freely, never taking more than you give.
19837 **
19838 *************************************************************************
19839 ** This file contains the C functions that implement mutexes.
19840 **
19841 ** This file contains code that is common across all mutex implementations.
19842 */
19843
19844 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
19845 /*
19846 ** For debugging purposes, record when the mutex subsystem is initialized
19847 ** and uninitialized so that we can assert() if there is an attempt to
19848 ** allocate a mutex while the system is uninitialized.
19849 */
19850 static SQLITE_WSD int mutexIsInit = 0;
19851 #endif /* SQLITE_DEBUG */
19852
19853
19854 #ifndef SQLITE_MUTEX_OMIT
19855 /*
19856 ** Initialize the mutex system.
19857 */
19858 SQLITE_PRIVATE int sqlite3MutexInit(void){
19859   int rc = SQLITE_OK;
19860   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
19861     /* If the xMutexAlloc method has not been set, then the user did not
19862     ** install a mutex implementation via sqlite3_config() prior to
19863     ** sqlite3_initialize() being called. This block copies pointers to
19864     ** the default implementation into the sqlite3GlobalConfig structure.
19865     */
19866     sqlite3_mutex_methods const *pFrom;
19867     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
19868
19869     if( sqlite3GlobalConfig.bCoreMutex ){
19870       pFrom = sqlite3DefaultMutex();
19871     }else{
19872       pFrom = sqlite3NoopMutex();
19873     }
19874     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
19875     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
19876            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
19877     pTo->xMutexAlloc = pFrom->xMutexAlloc;
19878   }
19879   rc = sqlite3GlobalConfig.mutex.xMutexInit();
19880
19881 #ifdef SQLITE_DEBUG
19882   GLOBAL(int, mutexIsInit) = 1;
19883 #endif
19884
19885   return rc;
19886 }
19887
19888 /*
19889 ** Shutdown the mutex system. This call frees resources allocated by
19890 ** sqlite3MutexInit().
19891 */
19892 SQLITE_PRIVATE int sqlite3MutexEnd(void){
19893   int rc = SQLITE_OK;
19894   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
19895     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
19896   }
19897
19898 #ifdef SQLITE_DEBUG
19899   GLOBAL(int, mutexIsInit) = 0;
19900 #endif
19901
19902   return rc;
19903 }
19904
19905 /*
19906 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
19907 */
19908 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
19909 #ifndef SQLITE_OMIT_AUTOINIT
19910   if( sqlite3_initialize() ) return 0;
19911 #endif
19912   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19913 }
19914
19915 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
19916   if( !sqlite3GlobalConfig.bCoreMutex ){
19917     return 0;
19918   }
19919   assert( GLOBAL(int, mutexIsInit) );
19920   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19921 }
19922
19923 /*
19924 ** Free a dynamic mutex.
19925 */
19926 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
19927   if( p ){
19928     sqlite3GlobalConfig.mutex.xMutexFree(p);
19929   }
19930 }
19931
19932 /*
19933 ** Obtain the mutex p. If some other thread already has the mutex, block
19934 ** until it can be obtained.
19935 */
19936 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
19937   if( p ){
19938     sqlite3GlobalConfig.mutex.xMutexEnter(p);
19939   }
19940 }
19941
19942 /*
19943 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
19944 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
19945 */
19946 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
19947   int rc = SQLITE_OK;
19948   if( p ){
19949     return sqlite3GlobalConfig.mutex.xMutexTry(p);
19950   }
19951   return rc;
19952 }
19953
19954 /*
19955 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
19956 ** entered by the same thread.  The behavior is undefined if the mutex
19957 ** is not currently entered. If a NULL pointer is passed as an argument
19958 ** this function is a no-op.
19959 */
19960 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
19961   if( p ){
19962     sqlite3GlobalConfig.mutex.xMutexLeave(p);
19963   }
19964 }
19965
19966 #ifndef NDEBUG
19967 /*
19968 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19969 ** intended for use inside assert() statements.
19970 */
19971 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
19972   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
19973 }
19974 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
19975   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
19976 }
19977 #endif
19978
19979 #endif /* !defined(SQLITE_MUTEX_OMIT) */
19980
19981 /************** End of mutex.c ***********************************************/
19982 /************** Begin file mutex_noop.c **************************************/
19983 /*
19984 ** 2008 October 07
19985 **
19986 ** The author disclaims copyright to this source code.  In place of
19987 ** a legal notice, here is a blessing:
19988 **
19989 **    May you do good and not evil.
19990 **    May you find forgiveness for yourself and forgive others.
19991 **    May you share freely, never taking more than you give.
19992 **
19993 *************************************************************************
19994 ** This file contains the C functions that implement mutexes.
19995 **
19996 ** This implementation in this file does not provide any mutual
19997 ** exclusion and is thus suitable for use only in applications
19998 ** that use SQLite in a single thread.  The routines defined
19999 ** here are place-holders.  Applications can substitute working
20000 ** mutex routines at start-time using the
20001 **
20002 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
20003 **
20004 ** interface.
20005 **
20006 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
20007 ** that does error checking on mutexes to make sure they are being
20008 ** called correctly.
20009 */
20010
20011 #ifndef SQLITE_MUTEX_OMIT
20012
20013 #ifndef SQLITE_DEBUG
20014 /*
20015 ** Stub routines for all mutex methods.
20016 **
20017 ** This routines provide no mutual exclusion or error checking.
20018 */
20019 static int noopMutexInit(void){ return SQLITE_OK; }
20020 static int noopMutexEnd(void){ return SQLITE_OK; }
20021 static sqlite3_mutex *noopMutexAlloc(int id){
20022   UNUSED_PARAMETER(id);
20023   return (sqlite3_mutex*)8;
20024 }
20025 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20026 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20027 static int noopMutexTry(sqlite3_mutex *p){
20028   UNUSED_PARAMETER(p);
20029   return SQLITE_OK;
20030 }
20031 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
20032
20033 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
20034   static const sqlite3_mutex_methods sMutex = {
20035     noopMutexInit,
20036     noopMutexEnd,
20037     noopMutexAlloc,
20038     noopMutexFree,
20039     noopMutexEnter,
20040     noopMutexTry,
20041     noopMutexLeave,
20042
20043     0,
20044     0,
20045   };
20046
20047   return &sMutex;
20048 }
20049 #endif /* !SQLITE_DEBUG */
20050
20051 #ifdef SQLITE_DEBUG
20052 /*
20053 ** In this implementation, error checking is provided for testing
20054 ** and debugging purposes.  The mutexes still do not provide any
20055 ** mutual exclusion.
20056 */
20057
20058 /*
20059 ** The mutex object
20060 */
20061 typedef struct sqlite3_debug_mutex {
20062   int id;     /* The mutex type */
20063   int cnt;    /* Number of entries without a matching leave */
20064 } sqlite3_debug_mutex;
20065
20066 /*
20067 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20068 ** intended for use inside assert() statements.
20069 */
20070 static int debugMutexHeld(sqlite3_mutex *pX){
20071   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20072   return p==0 || p->cnt>0;
20073 }
20074 static int debugMutexNotheld(sqlite3_mutex *pX){
20075   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20076   return p==0 || p->cnt==0;
20077 }
20078
20079 /*
20080 ** Initialize and deinitialize the mutex subsystem.
20081 */
20082 static int debugMutexInit(void){ return SQLITE_OK; }
20083 static int debugMutexEnd(void){ return SQLITE_OK; }
20084
20085 /*
20086 ** The sqlite3_mutex_alloc() routine allocates a new
20087 ** mutex and returns a pointer to it.  If it returns NULL
20088 ** that means that a mutex could not be allocated.
20089 */
20090 static sqlite3_mutex *debugMutexAlloc(int id){
20091   static sqlite3_debug_mutex aStatic[6];
20092   sqlite3_debug_mutex *pNew = 0;
20093   switch( id ){
20094     case SQLITE_MUTEX_FAST:
20095     case SQLITE_MUTEX_RECURSIVE: {
20096       pNew = sqlite3Malloc(sizeof(*pNew));
20097       if( pNew ){
20098         pNew->id = id;
20099         pNew->cnt = 0;
20100       }
20101       break;
20102     }
20103     default: {
20104       assert( id-2 >= 0 );
20105       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
20106       pNew = &aStatic[id-2];
20107       pNew->id = id;
20108       break;
20109     }
20110   }
20111   return (sqlite3_mutex*)pNew;
20112 }
20113
20114 /*
20115 ** This routine deallocates a previously allocated mutex.
20116 */
20117 static void debugMutexFree(sqlite3_mutex *pX){
20118   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20119   assert( p->cnt==0 );
20120   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
20121   sqlite3_free(p);
20122 }
20123
20124 /*
20125 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20126 ** to enter a mutex.  If another thread is already within the mutex,
20127 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20128 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
20129 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
20130 ** be entered multiple times by the same thread.  In such cases the,
20131 ** mutex must be exited an equal number of times before another thread
20132 ** can enter.  If the same thread tries to enter any other kind of mutex
20133 ** more than once, the behavior is undefined.
20134 */
20135 static void debugMutexEnter(sqlite3_mutex *pX){
20136   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20137   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20138   p->cnt++;
20139 }
20140 static int debugMutexTry(sqlite3_mutex *pX){
20141   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20142   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20143   p->cnt++;
20144   return SQLITE_OK;
20145 }
20146
20147 /*
20148 ** The sqlite3_mutex_leave() routine exits a mutex that was
20149 ** previously entered by the same thread.  The behavior
20150 ** is undefined if the mutex is not currently entered or
20151 ** is not currently allocated.  SQLite will never do either.
20152 */
20153 static void debugMutexLeave(sqlite3_mutex *pX){
20154   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
20155   assert( debugMutexHeld(pX) );
20156   p->cnt--;
20157   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
20158 }
20159
20160 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
20161   static const sqlite3_mutex_methods sMutex = {
20162     debugMutexInit,
20163     debugMutexEnd,
20164     debugMutexAlloc,
20165     debugMutexFree,
20166     debugMutexEnter,
20167     debugMutexTry,
20168     debugMutexLeave,
20169
20170     debugMutexHeld,
20171     debugMutexNotheld
20172   };
20173
20174   return &sMutex;
20175 }
20176 #endif /* SQLITE_DEBUG */
20177
20178 /*
20179 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
20180 ** is used regardless of the run-time threadsafety setting.
20181 */
20182 #ifdef SQLITE_MUTEX_NOOP
20183 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20184   return sqlite3NoopMutex();
20185 }
20186 #endif /* defined(SQLITE_MUTEX_NOOP) */
20187 #endif /* !defined(SQLITE_MUTEX_OMIT) */
20188
20189 /************** End of mutex_noop.c ******************************************/
20190 /************** Begin file mutex_unix.c **************************************/
20191 /*
20192 ** 2007 August 28
20193 **
20194 ** The author disclaims copyright to this source code.  In place of
20195 ** a legal notice, here is a blessing:
20196 **
20197 **    May you do good and not evil.
20198 **    May you find forgiveness for yourself and forgive others.
20199 **    May you share freely, never taking more than you give.
20200 **
20201 *************************************************************************
20202 ** This file contains the C functions that implement mutexes for pthreads
20203 */
20204
20205 /*
20206 ** The code in this file is only used if we are compiling threadsafe
20207 ** under unix with pthreads.
20208 **
20209 ** Note that this implementation requires a version of pthreads that
20210 ** supports recursive mutexes.
20211 */
20212 #ifdef SQLITE_MUTEX_PTHREADS
20213
20214 #include <pthread.h>
20215
20216 /*
20217 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
20218 ** are necessary under two condidtions:  (1) Debug builds and (2) using
20219 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
20220 */
20221 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
20222 # define SQLITE_MUTEX_NREF 1
20223 #else
20224 # define SQLITE_MUTEX_NREF 0
20225 #endif
20226
20227 /*
20228 ** Each recursive mutex is an instance of the following structure.
20229 */
20230 struct sqlite3_mutex {
20231   pthread_mutex_t mutex;     /* Mutex controlling the lock */
20232 #if SQLITE_MUTEX_NREF
20233   int id;                    /* Mutex type */
20234   volatile int nRef;         /* Number of entrances */
20235   volatile pthread_t owner;  /* Thread that is within this mutex */
20236   int trace;                 /* True to trace changes */
20237 #endif
20238 };
20239 #if SQLITE_MUTEX_NREF
20240 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
20241 #else
20242 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
20243 #endif
20244
20245 /*
20246 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20247 ** intended for use only inside assert() statements.  On some platforms,
20248 ** there might be race conditions that can cause these routines to
20249 ** deliver incorrect results.  In particular, if pthread_equal() is
20250 ** not an atomic operation, then these routines might delivery
20251 ** incorrect results.  On most platforms, pthread_equal() is a
20252 ** comparison of two integers and is therefore atomic.  But we are
20253 ** told that HPUX is not such a platform.  If so, then these routines
20254 ** will not always work correctly on HPUX.
20255 **
20256 ** On those platforms where pthread_equal() is not atomic, SQLite
20257 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
20258 ** make sure no assert() statements are evaluated and hence these
20259 ** routines are never called.
20260 */
20261 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
20262 static int pthreadMutexHeld(sqlite3_mutex *p){
20263   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
20264 }
20265 static int pthreadMutexNotheld(sqlite3_mutex *p){
20266   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
20267 }
20268 #endif
20269
20270 /*
20271 ** Initialize and deinitialize the mutex subsystem.
20272 */
20273 static int pthreadMutexInit(void){ return SQLITE_OK; }
20274 static int pthreadMutexEnd(void){ return SQLITE_OK; }
20275
20276 /*
20277 ** The sqlite3_mutex_alloc() routine allocates a new
20278 ** mutex and returns a pointer to it.  If it returns NULL
20279 ** that means that a mutex could not be allocated.  SQLite
20280 ** will unwind its stack and return an error.  The argument
20281 ** to sqlite3_mutex_alloc() is one of these integer constants:
20282 **
20283 ** <ul>
20284 ** <li>  SQLITE_MUTEX_FAST
20285 ** <li>  SQLITE_MUTEX_RECURSIVE
20286 ** <li>  SQLITE_MUTEX_STATIC_MASTER
20287 ** <li>  SQLITE_MUTEX_STATIC_MEM
20288 ** <li>  SQLITE_MUTEX_STATIC_MEM2
20289 ** <li>  SQLITE_MUTEX_STATIC_PRNG
20290 ** <li>  SQLITE_MUTEX_STATIC_LRU
20291 ** <li>  SQLITE_MUTEX_STATIC_PMEM
20292 ** </ul>
20293 **
20294 ** The first two constants cause sqlite3_mutex_alloc() to create
20295 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
20296 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
20297 ** The mutex implementation does not need to make a distinction
20298 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
20299 ** not want to.  But SQLite will only request a recursive mutex in
20300 ** cases where it really needs one.  If a faster non-recursive mutex
20301 ** implementation is available on the host platform, the mutex subsystem
20302 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
20303 **
20304 ** The other allowed parameters to sqlite3_mutex_alloc() each return
20305 ** a pointer to a static preexisting mutex.  Six static mutexes are
20306 ** used by the current version of SQLite.  Future versions of SQLite
20307 ** may add additional static mutexes.  Static mutexes are for internal
20308 ** use by SQLite only.  Applications that use SQLite mutexes should
20309 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
20310 ** SQLITE_MUTEX_RECURSIVE.
20311 **
20312 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
20313 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
20314 ** returns a different mutex on every call.  But for the static
20315 ** mutex types, the same mutex is returned on every call that has
20316 ** the same type number.
20317 */
20318 static sqlite3_mutex *pthreadMutexAlloc(int iType){
20319   static sqlite3_mutex staticMutexes[] = {
20320     SQLITE3_MUTEX_INITIALIZER,
20321     SQLITE3_MUTEX_INITIALIZER,
20322     SQLITE3_MUTEX_INITIALIZER,
20323     SQLITE3_MUTEX_INITIALIZER,
20324     SQLITE3_MUTEX_INITIALIZER,
20325     SQLITE3_MUTEX_INITIALIZER
20326   };
20327   sqlite3_mutex *p;
20328   switch( iType ){
20329     case SQLITE_MUTEX_RECURSIVE: {
20330       p = sqlite3MallocZero( sizeof(*p) );
20331       if( p ){
20332 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20333         /* If recursive mutexes are not available, we will have to
20334         ** build our own.  See below. */
20335         pthread_mutex_init(&p->mutex, 0);
20336 #else
20337         /* Use a recursive mutex if it is available */
20338         pthread_mutexattr_t recursiveAttr;
20339         pthread_mutexattr_init(&recursiveAttr);
20340         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
20341         pthread_mutex_init(&p->mutex, &recursiveAttr);
20342         pthread_mutexattr_destroy(&recursiveAttr);
20343 #endif
20344 #if SQLITE_MUTEX_NREF
20345         p->id = iType;
20346 #endif
20347       }
20348       break;
20349     }
20350     case SQLITE_MUTEX_FAST: {
20351       p = sqlite3MallocZero( sizeof(*p) );
20352       if( p ){
20353 #if SQLITE_MUTEX_NREF
20354         p->id = iType;
20355 #endif
20356         pthread_mutex_init(&p->mutex, 0);
20357       }
20358       break;
20359     }
20360     default: {
20361       assert( iType-2 >= 0 );
20362       assert( iType-2 < ArraySize(staticMutexes) );
20363       p = &staticMutexes[iType-2];
20364 #if SQLITE_MUTEX_NREF
20365       p->id = iType;
20366 #endif
20367       break;
20368     }
20369   }
20370   return p;
20371 }
20372
20373
20374 /*
20375 ** This routine deallocates a previously
20376 ** allocated mutex.  SQLite is careful to deallocate every
20377 ** mutex that it allocates.
20378 */
20379 static void pthreadMutexFree(sqlite3_mutex *p){
20380   assert( p->nRef==0 );
20381   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
20382   pthread_mutex_destroy(&p->mutex);
20383   sqlite3_free(p);
20384 }
20385
20386 /*
20387 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20388 ** to enter a mutex.  If another thread is already within the mutex,
20389 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20390 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
20391 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
20392 ** be entered multiple times by the same thread.  In such cases the,
20393 ** mutex must be exited an equal number of times before another thread
20394 ** can enter.  If the same thread tries to enter any other kind of mutex
20395 ** more than once, the behavior is undefined.
20396 */
20397 static void pthreadMutexEnter(sqlite3_mutex *p){
20398   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
20399
20400 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20401   /* If recursive mutexes are not available, then we have to grow
20402   ** our own.  This implementation assumes that pthread_equal()
20403   ** is atomic - that it cannot be deceived into thinking self
20404   ** and p->owner are equal if p->owner changes between two values
20405   ** that are not equal to self while the comparison is taking place.
20406   ** This implementation also assumes a coherent cache - that
20407   ** separate processes cannot read different values from the same
20408   ** address at the same time.  If either of these two conditions
20409   ** are not met, then the mutexes will fail and problems will result.
20410   */
20411   {
20412     pthread_t self = pthread_self();
20413     if( p->nRef>0 && pthread_equal(p->owner, self) ){
20414       p->nRef++;
20415     }else{
20416       pthread_mutex_lock(&p->mutex);
20417       assert( p->nRef==0 );
20418       p->owner = self;
20419       p->nRef = 1;
20420     }
20421   }
20422 #else
20423   /* Use the built-in recursive mutexes if they are available.
20424   */
20425   pthread_mutex_lock(&p->mutex);
20426 #if SQLITE_MUTEX_NREF
20427   assert( p->nRef>0 || p->owner==0 );
20428   p->owner = pthread_self();
20429   p->nRef++;
20430 #endif
20431 #endif
20432
20433 #ifdef SQLITE_DEBUG
20434   if( p->trace ){
20435     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20436   }
20437 #endif
20438 }
20439 static int pthreadMutexTry(sqlite3_mutex *p){
20440   int rc;
20441   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
20442
20443 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20444   /* If recursive mutexes are not available, then we have to grow
20445   ** our own.  This implementation assumes that pthread_equal()
20446   ** is atomic - that it cannot be deceived into thinking self
20447   ** and p->owner are equal if p->owner changes between two values
20448   ** that are not equal to self while the comparison is taking place.
20449   ** This implementation also assumes a coherent cache - that
20450   ** separate processes cannot read different values from the same
20451   ** address at the same time.  If either of these two conditions
20452   ** are not met, then the mutexes will fail and problems will result.
20453   */
20454   {
20455     pthread_t self = pthread_self();
20456     if( p->nRef>0 && pthread_equal(p->owner, self) ){
20457       p->nRef++;
20458       rc = SQLITE_OK;
20459     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
20460       assert( p->nRef==0 );
20461       p->owner = self;
20462       p->nRef = 1;
20463       rc = SQLITE_OK;
20464     }else{
20465       rc = SQLITE_BUSY;
20466     }
20467   }
20468 #else
20469   /* Use the built-in recursive mutexes if they are available.
20470   */
20471   if( pthread_mutex_trylock(&p->mutex)==0 ){
20472 #if SQLITE_MUTEX_NREF
20473     p->owner = pthread_self();
20474     p->nRef++;
20475 #endif
20476     rc = SQLITE_OK;
20477   }else{
20478     rc = SQLITE_BUSY;
20479   }
20480 #endif
20481
20482 #ifdef SQLITE_DEBUG
20483   if( rc==SQLITE_OK && p->trace ){
20484     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20485   }
20486 #endif
20487   return rc;
20488 }
20489
20490 /*
20491 ** The sqlite3_mutex_leave() routine exits a mutex that was
20492 ** previously entered by the same thread.  The behavior
20493 ** is undefined if the mutex is not currently entered or
20494 ** is not currently allocated.  SQLite will never do either.
20495 */
20496 static void pthreadMutexLeave(sqlite3_mutex *p){
20497   assert( pthreadMutexHeld(p) );
20498 #if SQLITE_MUTEX_NREF
20499   p->nRef--;
20500   if( p->nRef==0 ) p->owner = 0;
20501 #endif
20502   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
20503
20504 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
20505   if( p->nRef==0 ){
20506     pthread_mutex_unlock(&p->mutex);
20507   }
20508 #else
20509   pthread_mutex_unlock(&p->mutex);
20510 #endif
20511
20512 #ifdef SQLITE_DEBUG
20513   if( p->trace ){
20514     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20515   }
20516 #endif
20517 }
20518
20519 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20520   static const sqlite3_mutex_methods sMutex = {
20521     pthreadMutexInit,
20522     pthreadMutexEnd,
20523     pthreadMutexAlloc,
20524     pthreadMutexFree,
20525     pthreadMutexEnter,
20526     pthreadMutexTry,
20527     pthreadMutexLeave,
20528 #ifdef SQLITE_DEBUG
20529     pthreadMutexHeld,
20530     pthreadMutexNotheld
20531 #else
20532     0,
20533     0
20534 #endif
20535   };
20536
20537   return &sMutex;
20538 }
20539
20540 #endif /* SQLITE_MUTEX_PTHREADS */
20541
20542 /************** End of mutex_unix.c ******************************************/
20543 /************** Begin file mutex_w32.c ***************************************/
20544 /*
20545 ** 2007 August 14
20546 **
20547 ** The author disclaims copyright to this source code.  In place of
20548 ** a legal notice, here is a blessing:
20549 **
20550 **    May you do good and not evil.
20551 **    May you find forgiveness for yourself and forgive others.
20552 **    May you share freely, never taking more than you give.
20553 **
20554 *************************************************************************
20555 ** This file contains the C functions that implement mutexes for win32
20556 */
20557
20558 /*
20559 ** The code in this file is only used if we are compiling multithreaded
20560 ** on a win32 system.
20561 */
20562 #ifdef SQLITE_MUTEX_W32
20563
20564 /*
20565 ** Each recursive mutex is an instance of the following structure.
20566 */
20567 struct sqlite3_mutex {
20568   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
20569   int id;                    /* Mutex type */
20570 #ifdef SQLITE_DEBUG
20571   volatile int nRef;         /* Number of enterances */
20572   volatile DWORD owner;      /* Thread holding this mutex */
20573   int trace;                 /* True to trace changes */
20574 #endif
20575 };
20576 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
20577 #ifdef SQLITE_DEBUG
20578 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
20579 #else
20580 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
20581 #endif
20582
20583 /*
20584 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
20585 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
20586 **
20587 ** Here is an interesting observation:  Win95, Win98, and WinME lack
20588 ** the LockFileEx() API.  But we can still statically link against that
20589 ** API as long as we don't call it win running Win95/98/ME.  A call to
20590 ** this routine is used to determine if the host is Win95/98/ME or
20591 ** WinNT/2K/XP so that we will know whether or not we can safely call
20592 ** the LockFileEx() API.
20593 **
20594 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
20595 ** which is only available if your application was compiled with
20596 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
20597 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
20598 ** this out as well.
20599 */
20600 #if 0
20601 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
20602 # define mutexIsNT()  (1)
20603 #else
20604   static int mutexIsNT(void){
20605     static int osType = 0;
20606     if( osType==0 ){
20607       OSVERSIONINFO sInfo;
20608       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
20609       GetVersionEx(&sInfo);
20610       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
20611     }
20612     return osType==2;
20613   }
20614 #endif /* SQLITE_OS_WINCE */
20615 #endif
20616
20617 #ifdef SQLITE_DEBUG
20618 /*
20619 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20620 ** intended for use only inside assert() statements.
20621 */
20622 static int winMutexHeld(sqlite3_mutex *p){
20623   return p->nRef!=0 && p->owner==GetCurrentThreadId();
20624 }
20625 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
20626   return p->nRef==0 || p->owner!=tid;
20627 }
20628 static int winMutexNotheld(sqlite3_mutex *p){
20629   DWORD tid = GetCurrentThreadId();
20630   return winMutexNotheld2(p, tid);
20631 }
20632 #endif
20633
20634
20635 /*
20636 ** Initialize and deinitialize the mutex subsystem.
20637 */
20638 static sqlite3_mutex winMutex_staticMutexes[6] = {
20639   SQLITE3_MUTEX_INITIALIZER,
20640   SQLITE3_MUTEX_INITIALIZER,
20641   SQLITE3_MUTEX_INITIALIZER,
20642   SQLITE3_MUTEX_INITIALIZER,
20643   SQLITE3_MUTEX_INITIALIZER,
20644   SQLITE3_MUTEX_INITIALIZER
20645 };
20646 static int winMutex_isInit = 0;
20647 /* As winMutexInit() and winMutexEnd() are called as part
20648 ** of the sqlite3_initialize and sqlite3_shutdown()
20649 ** processing, the "interlocked" magic is probably not
20650 ** strictly necessary.
20651 */
20652 static long winMutex_lock = 0;
20653
20654 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
20655
20656 static int winMutexInit(void){
20657   /* The first to increment to 1 does actual initialization */
20658   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
20659     int i;
20660     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20661 #if SQLITE_OS_WINRT
20662       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
20663 #else
20664       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
20665 #endif
20666     }
20667     winMutex_isInit = 1;
20668   }else{
20669     /* Someone else is in the process of initing the static mutexes */
20670     while( !winMutex_isInit ){
20671       sqlite3_win32_sleep(1);
20672     }
20673   }
20674   return SQLITE_OK;
20675 }
20676
20677 static int winMutexEnd(void){
20678   /* The first to decrement to 0 does actual shutdown
20679   ** (which should be the last to shutdown.) */
20680   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
20681     if( winMutex_isInit==1 ){
20682       int i;
20683       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20684         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
20685       }
20686       winMutex_isInit = 0;
20687     }
20688   }
20689   return SQLITE_OK;
20690 }
20691
20692 /*
20693 ** The sqlite3_mutex_alloc() routine allocates a new
20694 ** mutex and returns a pointer to it.  If it returns NULL
20695 ** that means that a mutex could not be allocated.  SQLite
20696 ** will unwind its stack and return an error.  The argument
20697 ** to sqlite3_mutex_alloc() is one of these integer constants:
20698 **
20699 ** <ul>
20700 ** <li>  SQLITE_MUTEX_FAST
20701 ** <li>  SQLITE_MUTEX_RECURSIVE
20702 ** <li>  SQLITE_MUTEX_STATIC_MASTER
20703 ** <li>  SQLITE_MUTEX_STATIC_MEM
20704 ** <li>  SQLITE_MUTEX_STATIC_MEM2
20705 ** <li>  SQLITE_MUTEX_STATIC_PRNG
20706 ** <li>  SQLITE_MUTEX_STATIC_LRU
20707 ** <li>  SQLITE_MUTEX_STATIC_PMEM
20708 ** </ul>
20709 **
20710 ** The first two constants cause sqlite3_mutex_alloc() to create
20711 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
20712 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
20713 ** The mutex implementation does not need to make a distinction
20714 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
20715 ** not want to.  But SQLite will only request a recursive mutex in
20716 ** cases where it really needs one.  If a faster non-recursive mutex
20717 ** implementation is available on the host platform, the mutex subsystem
20718 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
20719 **
20720 ** The other allowed parameters to sqlite3_mutex_alloc() each return
20721 ** a pointer to a static preexisting mutex.  Six static mutexes are
20722 ** used by the current version of SQLite.  Future versions of SQLite
20723 ** may add additional static mutexes.  Static mutexes are for internal
20724 ** use by SQLite only.  Applications that use SQLite mutexes should
20725 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
20726 ** SQLITE_MUTEX_RECURSIVE.
20727 **
20728 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
20729 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
20730 ** returns a different mutex on every call.  But for the static
20731 ** mutex types, the same mutex is returned on every call that has
20732 ** the same type number.
20733 */
20734 static sqlite3_mutex *winMutexAlloc(int iType){
20735   sqlite3_mutex *p;
20736
20737   switch( iType ){
20738     case SQLITE_MUTEX_FAST:
20739     case SQLITE_MUTEX_RECURSIVE: {
20740       p = sqlite3MallocZero( sizeof(*p) );
20741       if( p ){
20742 #ifdef SQLITE_DEBUG
20743         p->id = iType;
20744 #endif
20745 #if SQLITE_OS_WINRT
20746         InitializeCriticalSectionEx(&p->mutex, 0, 0);
20747 #else
20748         InitializeCriticalSection(&p->mutex);
20749 #endif
20750       }
20751       break;
20752     }
20753     default: {
20754       assert( winMutex_isInit==1 );
20755       assert( iType-2 >= 0 );
20756       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
20757       p = &winMutex_staticMutexes[iType-2];
20758 #ifdef SQLITE_DEBUG
20759       p->id = iType;
20760 #endif
20761       break;
20762     }
20763   }
20764   return p;
20765 }
20766
20767
20768 /*
20769 ** This routine deallocates a previously
20770 ** allocated mutex.  SQLite is careful to deallocate every
20771 ** mutex that it allocates.
20772 */
20773 static void winMutexFree(sqlite3_mutex *p){
20774   assert( p );
20775   assert( p->nRef==0 && p->owner==0 );
20776   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
20777   DeleteCriticalSection(&p->mutex);
20778   sqlite3_free(p);
20779 }
20780
20781 /*
20782 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20783 ** to enter a mutex.  If another thread is already within the mutex,
20784 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20785 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
20786 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
20787 ** be entered multiple times by the same thread.  In such cases the,
20788 ** mutex must be exited an equal number of times before another thread
20789 ** can enter.  If the same thread tries to enter any other kind of mutex
20790 ** more than once, the behavior is undefined.
20791 */
20792 static void winMutexEnter(sqlite3_mutex *p){
20793 #ifdef SQLITE_DEBUG
20794   DWORD tid = GetCurrentThreadId();
20795   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20796 #endif
20797   EnterCriticalSection(&p->mutex);
20798 #ifdef SQLITE_DEBUG
20799   assert( p->nRef>0 || p->owner==0 );
20800   p->owner = tid;
20801   p->nRef++;
20802   if( p->trace ){
20803     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20804   }
20805 #endif
20806 }
20807 static int winMutexTry(sqlite3_mutex *p){
20808 #ifndef NDEBUG
20809   DWORD tid = GetCurrentThreadId();
20810 #endif
20811   int rc = SQLITE_BUSY;
20812   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20813   /*
20814   ** The sqlite3_mutex_try() routine is very rarely used, and when it
20815   ** is used it is merely an optimization.  So it is OK for it to always
20816   ** fail.
20817   **
20818   ** The TryEnterCriticalSection() interface is only available on WinNT.
20819   ** And some windows compilers complain if you try to use it without
20820   ** first doing some #defines that prevent SQLite from building on Win98.
20821   ** For that reason, we will omit this optimization for now.  See
20822   ** ticket #2685.
20823   */
20824 #if 0
20825   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
20826     p->owner = tid;
20827     p->nRef++;
20828     rc = SQLITE_OK;
20829   }
20830 #else
20831   UNUSED_PARAMETER(p);
20832 #endif
20833 #ifdef SQLITE_DEBUG
20834   if( rc==SQLITE_OK && p->trace ){
20835     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20836   }
20837 #endif
20838   return rc;
20839 }
20840
20841 /*
20842 ** The sqlite3_mutex_leave() routine exits a mutex that was
20843 ** previously entered by the same thread.  The behavior
20844 ** is undefined if the mutex is not currently entered or
20845 ** is not currently allocated.  SQLite will never do either.
20846 */
20847 static void winMutexLeave(sqlite3_mutex *p){
20848 #ifndef NDEBUG
20849   DWORD tid = GetCurrentThreadId();
20850   assert( p->nRef>0 );
20851   assert( p->owner==tid );
20852   p->nRef--;
20853   if( p->nRef==0 ) p->owner = 0;
20854   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
20855 #endif
20856   LeaveCriticalSection(&p->mutex);
20857 #ifdef SQLITE_DEBUG
20858   if( p->trace ){
20859     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
20860   }
20861 #endif
20862 }
20863
20864 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20865   static const sqlite3_mutex_methods sMutex = {
20866     winMutexInit,
20867     winMutexEnd,
20868     winMutexAlloc,
20869     winMutexFree,
20870     winMutexEnter,
20871     winMutexTry,
20872     winMutexLeave,
20873 #ifdef SQLITE_DEBUG
20874     winMutexHeld,
20875     winMutexNotheld
20876 #else
20877     0,
20878     0
20879 #endif
20880   };
20881
20882   return &sMutex;
20883 }
20884 #endif /* SQLITE_MUTEX_W32 */
20885
20886 /************** End of mutex_w32.c *******************************************/
20887 /************** Begin file malloc.c ******************************************/
20888 /*
20889 ** 2001 September 15
20890 **
20891 ** The author disclaims copyright to this source code.  In place of
20892 ** a legal notice, here is a blessing:
20893 **
20894 **    May you do good and not evil.
20895 **    May you find forgiveness for yourself and forgive others.
20896 **    May you share freely, never taking more than you give.
20897 **
20898 *************************************************************************
20899 **
20900 ** Memory allocation functions used throughout sqlite.
20901 */
20902 /* #include <stdarg.h> */
20903
20904 /*
20905 ** Attempt to release up to n bytes of non-essential memory currently
20906 ** held by SQLite. An example of non-essential memory is memory used to
20907 ** cache database pages that are not currently in use.
20908 */
20909 SQLITE_API int sqlite3_release_memory(int n){
20910 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20911   return sqlite3PcacheReleaseMemory(n);
20912 #else
20913   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
20914   ** is a no-op returning zero if SQLite is not compiled with
20915   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
20916   UNUSED_PARAMETER(n);
20917   return 0;
20918 #endif
20919 }
20920
20921 /*
20922 ** An instance of the following object records the location of
20923 ** each unused scratch buffer.
20924 */
20925 typedef struct ScratchFreeslot {
20926   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
20927 } ScratchFreeslot;
20928
20929 /*
20930 ** State information local to the memory allocation subsystem.
20931 */
20932 static SQLITE_WSD struct Mem0Global {
20933   sqlite3_mutex *mutex;         /* Mutex to serialize access */
20934
20935   /*
20936   ** The alarm callback and its arguments.  The mem0.mutex lock will
20937   ** be held while the callback is running.  Recursive calls into
20938   ** the memory subsystem are allowed, but no new callbacks will be
20939   ** issued.
20940   */
20941   sqlite3_int64 alarmThreshold;
20942   void (*alarmCallback)(void*, sqlite3_int64,int);
20943   void *alarmArg;
20944
20945   /*
20946   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
20947   ** (so that a range test can be used to determine if an allocation
20948   ** being freed came from pScratch) and a pointer to the list of
20949   ** unused scratch allocations.
20950   */
20951   void *pScratchEnd;
20952   ScratchFreeslot *pScratchFree;
20953   u32 nScratchFree;
20954
20955   /*
20956   ** True if heap is nearly "full" where "full" is defined by the
20957   ** sqlite3_soft_heap_limit() setting.
20958   */
20959   int nearlyFull;
20960 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
20961
20962 #define mem0 GLOBAL(struct Mem0Global, mem0)
20963
20964 /*
20965 ** This routine runs when the memory allocator sees that the
20966 ** total memory allocation is about to exceed the soft heap
20967 ** limit.
20968 */
20969 static void softHeapLimitEnforcer(
20970   void *NotUsed,
20971   sqlite3_int64 NotUsed2,
20972   int allocSize
20973 ){
20974   UNUSED_PARAMETER2(NotUsed, NotUsed2);
20975   sqlite3_release_memory(allocSize);
20976 }
20977
20978 /*
20979 ** Change the alarm callback
20980 */
20981 static int sqlite3MemoryAlarm(
20982   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20983   void *pArg,
20984   sqlite3_int64 iThreshold
20985 ){
20986   int nUsed;
20987   sqlite3_mutex_enter(mem0.mutex);
20988   mem0.alarmCallback = xCallback;
20989   mem0.alarmArg = pArg;
20990   mem0.alarmThreshold = iThreshold;
20991   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20992   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20993   sqlite3_mutex_leave(mem0.mutex);
20994   return SQLITE_OK;
20995 }
20996
20997 #ifndef SQLITE_OMIT_DEPRECATED
20998 /*
20999 ** Deprecated external interface.  Internal/core SQLite code
21000 ** should call sqlite3MemoryAlarm.
21001 */
21002 SQLITE_API int sqlite3_memory_alarm(
21003   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
21004   void *pArg,
21005   sqlite3_int64 iThreshold
21006 ){
21007   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
21008 }
21009 #endif
21010
21011 /*
21012 ** Set the soft heap-size limit for the library. Passing a zero or
21013 ** negative value indicates no limit.
21014 */
21015 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
21016   sqlite3_int64 priorLimit;
21017   sqlite3_int64 excess;
21018 #ifndef SQLITE_OMIT_AUTOINIT
21019   int rc = sqlite3_initialize();
21020   if( rc ) return -1;
21021 #endif
21022   sqlite3_mutex_enter(mem0.mutex);
21023   priorLimit = mem0.alarmThreshold;
21024   sqlite3_mutex_leave(mem0.mutex);
21025   if( n<0 ) return priorLimit;
21026   if( n>0 ){
21027     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
21028   }else{
21029     sqlite3MemoryAlarm(0, 0, 0);
21030   }
21031   excess = sqlite3_memory_used() - n;
21032   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
21033   return priorLimit;
21034 }
21035 SQLITE_API void sqlite3_soft_heap_limit(int n){
21036   if( n<0 ) n = 0;
21037   sqlite3_soft_heap_limit64(n);
21038 }
21039
21040 /*
21041 ** Initialize the memory allocation subsystem.
21042 */
21043 SQLITE_PRIVATE int sqlite3MallocInit(void){
21044   if( sqlite3GlobalConfig.m.xMalloc==0 ){
21045     sqlite3MemSetDefault();
21046   }
21047   memset(&mem0, 0, sizeof(mem0));
21048   if( sqlite3GlobalConfig.bCoreMutex ){
21049     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21050   }
21051   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
21052       && sqlite3GlobalConfig.nScratch>0 ){
21053     int i, n, sz;
21054     ScratchFreeslot *pSlot;
21055     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
21056     sqlite3GlobalConfig.szScratch = sz;
21057     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
21058     n = sqlite3GlobalConfig.nScratch;
21059     mem0.pScratchFree = pSlot;
21060     mem0.nScratchFree = n;
21061     for(i=0; i<n-1; i++){
21062       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
21063       pSlot = pSlot->pNext;
21064     }
21065     pSlot->pNext = 0;
21066     mem0.pScratchEnd = (void*)&pSlot[1];
21067   }else{
21068     mem0.pScratchEnd = 0;
21069     sqlite3GlobalConfig.pScratch = 0;
21070     sqlite3GlobalConfig.szScratch = 0;
21071     sqlite3GlobalConfig.nScratch = 0;
21072   }
21073   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
21074       || sqlite3GlobalConfig.nPage<1 ){
21075     sqlite3GlobalConfig.pPage = 0;
21076     sqlite3GlobalConfig.szPage = 0;
21077     sqlite3GlobalConfig.nPage = 0;
21078   }
21079   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
21080 }
21081
21082 /*
21083 ** Return true if the heap is currently under memory pressure - in other
21084 ** words if the amount of heap used is close to the limit set by
21085 ** sqlite3_soft_heap_limit().
21086 */
21087 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
21088   return mem0.nearlyFull;
21089 }
21090
21091 /*
21092 ** Deinitialize the memory allocation subsystem.
21093 */
21094 SQLITE_PRIVATE void sqlite3MallocEnd(void){
21095   if( sqlite3GlobalConfig.m.xShutdown ){
21096     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
21097   }
21098   memset(&mem0, 0, sizeof(mem0));
21099 }
21100
21101 /*
21102 ** Return the amount of memory currently checked out.
21103 */
21104 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
21105   int n, mx;
21106   sqlite3_int64 res;
21107   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
21108   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
21109   return res;
21110 }
21111
21112 /*
21113 ** Return the maximum amount of memory that has ever been
21114 ** checked out since either the beginning of this process
21115 ** or since the most recent reset.
21116 */
21117 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
21118   int n, mx;
21119   sqlite3_int64 res;
21120   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
21121   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
21122   return res;
21123 }
21124
21125 /*
21126 ** Trigger the alarm
21127 */
21128 static void sqlite3MallocAlarm(int nByte){
21129   void (*xCallback)(void*,sqlite3_int64,int);
21130   sqlite3_int64 nowUsed;
21131   void *pArg;
21132   if( mem0.alarmCallback==0 ) return;
21133   xCallback = mem0.alarmCallback;
21134   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
21135   pArg = mem0.alarmArg;
21136   mem0.alarmCallback = 0;
21137   sqlite3_mutex_leave(mem0.mutex);
21138   xCallback(pArg, nowUsed, nByte);
21139   sqlite3_mutex_enter(mem0.mutex);
21140   mem0.alarmCallback = xCallback;
21141   mem0.alarmArg = pArg;
21142 }
21143
21144 /*
21145 ** Do a memory allocation with statistics and alarms.  Assume the
21146 ** lock is already held.
21147 */
21148 static int mallocWithAlarm(int n, void **pp){
21149   int nFull;
21150   void *p;
21151   assert( sqlite3_mutex_held(mem0.mutex) );
21152   nFull = sqlite3GlobalConfig.m.xRoundup(n);
21153   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
21154   if( mem0.alarmCallback!=0 ){
21155     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
21156     if( nUsed >= mem0.alarmThreshold - nFull ){
21157       mem0.nearlyFull = 1;
21158       sqlite3MallocAlarm(nFull);
21159     }else{
21160       mem0.nearlyFull = 0;
21161     }
21162   }
21163   p = sqlite3GlobalConfig.m.xMalloc(nFull);
21164 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
21165   if( p==0 && mem0.alarmCallback ){
21166     sqlite3MallocAlarm(nFull);
21167     p = sqlite3GlobalConfig.m.xMalloc(nFull);
21168   }
21169 #endif
21170   if( p ){
21171     nFull = sqlite3MallocSize(p);
21172     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
21173     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
21174   }
21175   *pp = p;
21176   return nFull;
21177 }
21178
21179 /*
21180 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
21181 ** assumes the memory subsystem has already been initialized.
21182 */
21183 SQLITE_PRIVATE void *sqlite3Malloc(int n){
21184   void *p;
21185   if( n<=0               /* IMP: R-65312-04917 */
21186    || n>=0x7fffff00
21187   ){
21188     /* A memory allocation of a number of bytes which is near the maximum
21189     ** signed integer value might cause an integer overflow inside of the
21190     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
21191     ** 255 bytes of overhead.  SQLite itself will never use anything near
21192     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
21193     p = 0;
21194   }else if( sqlite3GlobalConfig.bMemstat ){
21195     sqlite3_mutex_enter(mem0.mutex);
21196     mallocWithAlarm(n, &p);
21197     sqlite3_mutex_leave(mem0.mutex);
21198   }else{
21199     p = sqlite3GlobalConfig.m.xMalloc(n);
21200   }
21201   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
21202   return p;
21203 }
21204
21205 /*
21206 ** This version of the memory allocation is for use by the application.
21207 ** First make sure the memory subsystem is initialized, then do the
21208 ** allocation.
21209 */
21210 SQLITE_API void *sqlite3_malloc(int n){
21211 #ifndef SQLITE_OMIT_AUTOINIT
21212   if( sqlite3_initialize() ) return 0;
21213 #endif
21214   return sqlite3Malloc(n);
21215 }
21216
21217 /*
21218 ** Each thread may only have a single outstanding allocation from
21219 ** xScratchMalloc().  We verify this constraint in the single-threaded
21220 ** case by setting scratchAllocOut to 1 when an allocation
21221 ** is outstanding clearing it when the allocation is freed.
21222 */
21223 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
21224 static int scratchAllocOut = 0;
21225 #endif
21226
21227
21228 /*
21229 ** Allocate memory that is to be used and released right away.
21230 ** This routine is similar to alloca() in that it is not intended
21231 ** for situations where the memory might be held long-term.  This
21232 ** routine is intended to get memory to old large transient data
21233 ** structures that would not normally fit on the stack of an
21234 ** embedded processor.
21235 */
21236 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
21237   void *p;
21238   assert( n>0 );
21239
21240   sqlite3_mutex_enter(mem0.mutex);
21241   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
21242     p = mem0.pScratchFree;
21243     mem0.pScratchFree = mem0.pScratchFree->pNext;
21244     mem0.nScratchFree--;
21245     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
21246     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
21247     sqlite3_mutex_leave(mem0.mutex);
21248   }else{
21249     if( sqlite3GlobalConfig.bMemstat ){
21250       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
21251       n = mallocWithAlarm(n, &p);
21252       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
21253       sqlite3_mutex_leave(mem0.mutex);
21254     }else{
21255       sqlite3_mutex_leave(mem0.mutex);
21256       p = sqlite3GlobalConfig.m.xMalloc(n);
21257     }
21258     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
21259   }
21260   assert( sqlite3_mutex_notheld(mem0.mutex) );
21261
21262
21263 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
21264   /* Verify that no more than two scratch allocations per thread
21265   ** are outstanding at one time.  (This is only checked in the
21266   ** single-threaded case since checking in the multi-threaded case
21267   ** would be much more complicated.) */
21268   assert( scratchAllocOut<=1 );
21269   if( p ) scratchAllocOut++;
21270 #endif
21271
21272   return p;
21273 }
21274 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
21275   if( p ){
21276
21277 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
21278     /* Verify that no more than two scratch allocation per thread
21279     ** is outstanding at one time.  (This is only checked in the
21280     ** single-threaded case since checking in the multi-threaded case
21281     ** would be much more complicated.) */
21282     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
21283     scratchAllocOut--;
21284 #endif
21285
21286     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
21287       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
21288       ScratchFreeslot *pSlot;
21289       pSlot = (ScratchFreeslot*)p;
21290       sqlite3_mutex_enter(mem0.mutex);
21291       pSlot->pNext = mem0.pScratchFree;
21292       mem0.pScratchFree = pSlot;
21293       mem0.nScratchFree++;
21294       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
21295       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
21296       sqlite3_mutex_leave(mem0.mutex);
21297     }else{
21298       /* Release memory back to the heap */
21299       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
21300       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
21301       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21302       if( sqlite3GlobalConfig.bMemstat ){
21303         int iSize = sqlite3MallocSize(p);
21304         sqlite3_mutex_enter(mem0.mutex);
21305         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
21306         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
21307         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
21308         sqlite3GlobalConfig.m.xFree(p);
21309         sqlite3_mutex_leave(mem0.mutex);
21310       }else{
21311         sqlite3GlobalConfig.m.xFree(p);
21312       }
21313     }
21314   }
21315 }
21316
21317 /*
21318 ** TRUE if p is a lookaside memory allocation from db
21319 */
21320 #ifndef SQLITE_OMIT_LOOKASIDE
21321 static int isLookaside(sqlite3 *db, void *p){
21322   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
21323 }
21324 #else
21325 #define isLookaside(A,B) 0
21326 #endif
21327
21328 /*
21329 ** Return the size of a memory allocation previously obtained from
21330 ** sqlite3Malloc() or sqlite3_malloc().
21331 */
21332 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
21333   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21334   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
21335   return sqlite3GlobalConfig.m.xSize(p);
21336 }
21337 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
21338   assert( db==0 || sqlite3_mutex_held(db->mutex) );
21339   if( db && isLookaside(db, p) ){
21340     return db->lookaside.sz;
21341   }else{
21342     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
21343     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
21344     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21345     return sqlite3GlobalConfig.m.xSize(p);
21346   }
21347 }
21348
21349 /*
21350 ** Free memory previously obtained from sqlite3Malloc().
21351 */
21352 SQLITE_API void sqlite3_free(void *p){
21353   if( p==0 ) return;  /* IMP: R-49053-54554 */
21354   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
21355   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21356   if( sqlite3GlobalConfig.bMemstat ){
21357     sqlite3_mutex_enter(mem0.mutex);
21358     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
21359     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
21360     sqlite3GlobalConfig.m.xFree(p);
21361     sqlite3_mutex_leave(mem0.mutex);
21362   }else{
21363     sqlite3GlobalConfig.m.xFree(p);
21364   }
21365 }
21366
21367 /*
21368 ** Free memory that might be associated with a particular database
21369 ** connection.
21370 */
21371 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
21372   assert( db==0 || sqlite3_mutex_held(db->mutex) );
21373   if( db ){
21374     if( db->pnBytesFreed ){
21375       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
21376       return;
21377     }
21378     if( isLookaside(db, p) ){
21379       LookasideSlot *pBuf = (LookasideSlot*)p;
21380 #if SQLITE_DEBUG
21381       /* Trash all content in the buffer being freed */
21382       memset(p, 0xaa, db->lookaside.sz);
21383 #endif
21384       pBuf->pNext = db->lookaside.pFree;
21385       db->lookaside.pFree = pBuf;
21386       db->lookaside.nOut--;
21387       return;
21388     }
21389   }
21390   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
21391   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
21392   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21393   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21394   sqlite3_free(p);
21395 }
21396
21397 /*
21398 ** Change the size of an existing memory allocation
21399 */
21400 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
21401   int nOld, nNew, nDiff;
21402   void *pNew;
21403   if( pOld==0 ){
21404     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
21405   }
21406   if( nBytes<=0 ){
21407     sqlite3_free(pOld); /* IMP: R-31593-10574 */
21408     return 0;
21409   }
21410   if( nBytes>=0x7fffff00 ){
21411     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
21412     return 0;
21413   }
21414   nOld = sqlite3MallocSize(pOld);
21415   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
21416   ** argument to xRealloc is always a value returned by a prior call to
21417   ** xRoundup. */
21418   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
21419   if( nOld==nNew ){
21420     pNew = pOld;
21421   }else if( sqlite3GlobalConfig.bMemstat ){
21422     sqlite3_mutex_enter(mem0.mutex);
21423     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
21424     nDiff = nNew - nOld;
21425     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
21426           mem0.alarmThreshold-nDiff ){
21427       sqlite3MallocAlarm(nDiff);
21428     }
21429     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
21430     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
21431     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21432     if( pNew==0 && mem0.alarmCallback ){
21433       sqlite3MallocAlarm(nBytes);
21434       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21435     }
21436     if( pNew ){
21437       nNew = sqlite3MallocSize(pNew);
21438       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
21439     }
21440     sqlite3_mutex_leave(mem0.mutex);
21441   }else{
21442     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21443   }
21444   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
21445   return pNew;
21446 }
21447
21448 /*
21449 ** The public interface to sqlite3Realloc.  Make sure that the memory
21450 ** subsystem is initialized prior to invoking sqliteRealloc.
21451 */
21452 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
21453 #ifndef SQLITE_OMIT_AUTOINIT
21454   if( sqlite3_initialize() ) return 0;
21455 #endif
21456   return sqlite3Realloc(pOld, n);
21457 }
21458
21459
21460 /*
21461 ** Allocate and zero memory.
21462 */
21463 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
21464   void *p = sqlite3Malloc(n);
21465   if( p ){
21466     memset(p, 0, n);
21467   }
21468   return p;
21469 }
21470
21471 /*
21472 ** Allocate and zero memory.  If the allocation fails, make
21473 ** the mallocFailed flag in the connection pointer.
21474 */
21475 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
21476   void *p = sqlite3DbMallocRaw(db, n);
21477   if( p ){
21478     memset(p, 0, n);
21479   }
21480   return p;
21481 }
21482
21483 /*
21484 ** Allocate and zero memory.  If the allocation fails, make
21485 ** the mallocFailed flag in the connection pointer.
21486 **
21487 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
21488 ** failure on the same database connection) then always return 0.
21489 ** Hence for a particular database connection, once malloc starts
21490 ** failing, it fails consistently until mallocFailed is reset.
21491 ** This is an important assumption.  There are many places in the
21492 ** code that do things like this:
21493 **
21494 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
21495 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
21496 **         if( b ) a[10] = 9;
21497 **
21498 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
21499 ** that all prior mallocs (ex: "a") worked too.
21500 */
21501 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
21502   void *p;
21503   assert( db==0 || sqlite3_mutex_held(db->mutex) );
21504   assert( db==0 || db->pnBytesFreed==0 );
21505 #ifndef SQLITE_OMIT_LOOKASIDE
21506   if( db ){
21507     LookasideSlot *pBuf;
21508     if( db->mallocFailed ){
21509       return 0;
21510     }
21511     if( db->lookaside.bEnabled ){
21512       if( n>db->lookaside.sz ){
21513         db->lookaside.anStat[1]++;
21514       }else if( (pBuf = db->lookaside.pFree)==0 ){
21515         db->lookaside.anStat[2]++;
21516       }else{
21517         db->lookaside.pFree = pBuf->pNext;
21518         db->lookaside.nOut++;
21519         db->lookaside.anStat[0]++;
21520         if( db->lookaside.nOut>db->lookaside.mxOut ){
21521           db->lookaside.mxOut = db->lookaside.nOut;
21522         }
21523         return (void*)pBuf;
21524       }
21525     }
21526   }
21527 #else
21528   if( db && db->mallocFailed ){
21529     return 0;
21530   }
21531 #endif
21532   p = sqlite3Malloc(n);
21533   if( !p && db ){
21534     db->mallocFailed = 1;
21535   }
21536   sqlite3MemdebugSetType(p, MEMTYPE_DB |
21537          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
21538   return p;
21539 }
21540
21541 /*
21542 ** Resize the block of memory pointed to by p to n bytes. If the
21543 ** resize fails, set the mallocFailed flag in the connection object.
21544 */
21545 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
21546   void *pNew = 0;
21547   assert( db!=0 );
21548   assert( sqlite3_mutex_held(db->mutex) );
21549   if( db->mallocFailed==0 ){
21550     if( p==0 ){
21551       return sqlite3DbMallocRaw(db, n);
21552     }
21553     if( isLookaside(db, p) ){
21554       if( n<=db->lookaside.sz ){
21555         return p;
21556       }
21557       pNew = sqlite3DbMallocRaw(db, n);
21558       if( pNew ){
21559         memcpy(pNew, p, db->lookaside.sz);
21560         sqlite3DbFree(db, p);
21561       }
21562     }else{
21563       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
21564       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
21565       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21566       pNew = sqlite3_realloc(p, n);
21567       if( !pNew ){
21568         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
21569         db->mallocFailed = 1;
21570       }
21571       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
21572             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
21573     }
21574   }
21575   return pNew;
21576 }
21577
21578 /*
21579 ** Attempt to reallocate p.  If the reallocation fails, then free p
21580 ** and set the mallocFailed flag in the database connection.
21581 */
21582 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
21583   void *pNew;
21584   pNew = sqlite3DbRealloc(db, p, n);
21585   if( !pNew ){
21586     sqlite3DbFree(db, p);
21587   }
21588   return pNew;
21589 }
21590
21591 /*
21592 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
21593 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
21594 ** is because when memory debugging is turned on, these two functions are
21595 ** called via macros that record the current file and line number in the
21596 ** ThreadData structure.
21597 */
21598 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
21599   char *zNew;
21600   size_t n;
21601   if( z==0 ){
21602     return 0;
21603   }
21604   n = sqlite3Strlen30(z) + 1;
21605   assert( (n&0x7fffffff)==n );
21606   zNew = sqlite3DbMallocRaw(db, (int)n);
21607   if( zNew ){
21608     memcpy(zNew, z, n);
21609   }
21610   return zNew;
21611 }
21612 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
21613   char *zNew;
21614   if( z==0 ){
21615     return 0;
21616   }
21617   assert( (n&0x7fffffff)==n );
21618   zNew = sqlite3DbMallocRaw(db, n+1);
21619   if( zNew ){
21620     memcpy(zNew, z, n);
21621     zNew[n] = 0;
21622   }
21623   return zNew;
21624 }
21625
21626 /*
21627 ** Create a string from the zFromat argument and the va_list that follows.
21628 ** Store the string in memory obtained from sqliteMalloc() and make *pz
21629 ** point to that string.
21630 */
21631 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
21632   va_list ap;
21633   char *z;
21634
21635   va_start(ap, zFormat);
21636   z = sqlite3VMPrintf(db, zFormat, ap);
21637   va_end(ap);
21638   sqlite3DbFree(db, *pz);
21639   *pz = z;
21640 }
21641
21642
21643 /*
21644 ** This function must be called before exiting any API function (i.e.
21645 ** returning control to the user) that has called sqlite3_malloc or
21646 ** sqlite3_realloc.
21647 **
21648 ** The returned value is normally a copy of the second argument to this
21649 ** function. However, if a malloc() failure has occurred since the previous
21650 ** invocation SQLITE_NOMEM is returned instead.
21651 **
21652 ** If the first argument, db, is not NULL and a malloc() error has occurred,
21653 ** then the connection error-code (the value returned by sqlite3_errcode())
21654 ** is set to SQLITE_NOMEM.
21655 */
21656 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
21657   /* If the db handle is not NULL, then we must hold the connection handle
21658   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
21659   ** is unsafe, as is the call to sqlite3Error().
21660   */
21661   assert( !db || sqlite3_mutex_held(db->mutex) );
21662   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
21663     sqlite3Error(db, SQLITE_NOMEM, 0);
21664     db->mallocFailed = 0;
21665     rc = SQLITE_NOMEM;
21666   }
21667   return rc & (db ? db->errMask : 0xff);
21668 }
21669
21670 /************** End of malloc.c **********************************************/
21671 /************** Begin file printf.c ******************************************/
21672 /*
21673 ** The "printf" code that follows dates from the 1980's.  It is in
21674 ** the public domain.  The original comments are included here for
21675 ** completeness.  They are very out-of-date but might be useful as
21676 ** an historical reference.  Most of the "enhancements" have been backed
21677 ** out so that the functionality is now the same as standard printf().
21678 **
21679 **************************************************************************
21680 **
21681 ** This file contains code for a set of "printf"-like routines.  These
21682 ** routines format strings much like the printf() from the standard C
21683 ** library, though the implementation here has enhancements to support
21684 ** SQLlite.
21685 */
21686
21687 /*
21688 ** Conversion types fall into various categories as defined by the
21689 ** following enumeration.
21690 */
21691 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
21692 #define etFLOAT       2 /* Floating point.  %f */
21693 #define etEXP         3 /* Exponentional notation. %e and %E */
21694 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
21695 #define etSIZE        5 /* Return number of characters processed so far. %n */
21696 #define etSTRING      6 /* Strings. %s */
21697 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
21698 #define etPERCENT     8 /* Percent symbol. %% */
21699 #define etCHARX       9 /* Characters. %c */
21700 /* The rest are extensions, not normally found in printf() */
21701 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
21702 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
21703                           NULL pointers replaced by SQL NULL.  %Q */
21704 #define etTOKEN      12 /* a pointer to a Token structure */
21705 #define etSRCLIST    13 /* a pointer to a SrcList */
21706 #define etPOINTER    14 /* The %p conversion */
21707 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
21708 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
21709
21710 #define etINVALID     0 /* Any unrecognized conversion type */
21711
21712
21713 /*
21714 ** An "etByte" is an 8-bit unsigned value.
21715 */
21716 typedef unsigned char etByte;
21717
21718 /*
21719 ** Each builtin conversion character (ex: the 'd' in "%d") is described
21720 ** by an instance of the following structure
21721 */
21722 typedef struct et_info {   /* Information about each format field */
21723   char fmttype;            /* The format field code letter */
21724   etByte base;             /* The base for radix conversion */
21725   etByte flags;            /* One or more of FLAG_ constants below */
21726   etByte type;             /* Conversion paradigm */
21727   etByte charset;          /* Offset into aDigits[] of the digits string */
21728   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
21729 } et_info;
21730
21731 /*
21732 ** Allowed values for et_info.flags
21733 */
21734 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
21735 #define FLAG_INTERN  2     /* True if for internal use only */
21736 #define FLAG_STRING  4     /* Allow infinity precision */
21737
21738
21739 /*
21740 ** The following table is searched linearly, so it is good to put the
21741 ** most frequently used conversion types first.
21742 */
21743 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
21744 static const char aPrefix[] = "-x0\000X0";
21745 static const et_info fmtinfo[] = {
21746   {  'd', 10, 1, etRADIX,      0,  0 },
21747   {  's',  0, 4, etSTRING,     0,  0 },
21748   {  'g',  0, 1, etGENERIC,    30, 0 },
21749   {  'z',  0, 4, etDYNSTRING,  0,  0 },
21750   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
21751   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
21752   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
21753   {  'c',  0, 0, etCHARX,      0,  0 },
21754   {  'o',  8, 0, etRADIX,      0,  2 },
21755   {  'u', 10, 0, etRADIX,      0,  0 },
21756   {  'x', 16, 0, etRADIX,      16, 1 },
21757   {  'X', 16, 0, etRADIX,      0,  4 },
21758 #ifndef SQLITE_OMIT_FLOATING_POINT
21759   {  'f',  0, 1, etFLOAT,      0,  0 },
21760   {  'e',  0, 1, etEXP,        30, 0 },
21761   {  'E',  0, 1, etEXP,        14, 0 },
21762   {  'G',  0, 1, etGENERIC,    14, 0 },
21763 #endif
21764   {  'i', 10, 1, etRADIX,      0,  0 },
21765   {  'n',  0, 0, etSIZE,       0,  0 },
21766   {  '%',  0, 0, etPERCENT,    0,  0 },
21767   {  'p', 16, 0, etPOINTER,    0,  1 },
21768
21769 /* All the rest have the FLAG_INTERN bit set and are thus for internal
21770 ** use only */
21771   {  'T',  0, 2, etTOKEN,      0,  0 },
21772   {  'S',  0, 2, etSRCLIST,    0,  0 },
21773   {  'r', 10, 3, etORDINAL,    0,  0 },
21774 };
21775
21776 /*
21777 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
21778 ** conversions will work.
21779 */
21780 #ifndef SQLITE_OMIT_FLOATING_POINT
21781 /*
21782 ** "*val" is a double such that 0.1 <= *val < 10.0
21783 ** Return the ascii code for the leading digit of *val, then
21784 ** multiply "*val" by 10.0 to renormalize.
21785 **
21786 ** Example:
21787 **     input:     *val = 3.14159
21788 **     output:    *val = 1.4159    function return = '3'
21789 **
21790 ** The counter *cnt is incremented each time.  After counter exceeds
21791 ** 16 (the number of significant digits in a 64-bit float) '0' is
21792 ** always returned.
21793 */
21794 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
21795   int digit;
21796   LONGDOUBLE_TYPE d;
21797   if( (*cnt)<=0 ) return '0';
21798   (*cnt)--;
21799   digit = (int)*val;
21800   d = digit;
21801   digit += '0';
21802   *val = (*val - d)*10.0;
21803   return (char)digit;
21804 }
21805 #endif /* SQLITE_OMIT_FLOATING_POINT */
21806
21807 /*
21808 ** Append N space characters to the given string buffer.
21809 */
21810 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
21811   static const char zSpaces[] = "                             ";
21812   while( N>=(int)sizeof(zSpaces)-1 ){
21813     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
21814     N -= sizeof(zSpaces)-1;
21815   }
21816   if( N>0 ){
21817     sqlite3StrAccumAppend(pAccum, zSpaces, N);
21818   }
21819 }
21820
21821 /*
21822 ** On machines with a small stack size, you can redefine the
21823 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
21824 */
21825 #ifndef SQLITE_PRINT_BUF_SIZE
21826 # define SQLITE_PRINT_BUF_SIZE 70
21827 #endif
21828 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
21829
21830 /*
21831 ** Render a string given by "fmt" into the StrAccum object.
21832 */
21833 SQLITE_PRIVATE void sqlite3VXPrintf(
21834   StrAccum *pAccum,                  /* Accumulate results here */
21835   int useExtended,                   /* Allow extended %-conversions */
21836   const char *fmt,                   /* Format string */
21837   va_list ap                         /* arguments */
21838 ){
21839   int c;                     /* Next character in the format string */
21840   char *bufpt;               /* Pointer to the conversion buffer */
21841   int precision;             /* Precision of the current field */
21842   int length;                /* Length of the field */
21843   int idx;                   /* A general purpose loop counter */
21844   int width;                 /* Width of the current field */
21845   etByte flag_leftjustify;   /* True if "-" flag is present */
21846   etByte flag_plussign;      /* True if "+" flag is present */
21847   etByte flag_blanksign;     /* True if " " flag is present */
21848   etByte flag_alternateform; /* True if "#" flag is present */
21849   etByte flag_altform2;      /* True if "!" flag is present */
21850   etByte flag_zeropad;       /* True if field width constant starts with zero */
21851   etByte flag_long;          /* True if "l" flag is present */
21852   etByte flag_longlong;      /* True if the "ll" flag is present */
21853   etByte done;               /* Loop termination flag */
21854   etByte xtype = 0;          /* Conversion paradigm */
21855   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
21856   sqlite_uint64 longvalue;   /* Value for integer types */
21857   LONGDOUBLE_TYPE realvalue; /* Value for real types */
21858   const et_info *infop;      /* Pointer to the appropriate info structure */
21859   char *zOut;                /* Rendering buffer */
21860   int nOut;                  /* Size of the rendering buffer */
21861   char *zExtra;              /* Malloced memory used by some conversion */
21862 #ifndef SQLITE_OMIT_FLOATING_POINT
21863   int  exp, e2;              /* exponent of real numbers */
21864   int nsd;                   /* Number of significant digits returned */
21865   double rounder;            /* Used for rounding floating point values */
21866   etByte flag_dp;            /* True if decimal point should be shown */
21867   etByte flag_rtz;           /* True if trailing zeros should be removed */
21868 #endif
21869   char buf[etBUFSIZE];       /* Conversion buffer */
21870
21871   bufpt = 0;
21872   for(; (c=(*fmt))!=0; ++fmt){
21873     if( c!='%' ){
21874       int amt;
21875       bufpt = (char *)fmt;
21876       amt = 1;
21877       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
21878       sqlite3StrAccumAppend(pAccum, bufpt, amt);
21879       if( c==0 ) break;
21880     }
21881     if( (c=(*++fmt))==0 ){
21882       sqlite3StrAccumAppend(pAccum, "%", 1);
21883       break;
21884     }
21885     /* Find out what flags are present */
21886     flag_leftjustify = flag_plussign = flag_blanksign =
21887      flag_alternateform = flag_altform2 = flag_zeropad = 0;
21888     done = 0;
21889     do{
21890       switch( c ){
21891         case '-':   flag_leftjustify = 1;     break;
21892         case '+':   flag_plussign = 1;        break;
21893         case ' ':   flag_blanksign = 1;       break;
21894         case '#':   flag_alternateform = 1;   break;
21895         case '!':   flag_altform2 = 1;        break;
21896         case '0':   flag_zeropad = 1;         break;
21897         default:    done = 1;                 break;
21898       }
21899     }while( !done && (c=(*++fmt))!=0 );
21900     /* Get the field width */
21901     width = 0;
21902     if( c=='*' ){
21903       width = va_arg(ap,int);
21904       if( width<0 ){
21905         flag_leftjustify = 1;
21906         width = -width;
21907       }
21908       c = *++fmt;
21909     }else{
21910       while( c>='0' && c<='9' ){
21911         width = width*10 + c - '0';
21912         c = *++fmt;
21913       }
21914     }
21915     /* Get the precision */
21916     if( c=='.' ){
21917       precision = 0;
21918       c = *++fmt;
21919       if( c=='*' ){
21920         precision = va_arg(ap,int);
21921         if( precision<0 ) precision = -precision;
21922         c = *++fmt;
21923       }else{
21924         while( c>='0' && c<='9' ){
21925           precision = precision*10 + c - '0';
21926           c = *++fmt;
21927         }
21928       }
21929     }else{
21930       precision = -1;
21931     }
21932     /* Get the conversion type modifier */
21933     if( c=='l' ){
21934       flag_long = 1;
21935       c = *++fmt;
21936       if( c=='l' ){
21937         flag_longlong = 1;
21938         c = *++fmt;
21939       }else{
21940         flag_longlong = 0;
21941       }
21942     }else{
21943       flag_long = flag_longlong = 0;
21944     }
21945     /* Fetch the info entry for the field */
21946     infop = &fmtinfo[0];
21947     xtype = etINVALID;
21948     for(idx=0; idx<ArraySize(fmtinfo); idx++){
21949       if( c==fmtinfo[idx].fmttype ){
21950         infop = &fmtinfo[idx];
21951         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
21952           xtype = infop->type;
21953         }else{
21954           return;
21955         }
21956         break;
21957       }
21958     }
21959     zExtra = 0;
21960
21961     /*
21962     ** At this point, variables are initialized as follows:
21963     **
21964     **   flag_alternateform          TRUE if a '#' is present.
21965     **   flag_altform2               TRUE if a '!' is present.
21966     **   flag_plussign               TRUE if a '+' is present.
21967     **   flag_leftjustify            TRUE if a '-' is present or if the
21968     **                               field width was negative.
21969     **   flag_zeropad                TRUE if the width began with 0.
21970     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
21971     **                               the conversion character.
21972     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
21973     **                               the conversion character.
21974     **   flag_blanksign              TRUE if a ' ' is present.
21975     **   width                       The specified field width.  This is
21976     **                               always non-negative.  Zero is the default.
21977     **   precision                   The specified precision.  The default
21978     **                               is -1.
21979     **   xtype                       The class of the conversion.
21980     **   infop                       Pointer to the appropriate info struct.
21981     */
21982     switch( xtype ){
21983       case etPOINTER:
21984         flag_longlong = sizeof(char*)==sizeof(i64);
21985         flag_long = sizeof(char*)==sizeof(long int);
21986         /* Fall through into the next case */
21987       case etORDINAL:
21988       case etRADIX:
21989         if( infop->flags & FLAG_SIGNED ){
21990           i64 v;
21991           if( flag_longlong ){
21992             v = va_arg(ap,i64);
21993           }else if( flag_long ){
21994             v = va_arg(ap,long int);
21995           }else{
21996             v = va_arg(ap,int);
21997           }
21998           if( v<0 ){
21999             if( v==SMALLEST_INT64 ){
22000               longvalue = ((u64)1)<<63;
22001             }else{
22002               longvalue = -v;
22003             }
22004             prefix = '-';
22005           }else{
22006             longvalue = v;
22007             if( flag_plussign )        prefix = '+';
22008             else if( flag_blanksign )  prefix = ' ';
22009             else                       prefix = 0;
22010           }
22011         }else{
22012           if( flag_longlong ){
22013             longvalue = va_arg(ap,u64);
22014           }else if( flag_long ){
22015             longvalue = va_arg(ap,unsigned long int);
22016           }else{
22017             longvalue = va_arg(ap,unsigned int);
22018           }
22019           prefix = 0;
22020         }
22021         if( longvalue==0 ) flag_alternateform = 0;
22022         if( flag_zeropad && precision<width-(prefix!=0) ){
22023           precision = width-(prefix!=0);
22024         }
22025         if( precision<etBUFSIZE-10 ){
22026           nOut = etBUFSIZE;
22027           zOut = buf;
22028         }else{
22029           nOut = precision + 10;
22030           zOut = zExtra = sqlite3Malloc( nOut );
22031           if( zOut==0 ){
22032             pAccum->mallocFailed = 1;
22033             return;
22034           }
22035         }
22036         bufpt = &zOut[nOut-1];
22037         if( xtype==etORDINAL ){
22038           static const char zOrd[] = "thstndrd";
22039           int x = (int)(longvalue % 10);
22040           if( x>=4 || (longvalue/10)%10==1 ){
22041             x = 0;
22042           }
22043           *(--bufpt) = zOrd[x*2+1];
22044           *(--bufpt) = zOrd[x*2];
22045         }
22046         {
22047           register const char *cset;      /* Use registers for speed */
22048           register int base;
22049           cset = &aDigits[infop->charset];
22050           base = infop->base;
22051           do{                                           /* Convert to ascii */
22052             *(--bufpt) = cset[longvalue%base];
22053             longvalue = longvalue/base;
22054           }while( longvalue>0 );
22055         }
22056         length = (int)(&zOut[nOut-1]-bufpt);
22057         for(idx=precision-length; idx>0; idx--){
22058           *(--bufpt) = '0';                             /* Zero pad */
22059         }
22060         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
22061         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
22062           const char *pre;
22063           char x;
22064           pre = &aPrefix[infop->prefix];
22065           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
22066         }
22067         length = (int)(&zOut[nOut-1]-bufpt);
22068         break;
22069       case etFLOAT:
22070       case etEXP:
22071       case etGENERIC:
22072         realvalue = va_arg(ap,double);
22073 #ifdef SQLITE_OMIT_FLOATING_POINT
22074         length = 0;
22075 #else
22076         if( precision<0 ) precision = 6;         /* Set default precision */
22077         if( realvalue<0.0 ){
22078           realvalue = -realvalue;
22079           prefix = '-';
22080         }else{
22081           if( flag_plussign )          prefix = '+';
22082           else if( flag_blanksign )    prefix = ' ';
22083           else                         prefix = 0;
22084         }
22085         if( xtype==etGENERIC && precision>0 ) precision--;
22086 #if 0
22087         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
22088         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
22089 #else
22090         /* It makes more sense to use 0.5 */
22091         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
22092 #endif
22093         if( xtype==etFLOAT ) realvalue += rounder;
22094         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
22095         exp = 0;
22096         if( sqlite3IsNaN((double)realvalue) ){
22097           bufpt = "NaN";
22098           length = 3;
22099           break;
22100         }
22101         if( realvalue>0.0 ){
22102           LONGDOUBLE_TYPE scale = 1.0;
22103           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
22104           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
22105           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
22106           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
22107           realvalue /= scale;
22108           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
22109           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
22110           if( exp>350 ){
22111             if( prefix=='-' ){
22112               bufpt = "-Inf";
22113             }else if( prefix=='+' ){
22114               bufpt = "+Inf";
22115             }else{
22116               bufpt = "Inf";
22117             }
22118             length = sqlite3Strlen30(bufpt);
22119             break;
22120           }
22121         }
22122         bufpt = buf;
22123         /*
22124         ** If the field type is etGENERIC, then convert to either etEXP
22125         ** or etFLOAT, as appropriate.
22126         */
22127         if( xtype!=etFLOAT ){
22128           realvalue += rounder;
22129           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
22130         }
22131         if( xtype==etGENERIC ){
22132           flag_rtz = !flag_alternateform;
22133           if( exp<-4 || exp>precision ){
22134             xtype = etEXP;
22135           }else{
22136             precision = precision - exp;
22137             xtype = etFLOAT;
22138           }
22139         }else{
22140           flag_rtz = flag_altform2;
22141         }
22142         if( xtype==etEXP ){
22143           e2 = 0;
22144         }else{
22145           e2 = exp;
22146         }
22147         if( e2+precision+width > etBUFSIZE - 15 ){
22148           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
22149           if( bufpt==0 ){
22150             pAccum->mallocFailed = 1;
22151             return;
22152           }
22153         }
22154         zOut = bufpt;
22155         nsd = 16 + flag_altform2*10;
22156         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
22157         /* The sign in front of the number */
22158         if( prefix ){
22159           *(bufpt++) = prefix;
22160         }
22161         /* Digits prior to the decimal point */
22162         if( e2<0 ){
22163           *(bufpt++) = '0';
22164         }else{
22165           for(; e2>=0; e2--){
22166             *(bufpt++) = et_getdigit(&realvalue,&nsd);
22167           }
22168         }
22169         /* The decimal point */
22170         if( flag_dp ){
22171           *(bufpt++) = '.';
22172         }
22173         /* "0" digits after the decimal point but before the first
22174         ** significant digit of the number */
22175         for(e2++; e2<0; precision--, e2++){
22176           assert( precision>0 );
22177           *(bufpt++) = '0';
22178         }
22179         /* Significant digits after the decimal point */
22180         while( (precision--)>0 ){
22181           *(bufpt++) = et_getdigit(&realvalue,&nsd);
22182         }
22183         /* Remove trailing zeros and the "." if no digits follow the "." */
22184         if( flag_rtz && flag_dp ){
22185           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
22186           assert( bufpt>zOut );
22187           if( bufpt[-1]=='.' ){
22188             if( flag_altform2 ){
22189               *(bufpt++) = '0';
22190             }else{
22191               *(--bufpt) = 0;
22192             }
22193           }
22194         }
22195         /* Add the "eNNN" suffix */
22196         if( xtype==etEXP ){
22197           *(bufpt++) = aDigits[infop->charset];
22198           if( exp<0 ){
22199             *(bufpt++) = '-'; exp = -exp;
22200           }else{
22201             *(bufpt++) = '+';
22202           }
22203           if( exp>=100 ){
22204             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
22205             exp %= 100;
22206           }
22207           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
22208           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
22209         }
22210         *bufpt = 0;
22211
22212         /* The converted number is in buf[] and zero terminated. Output it.
22213         ** Note that the number is in the usual order, not reversed as with
22214         ** integer conversions. */
22215         length = (int)(bufpt-zOut);
22216         bufpt = zOut;
22217
22218         /* Special case:  Add leading zeros if the flag_zeropad flag is
22219         ** set and we are not left justified */
22220         if( flag_zeropad && !flag_leftjustify && length < width){
22221           int i;
22222           int nPad = width - length;
22223           for(i=width; i>=nPad; i--){
22224             bufpt[i] = bufpt[i-nPad];
22225           }
22226           i = prefix!=0;
22227           while( nPad-- ) bufpt[i++] = '0';
22228           length = width;
22229         }
22230 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
22231         break;
22232       case etSIZE:
22233         *(va_arg(ap,int*)) = pAccum->nChar;
22234         length = width = 0;
22235         break;
22236       case etPERCENT:
22237         buf[0] = '%';
22238         bufpt = buf;
22239         length = 1;
22240         break;
22241       case etCHARX:
22242         c = va_arg(ap,int);
22243         buf[0] = (char)c;
22244         if( precision>=0 ){
22245           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
22246           length = precision;
22247         }else{
22248           length =1;
22249         }
22250         bufpt = buf;
22251         break;
22252       case etSTRING:
22253       case etDYNSTRING:
22254         bufpt = va_arg(ap,char*);
22255         if( bufpt==0 ){
22256           bufpt = "";
22257         }else if( xtype==etDYNSTRING ){
22258           zExtra = bufpt;
22259         }
22260         if( precision>=0 ){
22261           for(length=0; length<precision && bufpt[length]; length++){}
22262         }else{
22263           length = sqlite3Strlen30(bufpt);
22264         }
22265         break;
22266       case etSQLESCAPE:
22267       case etSQLESCAPE2:
22268       case etSQLESCAPE3: {
22269         int i, j, k, n, isnull;
22270         int needQuote;
22271         char ch;
22272         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
22273         char *escarg = va_arg(ap,char*);
22274         isnull = escarg==0;
22275         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
22276         k = precision;
22277         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
22278           if( ch==q )  n++;
22279         }
22280         needQuote = !isnull && xtype==etSQLESCAPE2;
22281         n += i + 1 + needQuote*2;
22282         if( n>etBUFSIZE ){
22283           bufpt = zExtra = sqlite3Malloc( n );
22284           if( bufpt==0 ){
22285             pAccum->mallocFailed = 1;
22286             return;
22287           }
22288         }else{
22289           bufpt = buf;
22290         }
22291         j = 0;
22292         if( needQuote ) bufpt[j++] = q;
22293         k = i;
22294         for(i=0; i<k; i++){
22295           bufpt[j++] = ch = escarg[i];
22296           if( ch==q ) bufpt[j++] = ch;
22297         }
22298         if( needQuote ) bufpt[j++] = q;
22299         bufpt[j] = 0;
22300         length = j;
22301         /* The precision in %q and %Q means how many input characters to
22302         ** consume, not the length of the output...
22303         ** if( precision>=0 && precision<length ) length = precision; */
22304         break;
22305       }
22306       case etTOKEN: {
22307         Token *pToken = va_arg(ap, Token*);
22308         if( pToken ){
22309           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
22310         }
22311         length = width = 0;
22312         break;
22313       }
22314       case etSRCLIST: {
22315         SrcList *pSrc = va_arg(ap, SrcList*);
22316         int k = va_arg(ap, int);
22317         struct SrcList_item *pItem = &pSrc->a[k];
22318         assert( k>=0 && k<pSrc->nSrc );
22319         if( pItem->zDatabase ){
22320           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
22321           sqlite3StrAccumAppend(pAccum, ".", 1);
22322         }
22323         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
22324         length = width = 0;
22325         break;
22326       }
22327       default: {
22328         assert( xtype==etINVALID );
22329         return;
22330       }
22331     }/* End switch over the format type */
22332     /*
22333     ** The text of the conversion is pointed to by "bufpt" and is
22334     ** "length" characters long.  The field width is "width".  Do
22335     ** the output.
22336     */
22337     if( !flag_leftjustify ){
22338       register int nspace;
22339       nspace = width-length;
22340       if( nspace>0 ){
22341         sqlite3AppendSpace(pAccum, nspace);
22342       }
22343     }
22344     if( length>0 ){
22345       sqlite3StrAccumAppend(pAccum, bufpt, length);
22346     }
22347     if( flag_leftjustify ){
22348       register int nspace;
22349       nspace = width-length;
22350       if( nspace>0 ){
22351         sqlite3AppendSpace(pAccum, nspace);
22352       }
22353     }
22354     sqlite3_free(zExtra);
22355   }/* End for loop over the format string */
22356 } /* End of function */
22357
22358 /*
22359 ** Append N bytes of text from z to the StrAccum object.
22360 */
22361 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
22362   assert( z!=0 || N==0 );
22363   if( p->tooBig | p->mallocFailed ){
22364     testcase(p->tooBig);
22365     testcase(p->mallocFailed);
22366     return;
22367   }
22368   assert( p->zText!=0 || p->nChar==0 );
22369   if( N<0 ){
22370     N = sqlite3Strlen30(z);
22371   }
22372   if( N==0 || NEVER(z==0) ){
22373     return;
22374   }
22375   if( p->nChar+N >= p->nAlloc ){
22376     char *zNew;
22377     if( !p->useMalloc ){
22378       p->tooBig = 1;
22379       N = p->nAlloc - p->nChar - 1;
22380       if( N<=0 ){
22381         return;
22382       }
22383     }else{
22384       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
22385       i64 szNew = p->nChar;
22386       szNew += N + 1;
22387       if( szNew > p->mxAlloc ){
22388         sqlite3StrAccumReset(p);
22389         p->tooBig = 1;
22390         return;
22391       }else{
22392         p->nAlloc = (int)szNew;
22393       }
22394       if( p->useMalloc==1 ){
22395         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
22396       }else{
22397         zNew = sqlite3_realloc(zOld, p->nAlloc);
22398       }
22399       if( zNew ){
22400         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
22401         p->zText = zNew;
22402       }else{
22403         p->mallocFailed = 1;
22404         sqlite3StrAccumReset(p);
22405         return;
22406       }
22407     }
22408   }
22409   assert( p->zText );
22410   memcpy(&p->zText[p->nChar], z, N);
22411   p->nChar += N;
22412 }
22413
22414 /*
22415 ** Finish off a string by making sure it is zero-terminated.
22416 ** Return a pointer to the resulting string.  Return a NULL
22417 ** pointer if any kind of error was encountered.
22418 */
22419 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
22420   if( p->zText ){
22421     p->zText[p->nChar] = 0;
22422     if( p->useMalloc && p->zText==p->zBase ){
22423       if( p->useMalloc==1 ){
22424         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
22425       }else{
22426         p->zText = sqlite3_malloc(p->nChar+1);
22427       }
22428       if( p->zText ){
22429         memcpy(p->zText, p->zBase, p->nChar+1);
22430       }else{
22431         p->mallocFailed = 1;
22432       }
22433     }
22434   }
22435   return p->zText;
22436 }
22437
22438 /*
22439 ** Reset an StrAccum string.  Reclaim all malloced memory.
22440 */
22441 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
22442   if( p->zText!=p->zBase ){
22443     if( p->useMalloc==1 ){
22444       sqlite3DbFree(p->db, p->zText);
22445     }else{
22446       sqlite3_free(p->zText);
22447     }
22448   }
22449   p->zText = 0;
22450 }
22451
22452 /*
22453 ** Initialize a string accumulator
22454 */
22455 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
22456   p->zText = p->zBase = zBase;
22457   p->db = 0;
22458   p->nChar = 0;
22459   p->nAlloc = n;
22460   p->mxAlloc = mx;
22461   p->useMalloc = 1;
22462   p->tooBig = 0;
22463   p->mallocFailed = 0;
22464 }
22465
22466 /*
22467 ** Print into memory obtained from sqliteMalloc().  Use the internal
22468 ** %-conversion extensions.
22469 */
22470 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
22471   char *z;
22472   char zBase[SQLITE_PRINT_BUF_SIZE];
22473   StrAccum acc;
22474   assert( db!=0 );
22475   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
22476                       db->aLimit[SQLITE_LIMIT_LENGTH]);
22477   acc.db = db;
22478   sqlite3VXPrintf(&acc, 1, zFormat, ap);
22479   z = sqlite3StrAccumFinish(&acc);
22480   if( acc.mallocFailed ){
22481     db->mallocFailed = 1;
22482   }
22483   return z;
22484 }
22485
22486 /*
22487 ** Print into memory obtained from sqliteMalloc().  Use the internal
22488 ** %-conversion extensions.
22489 */
22490 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
22491   va_list ap;
22492   char *z;
22493   va_start(ap, zFormat);
22494   z = sqlite3VMPrintf(db, zFormat, ap);
22495   va_end(ap);
22496   return z;
22497 }
22498
22499 /*
22500 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
22501 ** the string and before returnning.  This routine is intended to be used
22502 ** to modify an existing string.  For example:
22503 **
22504 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
22505 **
22506 */
22507 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
22508   va_list ap;
22509   char *z;
22510   va_start(ap, zFormat);
22511   z = sqlite3VMPrintf(db, zFormat, ap);
22512   va_end(ap);
22513   sqlite3DbFree(db, zStr);
22514   return z;
22515 }
22516
22517 /*
22518 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
22519 ** %-conversion extensions.
22520 */
22521 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
22522   char *z;
22523   char zBase[SQLITE_PRINT_BUF_SIZE];
22524   StrAccum acc;
22525 #ifndef SQLITE_OMIT_AUTOINIT
22526   if( sqlite3_initialize() ) return 0;
22527 #endif
22528   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
22529   acc.useMalloc = 2;
22530   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22531   z = sqlite3StrAccumFinish(&acc);
22532   return z;
22533 }
22534
22535 /*
22536 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
22537 ** %-conversion extensions.
22538 */
22539 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
22540   va_list ap;
22541   char *z;
22542 #ifndef SQLITE_OMIT_AUTOINIT
22543   if( sqlite3_initialize() ) return 0;
22544 #endif
22545   va_start(ap, zFormat);
22546   z = sqlite3_vmprintf(zFormat, ap);
22547   va_end(ap);
22548   return z;
22549 }
22550
22551 /*
22552 ** sqlite3_snprintf() works like snprintf() except that it ignores the
22553 ** current locale settings.  This is important for SQLite because we
22554 ** are not able to use a "," as the decimal point in place of "." as
22555 ** specified by some locales.
22556 **
22557 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
22558 ** from the snprintf() standard.  Unfortunately, it is too late to change
22559 ** this without breaking compatibility, so we just have to live with the
22560 ** mistake.
22561 **
22562 ** sqlite3_vsnprintf() is the varargs version.
22563 */
22564 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
22565   StrAccum acc;
22566   if( n<=0 ) return zBuf;
22567   sqlite3StrAccumInit(&acc, zBuf, n, 0);
22568   acc.useMalloc = 0;
22569   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22570   return sqlite3StrAccumFinish(&acc);
22571 }
22572 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
22573   char *z;
22574   va_list ap;
22575   va_start(ap,zFormat);
22576   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
22577   va_end(ap);
22578   return z;
22579 }
22580
22581 /*
22582 ** This is the routine that actually formats the sqlite3_log() message.
22583 ** We house it in a separate routine from sqlite3_log() to avoid using
22584 ** stack space on small-stack systems when logging is disabled.
22585 **
22586 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
22587 ** allocate memory because it might be called while the memory allocator
22588 ** mutex is held.
22589 */
22590 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
22591   StrAccum acc;                          /* String accumulator */
22592   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
22593
22594   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
22595   acc.useMalloc = 0;
22596   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22597   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
22598                            sqlite3StrAccumFinish(&acc));
22599 }
22600
22601 /*
22602 ** Format and write a message to the log if logging is enabled.
22603 */
22604 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
22605   va_list ap;                             /* Vararg list */
22606   if( sqlite3GlobalConfig.xLog ){
22607     va_start(ap, zFormat);
22608     renderLogMsg(iErrCode, zFormat, ap);
22609     va_end(ap);
22610   }
22611 }
22612
22613 #if defined(SQLITE_DEBUG)
22614 /*
22615 ** A version of printf() that understands %lld.  Used for debugging.
22616 ** The printf() built into some versions of windows does not understand %lld
22617 ** and segfaults if you give it a long long int.
22618 */
22619 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
22620   va_list ap;
22621   StrAccum acc;
22622   char zBuf[500];
22623   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
22624   acc.useMalloc = 0;
22625   va_start(ap,zFormat);
22626   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22627   va_end(ap);
22628   sqlite3StrAccumFinish(&acc);
22629   fprintf(stdout,"%s", zBuf);
22630   fflush(stdout);
22631 }
22632 #endif
22633
22634 #ifndef SQLITE_OMIT_TRACE
22635 /*
22636 ** variable-argument wrapper around sqlite3VXPrintf().
22637 */
22638 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
22639   va_list ap;
22640   va_start(ap,zFormat);
22641   sqlite3VXPrintf(p, 1, zFormat, ap);
22642   va_end(ap);
22643 }
22644 #endif
22645
22646 /************** End of printf.c **********************************************/
22647 /************** Begin file random.c ******************************************/
22648 /*
22649 ** 2001 September 15
22650 **
22651 ** The author disclaims copyright to this source code.  In place of
22652 ** a legal notice, here is a blessing:
22653 **
22654 **    May you do good and not evil.
22655 **    May you find forgiveness for yourself and forgive others.
22656 **    May you share freely, never taking more than you give.
22657 **
22658 *************************************************************************
22659 ** This file contains code to implement a pseudo-random number
22660 ** generator (PRNG) for SQLite.
22661 **
22662 ** Random numbers are used by some of the database backends in order
22663 ** to generate random integer keys for tables or random filenames.
22664 */
22665
22666
22667 /* All threads share a single random number generator.
22668 ** This structure is the current state of the generator.
22669 */
22670 static SQLITE_WSD struct sqlite3PrngType {
22671   unsigned char isInit;          /* True if initialized */
22672   unsigned char i, j;            /* State variables */
22673   unsigned char s[256];          /* State variables */
22674 } sqlite3Prng;
22675
22676 /*
22677 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
22678 ** must be held while executing this routine.
22679 **
22680 ** Why not just use a library random generator like lrand48() for this?
22681 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
22682 ** good source of random numbers.  The lrand48() library function may
22683 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
22684 ** subtle problems on some systems that could cause problems.  It is hard
22685 ** to know.  To minimize the risk of problems due to bad lrand48()
22686 ** implementations, SQLite uses this random number generator based
22687 ** on RC4, which we know works very well.
22688 **
22689 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
22690 ** randomness any more.  But we will leave this code in all the same.
22691 */
22692 static u8 randomByte(void){
22693   unsigned char t;
22694
22695
22696   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
22697   ** state vector.  If writable static data is unsupported on the target,
22698   ** we have to locate the state vector at run-time.  In the more common
22699   ** case where writable static data is supported, wsdPrng can refer directly
22700   ** to the "sqlite3Prng" state vector declared above.
22701   */
22702 #ifdef SQLITE_OMIT_WSD
22703   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
22704 # define wsdPrng p[0]
22705 #else
22706 # define wsdPrng sqlite3Prng
22707 #endif
22708
22709
22710   /* Initialize the state of the random number generator once,
22711   ** the first time this routine is called.  The seed value does
22712   ** not need to contain a lot of randomness since we are not
22713   ** trying to do secure encryption or anything like that...
22714   **
22715   ** Nothing in this file or anywhere else in SQLite does any kind of
22716   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
22717   ** number generator) not as an encryption device.
22718   */
22719   if( !wsdPrng.isInit ){
22720     int i;
22721     char k[256];
22722     wsdPrng.j = 0;
22723     wsdPrng.i = 0;
22724     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
22725     for(i=0; i<256; i++){
22726       wsdPrng.s[i] = (u8)i;
22727     }
22728     for(i=0; i<256; i++){
22729       wsdPrng.j += wsdPrng.s[i] + k[i];
22730       t = wsdPrng.s[wsdPrng.j];
22731       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
22732       wsdPrng.s[i] = t;
22733     }
22734     wsdPrng.isInit = 1;
22735   }
22736
22737   /* Generate and return single random byte
22738   */
22739   wsdPrng.i++;
22740   t = wsdPrng.s[wsdPrng.i];
22741   wsdPrng.j += t;
22742   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
22743   wsdPrng.s[wsdPrng.j] = t;
22744   t += wsdPrng.s[wsdPrng.i];
22745   return wsdPrng.s[t];
22746 }
22747
22748 /*
22749 ** Return N random bytes.
22750 */
22751 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
22752   unsigned char *zBuf = pBuf;
22753 #if SQLITE_THREADSAFE
22754   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
22755 #endif
22756   sqlite3_mutex_enter(mutex);
22757   while( N-- ){
22758     *(zBuf++) = randomByte();
22759   }
22760   sqlite3_mutex_leave(mutex);
22761 }
22762
22763 #ifndef SQLITE_OMIT_BUILTIN_TEST
22764 /*
22765 ** For testing purposes, we sometimes want to preserve the state of
22766 ** PRNG and restore the PRNG to its saved state at a later time, or
22767 ** to reset the PRNG to its initial state.  These routines accomplish
22768 ** those tasks.
22769 **
22770 ** The sqlite3_test_control() interface calls these routines to
22771 ** control the PRNG.
22772 */
22773 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
22774 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
22775   memcpy(
22776     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22777     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22778     sizeof(sqlite3Prng)
22779   );
22780 }
22781 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
22782   memcpy(
22783     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22784     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22785     sizeof(sqlite3Prng)
22786   );
22787 }
22788 SQLITE_PRIVATE void sqlite3PrngResetState(void){
22789   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
22790 }
22791 #endif /* SQLITE_OMIT_BUILTIN_TEST */
22792
22793 /************** End of random.c **********************************************/
22794 /************** Begin file utf.c *********************************************/
22795 /*
22796 ** 2004 April 13
22797 **
22798 ** The author disclaims copyright to this source code.  In place of
22799 ** a legal notice, here is a blessing:
22800 **
22801 **    May you do good and not evil.
22802 **    May you find forgiveness for yourself and forgive others.
22803 **    May you share freely, never taking more than you give.
22804 **
22805 *************************************************************************
22806 ** This file contains routines used to translate between UTF-8,
22807 ** UTF-16, UTF-16BE, and UTF-16LE.
22808 **
22809 ** Notes on UTF-8:
22810 **
22811 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
22812 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
22813 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
22814 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
22815 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
22816 **
22817 **
22818 ** Notes on UTF-16:  (with wwww+1==uuuuu)
22819 **
22820 **      Word-0               Word-1          Value
22821 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
22822 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
22823 **
22824 **
22825 ** BOM or Byte Order Mark:
22826 **     0xff 0xfe   little-endian utf-16 follows
22827 **     0xfe 0xff   big-endian utf-16 follows
22828 **
22829 */
22830 /* #include <assert.h> */
22831
22832 #ifndef SQLITE_AMALGAMATION
22833 /*
22834 ** The following constant value is used by the SQLITE_BIGENDIAN and
22835 ** SQLITE_LITTLEENDIAN macros.
22836 */
22837 SQLITE_PRIVATE const int sqlite3one = 1;
22838 #endif /* SQLITE_AMALGAMATION */
22839
22840 /*
22841 ** This lookup table is used to help decode the first byte of
22842 ** a multi-byte UTF8 character.
22843 */
22844 static const unsigned char sqlite3Utf8Trans1[] = {
22845   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22846   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22847   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22848   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22849   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22850   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22851   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22852   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22853 };
22854
22855
22856 #define WRITE_UTF8(zOut, c) {                          \
22857   if( c<0x00080 ){                                     \
22858     *zOut++ = (u8)(c&0xFF);                            \
22859   }                                                    \
22860   else if( c<0x00800 ){                                \
22861     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
22862     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22863   }                                                    \
22864   else if( c<0x10000 ){                                \
22865     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
22866     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22867     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22868   }else{                                               \
22869     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
22870     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
22871     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22872     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22873   }                                                    \
22874 }
22875
22876 #define WRITE_UTF16LE(zOut, c) {                                    \
22877   if( c<=0xFFFF ){                                                  \
22878     *zOut++ = (u8)(c&0x00FF);                                       \
22879     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22880   }else{                                                            \
22881     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22882     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22883     *zOut++ = (u8)(c&0x00FF);                                       \
22884     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22885   }                                                                 \
22886 }
22887
22888 #define WRITE_UTF16BE(zOut, c) {                                    \
22889   if( c<=0xFFFF ){                                                  \
22890     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22891     *zOut++ = (u8)(c&0x00FF);                                       \
22892   }else{                                                            \
22893     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22894     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22895     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22896     *zOut++ = (u8)(c&0x00FF);                                       \
22897   }                                                                 \
22898 }
22899
22900 #define READ_UTF16LE(zIn, TERM, c){                                   \
22901   c = (*zIn++);                                                       \
22902   c += ((*zIn++)<<8);                                                 \
22903   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22904     int c2 = (*zIn++);                                                \
22905     c2 += ((*zIn++)<<8);                                              \
22906     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22907   }                                                                   \
22908 }
22909
22910 #define READ_UTF16BE(zIn, TERM, c){                                   \
22911   c = ((*zIn++)<<8);                                                  \
22912   c += (*zIn++);                                                      \
22913   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22914     int c2 = ((*zIn++)<<8);                                           \
22915     c2 += (*zIn++);                                                   \
22916     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22917   }                                                                   \
22918 }
22919
22920 /*
22921 ** Translate a single UTF-8 character.  Return the unicode value.
22922 **
22923 ** During translation, assume that the byte that zTerm points
22924 ** is a 0x00.
22925 **
22926 ** Write a pointer to the next unread byte back into *pzNext.
22927 **
22928 ** Notes On Invalid UTF-8:
22929 **
22930 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
22931 **     be encoded as a multi-byte character.  Any multi-byte character that
22932 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
22933 **
22934 **  *  This routine never allows a UTF16 surrogate value to be encoded.
22935 **     If a multi-byte character attempts to encode a value between
22936 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
22937 **
22938 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
22939 **     byte of a character are interpreted as single-byte characters
22940 **     and rendered as themselves even though they are technically
22941 **     invalid characters.
22942 **
22943 **  *  This routine accepts an infinite number of different UTF8 encodings
22944 **     for unicode values 0x80 and greater.  It do not change over-length
22945 **     encodings to 0xfffd as some systems recommend.
22946 */
22947 #define READ_UTF8(zIn, zTerm, c)                           \
22948   c = *(zIn++);                                            \
22949   if( c>=0xc0 ){                                           \
22950     c = sqlite3Utf8Trans1[c-0xc0];                         \
22951     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
22952       c = (c<<6) + (0x3f & *(zIn++));                      \
22953     }                                                      \
22954     if( c<0x80                                             \
22955         || (c&0xFFFFF800)==0xD800                          \
22956         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
22957   }
22958 SQLITE_PRIVATE u32 sqlite3Utf8Read(
22959   const unsigned char **pz    /* Pointer to string from which to read char */
22960 ){
22961   unsigned int c;
22962
22963   /* Same as READ_UTF8() above but without the zTerm parameter.
22964   ** For this routine, we assume the UTF8 string is always zero-terminated.
22965   */
22966   c = *((*pz)++);
22967   if( c>=0xc0 ){
22968     c = sqlite3Utf8Trans1[c-0xc0];
22969     while( (*(*pz) & 0xc0)==0x80 ){
22970       c = (c<<6) + (0x3f & *((*pz)++));
22971     }
22972     if( c<0x80
22973         || (c&0xFFFFF800)==0xD800
22974         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
22975   }
22976   return c;
22977 }
22978
22979
22980
22981
22982 /*
22983 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
22984 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
22985 */
22986 /* #define TRANSLATE_TRACE 1 */
22987
22988 #ifndef SQLITE_OMIT_UTF16
22989 /*
22990 ** This routine transforms the internal text encoding used by pMem to
22991 ** desiredEnc. It is an error if the string is already of the desired
22992 ** encoding, or if *pMem does not contain a string value.
22993 */
22994 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
22995   int len;                    /* Maximum length of output string in bytes */
22996   unsigned char *zOut;                  /* Output buffer */
22997   unsigned char *zIn;                   /* Input iterator */
22998   unsigned char *zTerm;                 /* End of input */
22999   unsigned char *z;                     /* Output iterator */
23000   unsigned int c;
23001
23002   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
23003   assert( pMem->flags&MEM_Str );
23004   assert( pMem->enc!=desiredEnc );
23005   assert( pMem->enc!=0 );
23006   assert( pMem->n>=0 );
23007
23008 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
23009   {
23010     char zBuf[100];
23011     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
23012     fprintf(stderr, "INPUT:  %s\n", zBuf);
23013   }
23014 #endif
23015
23016   /* If the translation is between UTF-16 little and big endian, then
23017   ** all that is required is to swap the byte order. This case is handled
23018   ** differently from the others.
23019   */
23020   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
23021     u8 temp;
23022     int rc;
23023     rc = sqlite3VdbeMemMakeWriteable(pMem);
23024     if( rc!=SQLITE_OK ){
23025       assert( rc==SQLITE_NOMEM );
23026       return SQLITE_NOMEM;
23027     }
23028     zIn = (u8*)pMem->z;
23029     zTerm = &zIn[pMem->n&~1];
23030     while( zIn<zTerm ){
23031       temp = *zIn;
23032       *zIn = *(zIn+1);
23033       zIn++;
23034       *zIn++ = temp;
23035     }
23036     pMem->enc = desiredEnc;
23037     goto translate_out;
23038   }
23039
23040   /* Set len to the maximum number of bytes required in the output buffer. */
23041   if( desiredEnc==SQLITE_UTF8 ){
23042     /* When converting from UTF-16, the maximum growth results from
23043     ** translating a 2-byte character to a 4-byte UTF-8 character.
23044     ** A single byte is required for the output string
23045     ** nul-terminator.
23046     */
23047     pMem->n &= ~1;
23048     len = pMem->n * 2 + 1;
23049   }else{
23050     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
23051     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
23052     ** character. Two bytes are required in the output buffer for the
23053     ** nul-terminator.
23054     */
23055     len = pMem->n * 2 + 2;
23056   }
23057
23058   /* Set zIn to point at the start of the input buffer and zTerm to point 1
23059   ** byte past the end.
23060   **
23061   ** Variable zOut is set to point at the output buffer, space obtained
23062   ** from sqlite3_malloc().
23063   */
23064   zIn = (u8*)pMem->z;
23065   zTerm = &zIn[pMem->n];
23066   zOut = sqlite3DbMallocRaw(pMem->db, len);
23067   if( !zOut ){
23068     return SQLITE_NOMEM;
23069   }
23070   z = zOut;
23071
23072   if( pMem->enc==SQLITE_UTF8 ){
23073     if( desiredEnc==SQLITE_UTF16LE ){
23074       /* UTF-8 -> UTF-16 Little-endian */
23075       while( zIn<zTerm ){
23076         READ_UTF8(zIn, zTerm, c);
23077         WRITE_UTF16LE(z, c);
23078       }
23079     }else{
23080       assert( desiredEnc==SQLITE_UTF16BE );
23081       /* UTF-8 -> UTF-16 Big-endian */
23082       while( zIn<zTerm ){
23083         READ_UTF8(zIn, zTerm, c);
23084         WRITE_UTF16BE(z, c);
23085       }
23086     }
23087     pMem->n = (int)(z - zOut);
23088     *z++ = 0;
23089   }else{
23090     assert( desiredEnc==SQLITE_UTF8 );
23091     if( pMem->enc==SQLITE_UTF16LE ){
23092       /* UTF-16 Little-endian -> UTF-8 */
23093       while( zIn<zTerm ){
23094         READ_UTF16LE(zIn, zIn<zTerm, c);
23095         WRITE_UTF8(z, c);
23096       }
23097     }else{
23098       /* UTF-16 Big-endian -> UTF-8 */
23099       while( zIn<zTerm ){
23100         READ_UTF16BE(zIn, zIn<zTerm, c);
23101         WRITE_UTF8(z, c);
23102       }
23103     }
23104     pMem->n = (int)(z - zOut);
23105   }
23106   *z = 0;
23107   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
23108
23109   sqlite3VdbeMemRelease(pMem);
23110   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
23111   pMem->enc = desiredEnc;
23112   pMem->flags |= (MEM_Term|MEM_Dyn);
23113   pMem->z = (char*)zOut;
23114   pMem->zMalloc = pMem->z;
23115
23116 translate_out:
23117 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
23118   {
23119     char zBuf[100];
23120     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
23121     fprintf(stderr, "OUTPUT: %s\n", zBuf);
23122   }
23123 #endif
23124   return SQLITE_OK;
23125 }
23126
23127 /*
23128 ** This routine checks for a byte-order mark at the beginning of the
23129 ** UTF-16 string stored in *pMem. If one is present, it is removed and
23130 ** the encoding of the Mem adjusted. This routine does not do any
23131 ** byte-swapping, it just sets Mem.enc appropriately.
23132 **
23133 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
23134 ** changed by this function.
23135 */
23136 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
23137   int rc = SQLITE_OK;
23138   u8 bom = 0;
23139
23140   assert( pMem->n>=0 );
23141   if( pMem->n>1 ){
23142     u8 b1 = *(u8 *)pMem->z;
23143     u8 b2 = *(((u8 *)pMem->z) + 1);
23144     if( b1==0xFE && b2==0xFF ){
23145       bom = SQLITE_UTF16BE;
23146     }
23147     if( b1==0xFF && b2==0xFE ){
23148       bom = SQLITE_UTF16LE;
23149     }
23150   }
23151
23152   if( bom ){
23153     rc = sqlite3VdbeMemMakeWriteable(pMem);
23154     if( rc==SQLITE_OK ){
23155       pMem->n -= 2;
23156       memmove(pMem->z, &pMem->z[2], pMem->n);
23157       pMem->z[pMem->n] = '\0';
23158       pMem->z[pMem->n+1] = '\0';
23159       pMem->flags |= MEM_Term;
23160       pMem->enc = bom;
23161     }
23162   }
23163   return rc;
23164 }
23165 #endif /* SQLITE_OMIT_UTF16 */
23166
23167 /*
23168 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
23169 ** return the number of unicode characters in pZ up to (but not including)
23170 ** the first 0x00 byte. If nByte is not less than zero, return the
23171 ** number of unicode characters in the first nByte of pZ (or up to
23172 ** the first 0x00, whichever comes first).
23173 */
23174 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
23175   int r = 0;
23176   const u8 *z = (const u8*)zIn;
23177   const u8 *zTerm;
23178   if( nByte>=0 ){
23179     zTerm = &z[nByte];
23180   }else{
23181     zTerm = (const u8*)(-1);
23182   }
23183   assert( z<=zTerm );
23184   while( *z!=0 && z<zTerm ){
23185     SQLITE_SKIP_UTF8(z);
23186     r++;
23187   }
23188   return r;
23189 }
23190
23191 /* This test function is not currently used by the automated test-suite.
23192 ** Hence it is only available in debug builds.
23193 */
23194 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23195 /*
23196 ** Translate UTF-8 to UTF-8.
23197 **
23198 ** This has the effect of making sure that the string is well-formed
23199 ** UTF-8.  Miscoded characters are removed.
23200 **
23201 ** The translation is done in-place and aborted if the output
23202 ** overruns the input.
23203 */
23204 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
23205   unsigned char *zOut = zIn;
23206   unsigned char *zStart = zIn;
23207   u32 c;
23208
23209   while( zIn[0] && zOut<=zIn ){
23210     c = sqlite3Utf8Read((const u8**)&zIn);
23211     if( c!=0xfffd ){
23212       WRITE_UTF8(zOut, c);
23213     }
23214   }
23215   *zOut = 0;
23216   return (int)(zOut - zStart);
23217 }
23218 #endif
23219
23220 #ifndef SQLITE_OMIT_UTF16
23221 /*
23222 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
23223 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
23224 ** be freed by the calling function.
23225 **
23226 ** NULL is returned if there is an allocation error.
23227 */
23228 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
23229   Mem m;
23230   memset(&m, 0, sizeof(m));
23231   m.db = db;
23232   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
23233   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
23234   if( db->mallocFailed ){
23235     sqlite3VdbeMemRelease(&m);
23236     m.z = 0;
23237   }
23238   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
23239   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
23240   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
23241   assert( m.z || db->mallocFailed );
23242   return m.z;
23243 }
23244
23245 /*
23246 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
23247 ** enc. A pointer to the new string is returned, and the value of *pnOut
23248 ** is set to the length of the returned string in bytes. The call should
23249 ** arrange to call sqlite3DbFree() on the returned pointer when it is
23250 ** no longer required.
23251 **
23252 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
23253 ** flag set.
23254 */
23255 #ifdef SQLITE_ENABLE_STAT3
23256 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
23257   Mem m;
23258   memset(&m, 0, sizeof(m));
23259   m.db = db;
23260   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
23261   if( sqlite3VdbeMemTranslate(&m, enc) ){
23262     assert( db->mallocFailed );
23263     return 0;
23264   }
23265   assert( m.z==m.zMalloc );
23266   *pnOut = m.n;
23267   return m.z;
23268 }
23269 #endif
23270
23271 /*
23272 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
23273 ** Return the number of bytes in the first nChar unicode characters
23274 ** in pZ.  nChar must be non-negative.
23275 */
23276 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
23277   int c;
23278   unsigned char const *z = zIn;
23279   int n = 0;
23280
23281   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
23282     while( n<nChar ){
23283       READ_UTF16BE(z, 1, c);
23284       n++;
23285     }
23286   }else{
23287     while( n<nChar ){
23288       READ_UTF16LE(z, 1, c);
23289       n++;
23290     }
23291   }
23292   return (int)(z-(unsigned char const *)zIn);
23293 }
23294
23295 #if defined(SQLITE_TEST)
23296 /*
23297 ** This routine is called from the TCL test function "translate_selftest".
23298 ** It checks that the primitives for serializing and deserializing
23299 ** characters in each encoding are inverses of each other.
23300 */
23301 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
23302   unsigned int i, t;
23303   unsigned char zBuf[20];
23304   unsigned char *z;
23305   int n;
23306   unsigned int c;
23307
23308   for(i=0; i<0x00110000; i++){
23309     z = zBuf;
23310     WRITE_UTF8(z, i);
23311     n = (int)(z-zBuf);
23312     assert( n>0 && n<=4 );
23313     z[0] = 0;
23314     z = zBuf;
23315     c = sqlite3Utf8Read((const u8**)&z);
23316     t = i;
23317     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
23318     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
23319     assert( c==t );
23320     assert( (z-zBuf)==n );
23321   }
23322   for(i=0; i<0x00110000; i++){
23323     if( i>=0xD800 && i<0xE000 ) continue;
23324     z = zBuf;
23325     WRITE_UTF16LE(z, i);
23326     n = (int)(z-zBuf);
23327     assert( n>0 && n<=4 );
23328     z[0] = 0;
23329     z = zBuf;
23330     READ_UTF16LE(z, 1, c);
23331     assert( c==i );
23332     assert( (z-zBuf)==n );
23333   }
23334   for(i=0; i<0x00110000; i++){
23335     if( i>=0xD800 && i<0xE000 ) continue;
23336     z = zBuf;
23337     WRITE_UTF16BE(z, i);
23338     n = (int)(z-zBuf);
23339     assert( n>0 && n<=4 );
23340     z[0] = 0;
23341     z = zBuf;
23342     READ_UTF16BE(z, 1, c);
23343     assert( c==i );
23344     assert( (z-zBuf)==n );
23345   }
23346 }
23347 #endif /* SQLITE_TEST */
23348 #endif /* SQLITE_OMIT_UTF16 */
23349
23350 /************** End of utf.c *************************************************/
23351 /************** Begin file util.c ********************************************/
23352 /*
23353 ** 2001 September 15
23354 **
23355 ** The author disclaims copyright to this source code.  In place of
23356 ** a legal notice, here is a blessing:
23357 **
23358 **    May you do good and not evil.
23359 **    May you find forgiveness for yourself and forgive others.
23360 **    May you share freely, never taking more than you give.
23361 **
23362 *************************************************************************
23363 ** Utility functions used throughout sqlite.
23364 **
23365 ** This file contains functions for allocating memory, comparing
23366 ** strings, and stuff like that.
23367 **
23368 */
23369 /* #include <stdarg.h> */
23370 #ifdef SQLITE_HAVE_ISNAN
23371 # include <math.h>
23372 #endif
23373
23374 /*
23375 ** Routine needed to support the testcase() macro.
23376 */
23377 #ifdef SQLITE_COVERAGE_TEST
23378 SQLITE_PRIVATE void sqlite3Coverage(int x){
23379   static unsigned dummy = 0;
23380   dummy += (unsigned)x;
23381 }
23382 #endif
23383
23384 #ifndef SQLITE_OMIT_FLOATING_POINT
23385 /*
23386 ** Return true if the floating point value is Not a Number (NaN).
23387 **
23388 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
23389 ** Otherwise, we have our own implementation that works on most systems.
23390 */
23391 SQLITE_PRIVATE int sqlite3IsNaN(double x){
23392   int rc;   /* The value return */
23393 #if !defined(SQLITE_HAVE_ISNAN)
23394   /*
23395   ** Systems that support the isnan() library function should probably
23396   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
23397   ** found that many systems do not have a working isnan() function so
23398   ** this implementation is provided as an alternative.
23399   **
23400   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
23401   ** On the other hand, the use of -ffast-math comes with the following
23402   ** warning:
23403   **
23404   **      This option [-ffast-math] should never be turned on by any
23405   **      -O option since it can result in incorrect output for programs
23406   **      which depend on an exact implementation of IEEE or ISO
23407   **      rules/specifications for math functions.
23408   **
23409   ** Under MSVC, this NaN test may fail if compiled with a floating-
23410   ** point precision mode other than /fp:precise.  From the MSDN
23411   ** documentation:
23412   **
23413   **      The compiler [with /fp:precise] will properly handle comparisons
23414   **      involving NaN. For example, x != x evaluates to true if x is NaN
23415   **      ...
23416   */
23417 #ifdef __FAST_MATH__
23418 # error SQLite will not work correctly with the -ffast-math option of GCC.
23419 #endif
23420   volatile double y = x;
23421   volatile double z = y;
23422   rc = (y!=z);
23423 #else  /* if defined(SQLITE_HAVE_ISNAN) */
23424   rc = isnan(x);
23425 #endif /* SQLITE_HAVE_ISNAN */
23426   testcase( rc );
23427   return rc;
23428 }
23429 #endif /* SQLITE_OMIT_FLOATING_POINT */
23430
23431 /*
23432 ** Compute a string length that is limited to what can be stored in
23433 ** lower 30 bits of a 32-bit signed integer.
23434 **
23435 ** The value returned will never be negative.  Nor will it ever be greater
23436 ** than the actual length of the string.  For very long strings (greater
23437 ** than 1GiB) the value returned might be less than the true string length.
23438 */
23439 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
23440   const char *z2 = z;
23441   if( z==0 ) return 0;
23442   while( *z2 ){ z2++; }
23443   return 0x3fffffff & (int)(z2 - z);
23444 }
23445
23446 /*
23447 ** Set the most recent error code and error string for the sqlite
23448 ** handle "db". The error code is set to "err_code".
23449 **
23450 ** If it is not NULL, string zFormat specifies the format of the
23451 ** error string in the style of the printf functions: The following
23452 ** format characters are allowed:
23453 **
23454 **      %s      Insert a string
23455 **      %z      A string that should be freed after use
23456 **      %d      Insert an integer
23457 **      %T      Insert a token
23458 **      %S      Insert the first element of a SrcList
23459 **
23460 ** zFormat and any string tokens that follow it are assumed to be
23461 ** encoded in UTF-8.
23462 **
23463 ** To clear the most recent error for sqlite handle "db", sqlite3Error
23464 ** should be called with err_code set to SQLITE_OK and zFormat set
23465 ** to NULL.
23466 */
23467 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
23468   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
23469     db->errCode = err_code;
23470     if( zFormat ){
23471       char *z;
23472       va_list ap;
23473       va_start(ap, zFormat);
23474       z = sqlite3VMPrintf(db, zFormat, ap);
23475       va_end(ap);
23476       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
23477     }else{
23478       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
23479     }
23480   }
23481 }
23482
23483 /*
23484 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
23485 ** The following formatting characters are allowed:
23486 **
23487 **      %s      Insert a string
23488 **      %z      A string that should be freed after use
23489 **      %d      Insert an integer
23490 **      %T      Insert a token
23491 **      %S      Insert the first element of a SrcList
23492 **
23493 ** This function should be used to report any error that occurs whilst
23494 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
23495 ** last thing the sqlite3_prepare() function does is copy the error
23496 ** stored by this function into the database handle using sqlite3Error().
23497 ** Function sqlite3Error() should be used during statement execution
23498 ** (sqlite3_step() etc.).
23499 */
23500 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
23501   char *zMsg;
23502   va_list ap;
23503   sqlite3 *db = pParse->db;
23504   va_start(ap, zFormat);
23505   zMsg = sqlite3VMPrintf(db, zFormat, ap);
23506   va_end(ap);
23507   if( db->suppressErr ){
23508     sqlite3DbFree(db, zMsg);
23509   }else{
23510     pParse->nErr++;
23511     sqlite3DbFree(db, pParse->zErrMsg);
23512     pParse->zErrMsg = zMsg;
23513     pParse->rc = SQLITE_ERROR;
23514   }
23515 }
23516
23517 /*
23518 ** Convert an SQL-style quoted string into a normal string by removing
23519 ** the quote characters.  The conversion is done in-place.  If the
23520 ** input does not begin with a quote character, then this routine
23521 ** is a no-op.
23522 **
23523 ** The input string must be zero-terminated.  A new zero-terminator
23524 ** is added to the dequoted string.
23525 **
23526 ** The return value is -1 if no dequoting occurs or the length of the
23527 ** dequoted string, exclusive of the zero terminator, if dequoting does
23528 ** occur.
23529 **
23530 ** 2002-Feb-14: This routine is extended to remove MS-Access style
23531 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
23532 ** "a-b-c".
23533 */
23534 SQLITE_PRIVATE int sqlite3Dequote(char *z){
23535   char quote;
23536   int i, j;
23537   if( z==0 ) return -1;
23538   quote = z[0];
23539   switch( quote ){
23540     case '\'':  break;
23541     case '"':   break;
23542     case '`':   break;                /* For MySQL compatibility */
23543     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
23544     default:    return -1;
23545   }
23546   for(i=1, j=0; ALWAYS(z[i]); i++){
23547     if( z[i]==quote ){
23548       if( z[i+1]==quote ){
23549         z[j++] = quote;
23550         i++;
23551       }else{
23552         break;
23553       }
23554     }else{
23555       z[j++] = z[i];
23556     }
23557   }
23558   z[j] = 0;
23559   return j;
23560 }
23561
23562 /* Convenient short-hand */
23563 #define UpperToLower sqlite3UpperToLower
23564
23565 /*
23566 ** Some systems have stricmp().  Others have strcasecmp().  Because
23567 ** there is no consistency, we will define our own.
23568 **
23569 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
23570 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
23571 ** the contents of two buffers containing UTF-8 strings in a
23572 ** case-independent fashion, using the same definition of "case
23573 ** independence" that SQLite uses internally when comparing identifiers.
23574 */
23575 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
23576   register unsigned char *a, *b;
23577   a = (unsigned char *)zLeft;
23578   b = (unsigned char *)zRight;
23579   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23580   return UpperToLower[*a] - UpperToLower[*b];
23581 }
23582 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
23583   register unsigned char *a, *b;
23584   a = (unsigned char *)zLeft;
23585   b = (unsigned char *)zRight;
23586   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23587   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
23588 }
23589
23590 /*
23591 ** The string z[] is an text representation of a real number.
23592 ** Convert this string to a double and write it into *pResult.
23593 **
23594 ** The string z[] is length bytes in length (bytes, not characters) and
23595 ** uses the encoding enc.  The string is not necessarily zero-terminated.
23596 **
23597 ** Return TRUE if the result is a valid real number (or integer) and FALSE
23598 ** if the string is empty or contains extraneous text.  Valid numbers
23599 ** are in one of these formats:
23600 **
23601 **    [+-]digits[E[+-]digits]
23602 **    [+-]digits.[digits][E[+-]digits]
23603 **    [+-].digits[E[+-]digits]
23604 **
23605 ** Leading and trailing whitespace is ignored for the purpose of determining
23606 ** validity.
23607 **
23608 ** If some prefix of the input string is a valid number, this routine
23609 ** returns FALSE but it still converts the prefix and writes the result
23610 ** into *pResult.
23611 */
23612 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
23613 #ifndef SQLITE_OMIT_FLOATING_POINT
23614   int incr = (enc==SQLITE_UTF8?1:2);
23615   const char *zEnd = z + length;
23616   /* sign * significand * (10 ^ (esign * exponent)) */
23617   int sign = 1;    /* sign of significand */
23618   i64 s = 0;       /* significand */
23619   int d = 0;       /* adjust exponent for shifting decimal point */
23620   int esign = 1;   /* sign of exponent */
23621   int e = 0;       /* exponent */
23622   int eValid = 1;  /* True exponent is either not used or is well-formed */
23623   double result;
23624   int nDigits = 0;
23625
23626   *pResult = 0.0;   /* Default return value, in case of an error */
23627
23628   if( enc==SQLITE_UTF16BE ) z++;
23629
23630   /* skip leading spaces */
23631   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23632   if( z>=zEnd ) return 0;
23633
23634   /* get sign of significand */
23635   if( *z=='-' ){
23636     sign = -1;
23637     z+=incr;
23638   }else if( *z=='+' ){
23639     z+=incr;
23640   }
23641
23642   /* skip leading zeroes */
23643   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
23644
23645   /* copy max significant digits to significand */
23646   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23647     s = s*10 + (*z - '0');
23648     z+=incr, nDigits++;
23649   }
23650
23651   /* skip non-significant significand digits
23652   ** (increase exponent by d to shift decimal left) */
23653   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
23654   if( z>=zEnd ) goto do_atof_calc;
23655
23656   /* if decimal point is present */
23657   if( *z=='.' ){
23658     z+=incr;
23659     /* copy digits from after decimal to significand
23660     ** (decrease exponent by d to shift decimal right) */
23661     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23662       s = s*10 + (*z - '0');
23663       z+=incr, nDigits++, d--;
23664     }
23665     /* skip non-significant digits */
23666     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
23667   }
23668   if( z>=zEnd ) goto do_atof_calc;
23669
23670   /* if exponent is present */
23671   if( *z=='e' || *z=='E' ){
23672     z+=incr;
23673     eValid = 0;
23674     if( z>=zEnd ) goto do_atof_calc;
23675     /* get sign of exponent */
23676     if( *z=='-' ){
23677       esign = -1;
23678       z+=incr;
23679     }else if( *z=='+' ){
23680       z+=incr;
23681     }
23682     /* copy digits to exponent */
23683     while( z<zEnd && sqlite3Isdigit(*z) ){
23684       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
23685       z+=incr;
23686       eValid = 1;
23687     }
23688   }
23689
23690   /* skip trailing spaces */
23691   if( nDigits && eValid ){
23692     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23693   }
23694
23695 do_atof_calc:
23696   /* adjust exponent by d, and update sign */
23697   e = (e*esign) + d;
23698   if( e<0 ) {
23699     esign = -1;
23700     e *= -1;
23701   } else {
23702     esign = 1;
23703   }
23704
23705   /* if 0 significand */
23706   if( !s ) {
23707     /* In the IEEE 754 standard, zero is signed.
23708     ** Add the sign if we've seen at least one digit */
23709     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23710   } else {
23711     /* attempt to reduce exponent */
23712     if( esign>0 ){
23713       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23714     }else{
23715       while( !(s%10) && e>0 ) e--,s/=10;
23716     }
23717
23718     /* adjust the sign of significand */
23719     s = sign<0 ? -s : s;
23720
23721     /* if exponent, scale significand as appropriate
23722     ** and store in result. */
23723     if( e ){
23724       LONGDOUBLE_TYPE scale = 1.0;
23725       /* attempt to handle extremely small/large numbers better */
23726       if( e>307 && e<342 ){
23727         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23728         if( esign<0 ){
23729           result = s / scale;
23730           result /= 1.0e+308;
23731         }else{
23732           result = s * scale;
23733           result *= 1.0e+308;
23734         }
23735       }else if( e>=342 ){
23736         if( esign<0 ){
23737           result = 0.0*s;
23738         }else{
23739           result = 1e308*1e308*s;  /* Infinity */
23740         }
23741       }else{
23742         /* 1.0e+22 is the largest power of 10 than can be
23743         ** represented exactly. */
23744         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23745         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23746         if( esign<0 ){
23747           result = s / scale;
23748         }else{
23749           result = s * scale;
23750         }
23751       }
23752     } else {
23753       result = (double)s;
23754     }
23755   }
23756
23757   /* store the result */
23758   *pResult = result;
23759
23760   /* return true if number and no extra non-whitespace chracters after */
23761   return z>=zEnd && nDigits>0 && eValid;
23762 #else
23763   return !sqlite3Atoi64(z, pResult, length, enc);
23764 #endif /* SQLITE_OMIT_FLOATING_POINT */
23765 }
23766
23767 /*
23768 ** Compare the 19-character string zNum against the text representation
23769 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
23770 ** if zNum is less than, equal to, or greater than the string.
23771 ** Note that zNum must contain exactly 19 characters.
23772 **
23773 ** Unlike memcmp() this routine is guaranteed to return the difference
23774 ** in the values of the last digit if the only difference is in the
23775 ** last digit.  So, for example,
23776 **
23777 **      compare2pow63("9223372036854775800", 1)
23778 **
23779 ** will return -8.
23780 */
23781 static int compare2pow63(const char *zNum, int incr){
23782   int c = 0;
23783   int i;
23784                     /* 012345678901234567 */
23785   const char *pow63 = "922337203685477580";
23786   for(i=0; c==0 && i<18; i++){
23787     c = (zNum[i*incr]-pow63[i])*10;
23788   }
23789   if( c==0 ){
23790     c = zNum[18*incr] - '8';
23791     testcase( c==(-1) );
23792     testcase( c==0 );
23793     testcase( c==(+1) );
23794   }
23795   return c;
23796 }
23797
23798
23799 /*
23800 ** Convert zNum to a 64-bit signed integer.
23801 **
23802 ** If the zNum value is representable as a 64-bit twos-complement
23803 ** integer, then write that value into *pNum and return 0.
23804 **
23805 ** If zNum is exactly 9223372036854665808, return 2.  This special
23806 ** case is broken out because while 9223372036854665808 cannot be a
23807 ** signed 64-bit integer, its negative -9223372036854665808 can be.
23808 **
23809 ** If zNum is too big for a 64-bit integer and is not
23810 ** 9223372036854665808 then return 1.
23811 **
23812 ** length is the number of bytes in the string (bytes, not characters).
23813 ** The string is not necessarily zero-terminated.  The encoding is
23814 ** given by enc.
23815 */
23816 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23817   int incr = (enc==SQLITE_UTF8?1:2);
23818   u64 u = 0;
23819   int neg = 0; /* assume positive */
23820   int i;
23821   int c = 0;
23822   const char *zStart;
23823   const char *zEnd = zNum + length;
23824   if( enc==SQLITE_UTF16BE ) zNum++;
23825   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
23826   if( zNum<zEnd ){
23827     if( *zNum=='-' ){
23828       neg = 1;
23829       zNum+=incr;
23830     }else if( *zNum=='+' ){
23831       zNum+=incr;
23832     }
23833   }
23834   zStart = zNum;
23835   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23836   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23837     u = u*10 + c - '0';
23838   }
23839   if( u>LARGEST_INT64 ){
23840     *pNum = SMALLEST_INT64;
23841   }else if( neg ){
23842     *pNum = -(i64)u;
23843   }else{
23844     *pNum = (i64)u;
23845   }
23846   testcase( i==18 );
23847   testcase( i==19 );
23848   testcase( i==20 );
23849   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
23850     /* zNum is empty or contains non-numeric text or is longer
23851     ** than 19 digits (thus guaranteeing that it is too large) */
23852     return 1;
23853   }else if( i<19*incr ){
23854     /* Less than 19 digits, so we know that it fits in 64 bits */
23855     assert( u<=LARGEST_INT64 );
23856     return 0;
23857   }else{
23858     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
23859     c = compare2pow63(zNum, incr);
23860     if( c<0 ){
23861       /* zNum is less than 9223372036854775808 so it fits */
23862       assert( u<=LARGEST_INT64 );
23863       return 0;
23864     }else if( c>0 ){
23865       /* zNum is greater than 9223372036854775808 so it overflows */
23866       return 1;
23867     }else{
23868       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
23869       ** special case 2 overflow if positive */
23870       assert( u-1==LARGEST_INT64 );
23871       assert( (*pNum)==SMALLEST_INT64 );
23872       return neg ? 0 : 2;
23873     }
23874   }
23875 }
23876
23877 /*
23878 ** If zNum represents an integer that will fit in 32-bits, then set
23879 ** *pValue to that integer and return true.  Otherwise return false.
23880 **
23881 ** Any non-numeric characters that following zNum are ignored.
23882 ** This is different from sqlite3Atoi64() which requires the
23883 ** input number to be zero-terminated.
23884 */
23885 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
23886   sqlite_int64 v = 0;
23887   int i, c;
23888   int neg = 0;
23889   if( zNum[0]=='-' ){
23890     neg = 1;
23891     zNum++;
23892   }else if( zNum[0]=='+' ){
23893     zNum++;
23894   }
23895   while( zNum[0]=='0' ) zNum++;
23896   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
23897     v = v*10 + c;
23898   }
23899
23900   /* The longest decimal representation of a 32 bit integer is 10 digits:
23901   **
23902   **             1234567890
23903   **     2^31 -> 2147483648
23904   */
23905   testcase( i==10 );
23906   if( i>10 ){
23907     return 0;
23908   }
23909   testcase( v-neg==2147483647 );
23910   if( v-neg>2147483647 ){
23911     return 0;
23912   }
23913   if( neg ){
23914     v = -v;
23915   }
23916   *pValue = (int)v;
23917   return 1;
23918 }
23919
23920 /*
23921 ** Return a 32-bit integer value extracted from a string.  If the
23922 ** string is not an integer, just return 0.
23923 */
23924 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
23925   int x = 0;
23926   if( z ) sqlite3GetInt32(z, &x);
23927   return x;
23928 }
23929
23930 /*
23931 ** The variable-length integer encoding is as follows:
23932 **
23933 ** KEY:
23934 **         A = 0xxxxxxx    7 bits of data and one flag bit
23935 **         B = 1xxxxxxx    7 bits of data and one flag bit
23936 **         C = xxxxxxxx    8 bits of data
23937 **
23938 **  7 bits - A
23939 ** 14 bits - BA
23940 ** 21 bits - BBA
23941 ** 28 bits - BBBA
23942 ** 35 bits - BBBBA
23943 ** 42 bits - BBBBBA
23944 ** 49 bits - BBBBBBA
23945 ** 56 bits - BBBBBBBA
23946 ** 64 bits - BBBBBBBBC
23947 */
23948
23949 /*
23950 ** Write a 64-bit variable-length integer to memory starting at p[0].
23951 ** The length of data write will be between 1 and 9 bytes.  The number
23952 ** of bytes written is returned.
23953 **
23954 ** A variable-length integer consists of the lower 7 bits of each byte
23955 ** for all bytes that have the 8th bit set and one byte with the 8th
23956 ** bit clear.  Except, if we get to the 9th byte, it stores the full
23957 ** 8 bits and is the last byte.
23958 */
23959 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
23960   int i, j, n;
23961   u8 buf[10];
23962   if( v & (((u64)0xff000000)<<32) ){
23963     p[8] = (u8)v;
23964     v >>= 8;
23965     for(i=7; i>=0; i--){
23966       p[i] = (u8)((v & 0x7f) | 0x80);
23967       v >>= 7;
23968     }
23969     return 9;
23970   }
23971   n = 0;
23972   do{
23973     buf[n++] = (u8)((v & 0x7f) | 0x80);
23974     v >>= 7;
23975   }while( v!=0 );
23976   buf[0] &= 0x7f;
23977   assert( n<=9 );
23978   for(i=0, j=n-1; j>=0; j--, i++){
23979     p[i] = buf[j];
23980   }
23981   return n;
23982 }
23983
23984 /*
23985 ** This routine is a faster version of sqlite3PutVarint() that only
23986 ** works for 32-bit positive integers and which is optimized for
23987 ** the common case of small integers.  A MACRO version, putVarint32,
23988 ** is provided which inlines the single-byte case.  All code should use
23989 ** the MACRO version as this function assumes the single-byte case has
23990 ** already been handled.
23991 */
23992 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
23993 #ifndef putVarint32
23994   if( (v & ~0x7f)==0 ){
23995     p[0] = v;
23996     return 1;
23997   }
23998 #endif
23999   if( (v & ~0x3fff)==0 ){
24000     p[0] = (u8)((v>>7) | 0x80);
24001     p[1] = (u8)(v & 0x7f);
24002     return 2;
24003   }
24004   return sqlite3PutVarint(p, v);
24005 }
24006
24007 /*
24008 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
24009 ** are defined here rather than simply putting the constant expressions
24010 ** inline in order to work around bugs in the RVT compiler.
24011 **
24012 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
24013 **
24014 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
24015 */
24016 #define SLOT_2_0     0x001fc07f
24017 #define SLOT_4_2_0   0xf01fc07f
24018
24019
24020 /*
24021 ** Read a 64-bit variable-length integer from memory starting at p[0].
24022 ** Return the number of bytes read.  The value is stored in *v.
24023 */
24024 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
24025   u32 a,b,s;
24026
24027   a = *p;
24028   /* a: p0 (unmasked) */
24029   if (!(a&0x80))
24030   {
24031     *v = a;
24032     return 1;
24033   }
24034
24035   p++;
24036   b = *p;
24037   /* b: p1 (unmasked) */
24038   if (!(b&0x80))
24039   {
24040     a &= 0x7f;
24041     a = a<<7;
24042     a |= b;
24043     *v = a;
24044     return 2;
24045   }
24046
24047   /* Verify that constants are precomputed correctly */
24048   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
24049   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
24050
24051   p++;
24052   a = a<<14;
24053   a |= *p;
24054   /* a: p0<<14 | p2 (unmasked) */
24055   if (!(a&0x80))
24056   {
24057     a &= SLOT_2_0;
24058     b &= 0x7f;
24059     b = b<<7;
24060     a |= b;
24061     *v = a;
24062     return 3;
24063   }
24064
24065   /* CSE1 from below */
24066   a &= SLOT_2_0;
24067   p++;
24068   b = b<<14;
24069   b |= *p;
24070   /* b: p1<<14 | p3 (unmasked) */
24071   if (!(b&0x80))
24072   {
24073     b &= SLOT_2_0;
24074     /* moved CSE1 up */
24075     /* a &= (0x7f<<14)|(0x7f); */
24076     a = a<<7;
24077     a |= b;
24078     *v = a;
24079     return 4;
24080   }
24081
24082   /* a: p0<<14 | p2 (masked) */
24083   /* b: p1<<14 | p3 (unmasked) */
24084   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24085   /* moved CSE1 up */
24086   /* a &= (0x7f<<14)|(0x7f); */
24087   b &= SLOT_2_0;
24088   s = a;
24089   /* s: p0<<14 | p2 (masked) */
24090
24091   p++;
24092   a = a<<14;
24093   a |= *p;
24094   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
24095   if (!(a&0x80))
24096   {
24097     /* we can skip these cause they were (effectively) done above in calc'ing s */
24098     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
24099     /* b &= (0x7f<<14)|(0x7f); */
24100     b = b<<7;
24101     a |= b;
24102     s = s>>18;
24103     *v = ((u64)s)<<32 | a;
24104     return 5;
24105   }
24106
24107   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24108   s = s<<7;
24109   s |= b;
24110   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24111
24112   p++;
24113   b = b<<14;
24114   b |= *p;
24115   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
24116   if (!(b&0x80))
24117   {
24118     /* we can skip this cause it was (effectively) done above in calc'ing s */
24119     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
24120     a &= SLOT_2_0;
24121     a = a<<7;
24122     a |= b;
24123     s = s>>18;
24124     *v = ((u64)s)<<32 | a;
24125     return 6;
24126   }
24127
24128   p++;
24129   a = a<<14;
24130   a |= *p;
24131   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
24132   if (!(a&0x80))
24133   {
24134     a &= SLOT_4_2_0;
24135     b &= SLOT_2_0;
24136     b = b<<7;
24137     a |= b;
24138     s = s>>11;
24139     *v = ((u64)s)<<32 | a;
24140     return 7;
24141   }
24142
24143   /* CSE2 from below */
24144   a &= SLOT_2_0;
24145   p++;
24146   b = b<<14;
24147   b |= *p;
24148   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
24149   if (!(b&0x80))
24150   {
24151     b &= SLOT_4_2_0;
24152     /* moved CSE2 up */
24153     /* a &= (0x7f<<14)|(0x7f); */
24154     a = a<<7;
24155     a |= b;
24156     s = s>>4;
24157     *v = ((u64)s)<<32 | a;
24158     return 8;
24159   }
24160
24161   p++;
24162   a = a<<15;
24163   a |= *p;
24164   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
24165
24166   /* moved CSE2 up */
24167   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
24168   b &= SLOT_2_0;
24169   b = b<<8;
24170   a |= b;
24171
24172   s = s<<4;
24173   b = p[-4];
24174   b &= 0x7f;
24175   b = b>>3;
24176   s |= b;
24177
24178   *v = ((u64)s)<<32 | a;
24179
24180   return 9;
24181 }
24182
24183 /*
24184 ** Read a 32-bit variable-length integer from memory starting at p[0].
24185 ** Return the number of bytes read.  The value is stored in *v.
24186 **
24187 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
24188 ** integer, then set *v to 0xffffffff.
24189 **
24190 ** A MACRO version, getVarint32, is provided which inlines the
24191 ** single-byte case.  All code should use the MACRO version as
24192 ** this function assumes the single-byte case has already been handled.
24193 */
24194 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
24195   u32 a,b;
24196
24197   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
24198   ** by the getVarin32() macro */
24199   a = *p;
24200   /* a: p0 (unmasked) */
24201 #ifndef getVarint32
24202   if (!(a&0x80))
24203   {
24204     /* Values between 0 and 127 */
24205     *v = a;
24206     return 1;
24207   }
24208 #endif
24209
24210   /* The 2-byte case */
24211   p++;
24212   b = *p;
24213   /* b: p1 (unmasked) */
24214   if (!(b&0x80))
24215   {
24216     /* Values between 128 and 16383 */
24217     a &= 0x7f;
24218     a = a<<7;
24219     *v = a | b;
24220     return 2;
24221   }
24222
24223   /* The 3-byte case */
24224   p++;
24225   a = a<<14;
24226   a |= *p;
24227   /* a: p0<<14 | p2 (unmasked) */
24228   if (!(a&0x80))
24229   {
24230     /* Values between 16384 and 2097151 */
24231     a &= (0x7f<<14)|(0x7f);
24232     b &= 0x7f;
24233     b = b<<7;
24234     *v = a | b;
24235     return 3;
24236   }
24237
24238   /* A 32-bit varint is used to store size information in btrees.
24239   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
24240   ** A 3-byte varint is sufficient, for example, to record the size
24241   ** of a 1048569-byte BLOB or string.
24242   **
24243   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
24244   ** rare larger cases can be handled by the slower 64-bit varint
24245   ** routine.
24246   */
24247 #if 1
24248   {
24249     u64 v64;
24250     u8 n;
24251
24252     p -= 2;
24253     n = sqlite3GetVarint(p, &v64);
24254     assert( n>3 && n<=9 );
24255     if( (v64 & SQLITE_MAX_U32)!=v64 ){
24256       *v = 0xffffffff;
24257     }else{
24258       *v = (u32)v64;
24259     }
24260     return n;
24261   }
24262
24263 #else
24264   /* For following code (kept for historical record only) shows an
24265   ** unrolling for the 3- and 4-byte varint cases.  This code is
24266   ** slightly faster, but it is also larger and much harder to test.
24267   */
24268   p++;
24269   b = b<<14;
24270   b |= *p;
24271   /* b: p1<<14 | p3 (unmasked) */
24272   if (!(b&0x80))
24273   {
24274     /* Values between 2097152 and 268435455 */
24275     b &= (0x7f<<14)|(0x7f);
24276     a &= (0x7f<<14)|(0x7f);
24277     a = a<<7;
24278     *v = a | b;
24279     return 4;
24280   }
24281
24282   p++;
24283   a = a<<14;
24284   a |= *p;
24285   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
24286   if (!(a&0x80))
24287   {
24288     /* Values  between 268435456 and 34359738367 */
24289     a &= SLOT_4_2_0;
24290     b &= SLOT_4_2_0;
24291     b = b<<7;
24292     *v = a | b;
24293     return 5;
24294   }
24295
24296   /* We can only reach this point when reading a corrupt database
24297   ** file.  In that case we are not in any hurry.  Use the (relatively
24298   ** slow) general-purpose sqlite3GetVarint() routine to extract the
24299   ** value. */
24300   {
24301     u64 v64;
24302     u8 n;
24303
24304     p -= 4;
24305     n = sqlite3GetVarint(p, &v64);
24306     assert( n>5 && n<=9 );
24307     *v = (u32)v64;
24308     return n;
24309   }
24310 #endif
24311 }
24312
24313 /*
24314 ** Return the number of bytes that will be needed to store the given
24315 ** 64-bit integer.
24316 */
24317 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
24318   int i = 0;
24319   do{
24320     i++;
24321     v >>= 7;
24322   }while( v!=0 && ALWAYS(i<9) );
24323   return i;
24324 }
24325
24326
24327 /*
24328 ** Read or write a four-byte big-endian integer value.
24329 */
24330 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
24331   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
24332 }
24333 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
24334   p[0] = (u8)(v>>24);
24335   p[1] = (u8)(v>>16);
24336   p[2] = (u8)(v>>8);
24337   p[3] = (u8)v;
24338 }
24339
24340
24341
24342 /*
24343 ** Translate a single byte of Hex into an integer.
24344 ** This routine only works if h really is a valid hexadecimal
24345 ** character:  0..9a..fA..F
24346 */
24347 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
24348   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
24349 #ifdef SQLITE_ASCII
24350   h += 9*(1&(h>>6));
24351 #endif
24352 #ifdef SQLITE_EBCDIC
24353   h += 9*(1&~(h>>4));
24354 #endif
24355   return (u8)(h & 0xf);
24356 }
24357
24358 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
24359 /*
24360 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
24361 ** value.  Return a pointer to its binary value.  Space to hold the
24362 ** binary value has been obtained from malloc and must be freed by
24363 ** the calling routine.
24364 */
24365 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
24366   char *zBlob;
24367   int i;
24368
24369   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
24370   n--;
24371   if( zBlob ){
24372     for(i=0; i<n; i+=2){
24373       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
24374     }
24375     zBlob[i/2] = 0;
24376   }
24377   return zBlob;
24378 }
24379 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
24380
24381 /*
24382 ** Log an error that is an API call on a connection pointer that should
24383 ** not have been used.  The "type" of connection pointer is given as the
24384 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
24385 */
24386 static void logBadConnection(const char *zType){
24387   sqlite3_log(SQLITE_MISUSE,
24388      "API call with %s database connection pointer",
24389      zType
24390   );
24391 }
24392
24393 /*
24394 ** Check to make sure we have a valid db pointer.  This test is not
24395 ** foolproof but it does provide some measure of protection against
24396 ** misuse of the interface such as passing in db pointers that are
24397 ** NULL or which have been previously closed.  If this routine returns
24398 ** 1 it means that the db pointer is valid and 0 if it should not be
24399 ** dereferenced for any reason.  The calling function should invoke
24400 ** SQLITE_MISUSE immediately.
24401 **
24402 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
24403 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
24404 ** open properly and is not fit for general use but which can be
24405 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
24406 */
24407 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
24408   u32 magic;
24409   if( db==0 ){
24410     logBadConnection("NULL");
24411     return 0;
24412   }
24413   magic = db->magic;
24414   if( magic!=SQLITE_MAGIC_OPEN ){
24415     if( sqlite3SafetyCheckSickOrOk(db) ){
24416       testcase( sqlite3GlobalConfig.xLog!=0 );
24417       logBadConnection("unopened");
24418     }
24419     return 0;
24420   }else{
24421     return 1;
24422   }
24423 }
24424 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
24425   u32 magic;
24426   magic = db->magic;
24427   if( magic!=SQLITE_MAGIC_SICK &&
24428       magic!=SQLITE_MAGIC_OPEN &&
24429       magic!=SQLITE_MAGIC_BUSY ){
24430     testcase( sqlite3GlobalConfig.xLog!=0 );
24431     logBadConnection("invalid");
24432     return 0;
24433   }else{
24434     return 1;
24435   }
24436 }
24437
24438 /*
24439 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
24440 ** the other 64-bit signed integer at *pA and store the result in *pA.
24441 ** Return 0 on success.  Or if the operation would have resulted in an
24442 ** overflow, leave *pA unchanged and return 1.
24443 */
24444 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
24445   i64 iA = *pA;
24446   testcase( iA==0 ); testcase( iA==1 );
24447   testcase( iB==-1 ); testcase( iB==0 );
24448   if( iB>=0 ){
24449     testcase( iA>0 && LARGEST_INT64 - iA == iB );
24450     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
24451     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
24452     *pA += iB;
24453   }else{
24454     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
24455     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
24456     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
24457     *pA += iB;
24458   }
24459   return 0;
24460 }
24461 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
24462   testcase( iB==SMALLEST_INT64+1 );
24463   if( iB==SMALLEST_INT64 ){
24464     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
24465     if( (*pA)>=0 ) return 1;
24466     *pA -= iB;
24467     return 0;
24468   }else{
24469     return sqlite3AddInt64(pA, -iB);
24470   }
24471 }
24472 #define TWOPOWER32 (((i64)1)<<32)
24473 #define TWOPOWER31 (((i64)1)<<31)
24474 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
24475   i64 iA = *pA;
24476   i64 iA1, iA0, iB1, iB0, r;
24477
24478   iA1 = iA/TWOPOWER32;
24479   iA0 = iA % TWOPOWER32;
24480   iB1 = iB/TWOPOWER32;
24481   iB0 = iB % TWOPOWER32;
24482   if( iA1*iB1 != 0 ) return 1;
24483   assert( iA1*iB0==0 || iA0*iB1==0 );
24484   r = iA1*iB0 + iA0*iB1;
24485   testcase( r==(-TWOPOWER31)-1 );
24486   testcase( r==(-TWOPOWER31) );
24487   testcase( r==TWOPOWER31 );
24488   testcase( r==TWOPOWER31-1 );
24489   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
24490   r *= TWOPOWER32;
24491   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
24492   *pA = r;
24493   return 0;
24494 }
24495
24496 /*
24497 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
24498 ** if the integer has a value of -2147483648, return +2147483647
24499 */
24500 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
24501   if( x>=0 ) return x;
24502   if( x==(int)0x80000000 ) return 0x7fffffff;
24503   return -x;
24504 }
24505
24506 #ifdef SQLITE_ENABLE_8_3_NAMES
24507 /*
24508 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
24509 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
24510 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
24511 ** three characters, then shorten the suffix on z[] to be the last three
24512 ** characters of the original suffix.
24513 **
24514 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
24515 ** do the suffix shortening regardless of URI parameter.
24516 **
24517 ** Examples:
24518 **
24519 **     test.db-journal    =>   test.nal
24520 **     test.db-wal        =>   test.wal
24521 **     test.db-shm        =>   test.shm
24522 **     test.db-mj7f3319fa =>   test.9fa
24523 */
24524 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
24525 #if SQLITE_ENABLE_8_3_NAMES<2
24526   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
24527 #endif
24528   {
24529     int i, sz;
24530     sz = sqlite3Strlen30(z);
24531     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
24532     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
24533   }
24534 }
24535 #endif
24536
24537 /************** End of util.c ************************************************/
24538 /************** Begin file hash.c ********************************************/
24539 /*
24540 ** 2001 September 22
24541 **
24542 ** The author disclaims copyright to this source code.  In place of
24543 ** a legal notice, here is a blessing:
24544 **
24545 **    May you do good and not evil.
24546 **    May you find forgiveness for yourself and forgive others.
24547 **    May you share freely, never taking more than you give.
24548 **
24549 *************************************************************************
24550 ** This is the implementation of generic hash-tables
24551 ** used in SQLite.
24552 */
24553 /* #include <assert.h> */
24554
24555 /* Turn bulk memory into a hash table object by initializing the
24556 ** fields of the Hash structure.
24557 **
24558 ** "pNew" is a pointer to the hash table that is to be initialized.
24559 */
24560 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
24561   assert( pNew!=0 );
24562   pNew->first = 0;
24563   pNew->count = 0;
24564   pNew->htsize = 0;
24565   pNew->ht = 0;
24566 }
24567
24568 /* Remove all entries from a hash table.  Reclaim all memory.
24569 ** Call this routine to delete a hash table or to reset a hash table
24570 ** to the empty state.
24571 */
24572 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
24573   HashElem *elem;         /* For looping over all elements of the table */
24574
24575   assert( pH!=0 );
24576   elem = pH->first;
24577   pH->first = 0;
24578   sqlite3_free(pH->ht);
24579   pH->ht = 0;
24580   pH->htsize = 0;
24581   while( elem ){
24582     HashElem *next_elem = elem->next;
24583     sqlite3_free(elem);
24584     elem = next_elem;
24585   }
24586   pH->count = 0;
24587 }
24588
24589 /*
24590 ** The hashing function.
24591 */
24592 static unsigned int strHash(const char *z, int nKey){
24593   int h = 0;
24594   assert( nKey>=0 );
24595   while( nKey > 0  ){
24596     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
24597     nKey--;
24598   }
24599   return h;
24600 }
24601
24602
24603 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
24604 ** insert pNew into the pEntry hash bucket.
24605 */
24606 static void insertElement(
24607   Hash *pH,              /* The complete hash table */
24608   struct _ht *pEntry,    /* The entry into which pNew is inserted */
24609   HashElem *pNew         /* The element to be inserted */
24610 ){
24611   HashElem *pHead;       /* First element already in pEntry */
24612   if( pEntry ){
24613     pHead = pEntry->count ? pEntry->chain : 0;
24614     pEntry->count++;
24615     pEntry->chain = pNew;
24616   }else{
24617     pHead = 0;
24618   }
24619   if( pHead ){
24620     pNew->next = pHead;
24621     pNew->prev = pHead->prev;
24622     if( pHead->prev ){ pHead->prev->next = pNew; }
24623     else             { pH->first = pNew; }
24624     pHead->prev = pNew;
24625   }else{
24626     pNew->next = pH->first;
24627     if( pH->first ){ pH->first->prev = pNew; }
24628     pNew->prev = 0;
24629     pH->first = pNew;
24630   }
24631 }
24632
24633
24634 /* Resize the hash table so that it cantains "new_size" buckets.
24635 **
24636 ** The hash table might fail to resize if sqlite3_malloc() fails or
24637 ** if the new size is the same as the prior size.
24638 ** Return TRUE if the resize occurs and false if not.
24639 */
24640 static int rehash(Hash *pH, unsigned int new_size){
24641   struct _ht *new_ht;            /* The new hash table */
24642   HashElem *elem, *next_elem;    /* For looping over existing elements */
24643
24644 #if SQLITE_MALLOC_SOFT_LIMIT>0
24645   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
24646     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
24647   }
24648   if( new_size==pH->htsize ) return 0;
24649 #endif
24650
24651   /* The inability to allocates space for a larger hash table is
24652   ** a performance hit but it is not a fatal error.  So mark the
24653   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
24654   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
24655   ** only zeroes the requested number of bytes whereas this module will
24656   ** use the actual amount of space allocated for the hash table (which
24657   ** may be larger than the requested amount).
24658   */
24659   sqlite3BeginBenignMalloc();
24660   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
24661   sqlite3EndBenignMalloc();
24662
24663   if( new_ht==0 ) return 0;
24664   sqlite3_free(pH->ht);
24665   pH->ht = new_ht;
24666   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
24667   memset(new_ht, 0, new_size*sizeof(struct _ht));
24668   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
24669     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
24670     next_elem = elem->next;
24671     insertElement(pH, &new_ht[h], elem);
24672   }
24673   return 1;
24674 }
24675
24676 /* This function (for internal use only) locates an element in an
24677 ** hash table that matches the given key.  The hash for this key has
24678 ** already been computed and is passed as the 4th parameter.
24679 */
24680 static HashElem *findElementGivenHash(
24681   const Hash *pH,     /* The pH to be searched */
24682   const char *pKey,   /* The key we are searching for */
24683   int nKey,           /* Bytes in key (not counting zero terminator) */
24684   unsigned int h      /* The hash for this key. */
24685 ){
24686   HashElem *elem;                /* Used to loop thru the element list */
24687   int count;                     /* Number of elements left to test */
24688
24689   if( pH->ht ){
24690     struct _ht *pEntry = &pH->ht[h];
24691     elem = pEntry->chain;
24692     count = pEntry->count;
24693   }else{
24694     elem = pH->first;
24695     count = pH->count;
24696   }
24697   while( count-- && ALWAYS(elem) ){
24698     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
24699       return elem;
24700     }
24701     elem = elem->next;
24702   }
24703   return 0;
24704 }
24705
24706 /* Remove a single entry from the hash table given a pointer to that
24707 ** element and a hash on the element's key.
24708 */
24709 static void removeElementGivenHash(
24710   Hash *pH,         /* The pH containing "elem" */
24711   HashElem* elem,   /* The element to be removed from the pH */
24712   unsigned int h    /* Hash value for the element */
24713 ){
24714   struct _ht *pEntry;
24715   if( elem->prev ){
24716     elem->prev->next = elem->next;
24717   }else{
24718     pH->first = elem->next;
24719   }
24720   if( elem->next ){
24721     elem->next->prev = elem->prev;
24722   }
24723   if( pH->ht ){
24724     pEntry = &pH->ht[h];
24725     if( pEntry->chain==elem ){
24726       pEntry->chain = elem->next;
24727     }
24728     pEntry->count--;
24729     assert( pEntry->count>=0 );
24730   }
24731   sqlite3_free( elem );
24732   pH->count--;
24733   if( pH->count==0 ){
24734     assert( pH->first==0 );
24735     assert( pH->count==0 );
24736     sqlite3HashClear(pH);
24737   }
24738 }
24739
24740 /* Attempt to locate an element of the hash table pH with a key
24741 ** that matches pKey,nKey.  Return the data for this element if it is
24742 ** found, or NULL if there is no match.
24743 */
24744 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
24745   HashElem *elem;    /* The element that matches key */
24746   unsigned int h;    /* A hash on key */
24747
24748   assert( pH!=0 );
24749   assert( pKey!=0 );
24750   assert( nKey>=0 );
24751   if( pH->ht ){
24752     h = strHash(pKey, nKey) % pH->htsize;
24753   }else{
24754     h = 0;
24755   }
24756   elem = findElementGivenHash(pH, pKey, nKey, h);
24757   return elem ? elem->data : 0;
24758 }
24759
24760 /* Insert an element into the hash table pH.  The key is pKey,nKey
24761 ** and the data is "data".
24762 **
24763 ** If no element exists with a matching key, then a new
24764 ** element is created and NULL is returned.
24765 **
24766 ** If another element already exists with the same key, then the
24767 ** new data replaces the old data and the old data is returned.
24768 ** The key is not copied in this instance.  If a malloc fails, then
24769 ** the new data is returned and the hash table is unchanged.
24770 **
24771 ** If the "data" parameter to this function is NULL, then the
24772 ** element corresponding to "key" is removed from the hash table.
24773 */
24774 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
24775   unsigned int h;       /* the hash of the key modulo hash table size */
24776   HashElem *elem;       /* Used to loop thru the element list */
24777   HashElem *new_elem;   /* New element added to the pH */
24778
24779   assert( pH!=0 );
24780   assert( pKey!=0 );
24781   assert( nKey>=0 );
24782   if( pH->htsize ){
24783     h = strHash(pKey, nKey) % pH->htsize;
24784   }else{
24785     h = 0;
24786   }
24787   elem = findElementGivenHash(pH,pKey,nKey,h);
24788   if( elem ){
24789     void *old_data = elem->data;
24790     if( data==0 ){
24791       removeElementGivenHash(pH,elem,h);
24792     }else{
24793       elem->data = data;
24794       elem->pKey = pKey;
24795       assert(nKey==elem->nKey);
24796     }
24797     return old_data;
24798   }
24799   if( data==0 ) return 0;
24800   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
24801   if( new_elem==0 ) return data;
24802   new_elem->pKey = pKey;
24803   new_elem->nKey = nKey;
24804   new_elem->data = data;
24805   pH->count++;
24806   if( pH->count>=10 && pH->count > 2*pH->htsize ){
24807     if( rehash(pH, pH->count*2) ){
24808       assert( pH->htsize>0 );
24809       h = strHash(pKey, nKey) % pH->htsize;
24810     }
24811   }
24812   if( pH->ht ){
24813     insertElement(pH, &pH->ht[h], new_elem);
24814   }else{
24815     insertElement(pH, 0, new_elem);
24816   }
24817   return 0;
24818 }
24819
24820 /************** End of hash.c ************************************************/
24821 /************** Begin file opcodes.c *****************************************/
24822 /* Automatically generated.  Do not edit */
24823 /* See the mkopcodec.awk script for details. */
24824 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
24825 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
24826  static const char *const azName[] = { "?",
24827      /*   1 */ "Goto",
24828      /*   2 */ "Gosub",
24829      /*   3 */ "Return",
24830      /*   4 */ "Yield",
24831      /*   5 */ "HaltIfNull",
24832      /*   6 */ "Halt",
24833      /*   7 */ "Integer",
24834      /*   8 */ "Int64",
24835      /*   9 */ "String",
24836      /*  10 */ "Null",
24837      /*  11 */ "Blob",
24838      /*  12 */ "Variable",
24839      /*  13 */ "Move",
24840      /*  14 */ "Copy",
24841      /*  15 */ "SCopy",
24842      /*  16 */ "ResultRow",
24843      /*  17 */ "CollSeq",
24844      /*  18 */ "Function",
24845      /*  19 */ "Not",
24846      /*  20 */ "AddImm",
24847      /*  21 */ "MustBeInt",
24848      /*  22 */ "RealAffinity",
24849      /*  23 */ "Permutation",
24850      /*  24 */ "Compare",
24851      /*  25 */ "Jump",
24852      /*  26 */ "Once",
24853      /*  27 */ "If",
24854      /*  28 */ "IfNot",
24855      /*  29 */ "Column",
24856      /*  30 */ "Affinity",
24857      /*  31 */ "MakeRecord",
24858      /*  32 */ "Count",
24859      /*  33 */ "Savepoint",
24860      /*  34 */ "AutoCommit",
24861      /*  35 */ "Transaction",
24862      /*  36 */ "ReadCookie",
24863      /*  37 */ "SetCookie",
24864      /*  38 */ "VerifyCookie",
24865      /*  39 */ "OpenRead",
24866      /*  40 */ "OpenWrite",
24867      /*  41 */ "OpenAutoindex",
24868      /*  42 */ "OpenEphemeral",
24869      /*  43 */ "SorterOpen",
24870      /*  44 */ "OpenPseudo",
24871      /*  45 */ "Close",
24872      /*  46 */ "SeekLt",
24873      /*  47 */ "SeekLe",
24874      /*  48 */ "SeekGe",
24875      /*  49 */ "SeekGt",
24876      /*  50 */ "Seek",
24877      /*  51 */ "NotFound",
24878      /*  52 */ "Found",
24879      /*  53 */ "IsUnique",
24880      /*  54 */ "NotExists",
24881      /*  55 */ "Sequence",
24882      /*  56 */ "NewRowid",
24883      /*  57 */ "Insert",
24884      /*  58 */ "InsertInt",
24885      /*  59 */ "Delete",
24886      /*  60 */ "ResetCount",
24887      /*  61 */ "SorterCompare",
24888      /*  62 */ "SorterData",
24889      /*  63 */ "RowKey",
24890      /*  64 */ "RowData",
24891      /*  65 */ "Rowid",
24892      /*  66 */ "NullRow",
24893      /*  67 */ "Last",
24894      /*  68 */ "Or",
24895      /*  69 */ "And",
24896      /*  70 */ "SorterSort",
24897      /*  71 */ "Sort",
24898      /*  72 */ "Rewind",
24899      /*  73 */ "IsNull",
24900      /*  74 */ "NotNull",
24901      /*  75 */ "Ne",
24902      /*  76 */ "Eq",
24903      /*  77 */ "Gt",
24904      /*  78 */ "Le",
24905      /*  79 */ "Lt",
24906      /*  80 */ "Ge",
24907      /*  81 */ "SorterNext",
24908      /*  82 */ "BitAnd",
24909      /*  83 */ "BitOr",
24910      /*  84 */ "ShiftLeft",
24911      /*  85 */ "ShiftRight",
24912      /*  86 */ "Add",
24913      /*  87 */ "Subtract",
24914      /*  88 */ "Multiply",
24915      /*  89 */ "Divide",
24916      /*  90 */ "Remainder",
24917      /*  91 */ "Concat",
24918      /*  92 */ "Prev",
24919      /*  93 */ "BitNot",
24920      /*  94 */ "String8",
24921      /*  95 */ "Next",
24922      /*  96 */ "SorterInsert",
24923      /*  97 */ "IdxInsert",
24924      /*  98 */ "IdxDelete",
24925      /*  99 */ "IdxRowid",
24926      /* 100 */ "IdxLT",
24927      /* 101 */ "IdxGE",
24928      /* 102 */ "Destroy",
24929      /* 103 */ "Clear",
24930      /* 104 */ "CreateIndex",
24931      /* 105 */ "CreateTable",
24932      /* 106 */ "ParseSchema",
24933      /* 107 */ "LoadAnalysis",
24934      /* 108 */ "DropTable",
24935      /* 109 */ "DropIndex",
24936      /* 110 */ "DropTrigger",
24937      /* 111 */ "IntegrityCk",
24938      /* 112 */ "RowSetAdd",
24939      /* 113 */ "RowSetRead",
24940      /* 114 */ "RowSetTest",
24941      /* 115 */ "Program",
24942      /* 116 */ "Param",
24943      /* 117 */ "FkCounter",
24944      /* 118 */ "FkIfZero",
24945      /* 119 */ "MemMax",
24946      /* 120 */ "IfPos",
24947      /* 121 */ "IfNeg",
24948      /* 122 */ "IfZero",
24949      /* 123 */ "AggStep",
24950      /* 124 */ "AggFinal",
24951      /* 125 */ "Checkpoint",
24952      /* 126 */ "JournalMode",
24953      /* 127 */ "Vacuum",
24954      /* 128 */ "IncrVacuum",
24955      /* 129 */ "Expire",
24956      /* 130 */ "Real",
24957      /* 131 */ "TableLock",
24958      /* 132 */ "VBegin",
24959      /* 133 */ "VCreate",
24960      /* 134 */ "VDestroy",
24961      /* 135 */ "VOpen",
24962      /* 136 */ "VFilter",
24963      /* 137 */ "VColumn",
24964      /* 138 */ "VNext",
24965      /* 139 */ "VRename",
24966      /* 140 */ "VUpdate",
24967      /* 141 */ "ToText",
24968      /* 142 */ "ToBlob",
24969      /* 143 */ "ToNumeric",
24970      /* 144 */ "ToInt",
24971      /* 145 */ "ToReal",
24972      /* 146 */ "Pagecount",
24973      /* 147 */ "MaxPgcnt",
24974      /* 148 */ "Trace",
24975      /* 149 */ "Noop",
24976      /* 150 */ "Explain",
24977   };
24978   return azName[i];
24979 }
24980 #endif
24981
24982 /************** End of opcodes.c *********************************************/
24983 /************** Begin file os_unix.c *****************************************/
24984 /*
24985 ** 2004 May 22
24986 **
24987 ** The author disclaims copyright to this source code.  In place of
24988 ** a legal notice, here is a blessing:
24989 **
24990 **    May you do good and not evil.
24991 **    May you find forgiveness for yourself and forgive others.
24992 **    May you share freely, never taking more than you give.
24993 **
24994 ******************************************************************************
24995 **
24996 ** This file contains the VFS implementation for unix-like operating systems
24997 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24998 **
24999 ** There are actually several different VFS implementations in this file.
25000 ** The differences are in the way that file locking is done.  The default
25001 ** implementation uses Posix Advisory Locks.  Alternative implementations
25002 ** use flock(), dot-files, various proprietary locking schemas, or simply
25003 ** skip locking all together.
25004 **
25005 ** This source file is organized into divisions where the logic for various
25006 ** subfunctions is contained within the appropriate division.  PLEASE
25007 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
25008 ** in the correct division and should be clearly labeled.
25009 **
25010 ** The layout of divisions is as follows:
25011 **
25012 **   *  General-purpose declarations and utility functions.
25013 **   *  Unique file ID logic used by VxWorks.
25014 **   *  Various locking primitive implementations (all except proxy locking):
25015 **      + for Posix Advisory Locks
25016 **      + for no-op locks
25017 **      + for dot-file locks
25018 **      + for flock() locking
25019 **      + for named semaphore locks (VxWorks only)
25020 **      + for AFP filesystem locks (MacOSX only)
25021 **   *  sqlite3_file methods not associated with locking.
25022 **   *  Definitions of sqlite3_io_methods objects for all locking
25023 **      methods plus "finder" functions for each locking method.
25024 **   *  sqlite3_vfs method implementations.
25025 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
25026 **   *  Definitions of sqlite3_vfs objects for all locking methods
25027 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
25028 */
25029 #if SQLITE_OS_UNIX              /* This file is used on unix only */
25030
25031 /* Use posix_fallocate() if it is available
25032 */
25033 #if !defined(HAVE_POSIX_FALLOCATE) \
25034       && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
25035 # define HAVE_POSIX_FALLOCATE 1
25036 #endif
25037
25038 /*
25039 ** There are various methods for file locking used for concurrency
25040 ** control:
25041 **
25042 **   1. POSIX locking (the default),
25043 **   2. No locking,
25044 **   3. Dot-file locking,
25045 **   4. flock() locking,
25046 **   5. AFP locking (OSX only),
25047 **   6. Named POSIX semaphores (VXWorks only),
25048 **   7. proxy locking. (OSX only)
25049 **
25050 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
25051 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
25052 ** selection of the appropriate locking style based on the filesystem
25053 ** where the database is located.
25054 */
25055 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
25056 #  if defined(__APPLE__)
25057 #    define SQLITE_ENABLE_LOCKING_STYLE 1
25058 #  else
25059 #    define SQLITE_ENABLE_LOCKING_STYLE 0
25060 #  endif
25061 #endif
25062
25063 /*
25064 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
25065 ** vxworks, or 0 otherwise.
25066 */
25067 #ifndef OS_VXWORKS
25068 #  if defined(__RTP__) || defined(_WRS_KERNEL)
25069 #    define OS_VXWORKS 1
25070 #  else
25071 #    define OS_VXWORKS 0
25072 #  endif
25073 #endif
25074
25075 /*
25076 ** These #defines should enable >2GB file support on Posix if the
25077 ** underlying operating system supports it.  If the OS lacks
25078 ** large file support, these should be no-ops.
25079 **
25080 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
25081 ** on the compiler command line.  This is necessary if you are compiling
25082 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
25083 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
25084 ** without this option, LFS is enable.  But LFS does not exist in the kernel
25085 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
25086 ** portability you should omit LFS.
25087 **
25088 ** The previous paragraph was written in 2005.  (This paragraph is written
25089 ** on 2008-11-28.) These days, all Linux kernels support large files, so
25090 ** you should probably leave LFS enabled.  But some embedded platforms might
25091 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
25092 */
25093 #ifndef SQLITE_DISABLE_LFS
25094 # define _LARGE_FILE       1
25095 # ifndef _FILE_OFFSET_BITS
25096 #   define _FILE_OFFSET_BITS 64
25097 # endif
25098 # define _LARGEFILE_SOURCE 1
25099 #endif
25100
25101 /*
25102 ** standard include files.
25103 */
25104 #include <sys/types.h>
25105 #include <sys/stat.h>
25106 #include <fcntl.h>
25107 #include <unistd.h>
25108 /* #include <time.h> */
25109 #include <sys/time.h>
25110 #include <errno.h>
25111 #ifndef SQLITE_OMIT_WAL
25112 /* #include <sys/mman.h> */
25113 #endif
25114
25115
25116 #if SQLITE_ENABLE_LOCKING_STYLE
25117 # include <sys/ioctl.h>
25118 # if OS_VXWORKS
25119 #  include <semaphore.h>
25120 #  include <limits.h>
25121 # else
25122 #  include <sys/file.h>
25123 #  include <sys/param.h>
25124 # endif
25125 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
25126
25127 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
25128 # include <sys/mount.h>
25129 #endif
25130
25131 #ifdef HAVE_UTIME
25132 # include <utime.h>
25133 #endif
25134
25135 /*
25136 ** Allowed values of unixFile.fsFlags
25137 */
25138 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
25139
25140 /*
25141 ** If we are to be thread-safe, include the pthreads header and define
25142 ** the SQLITE_UNIX_THREADS macro.
25143 */
25144 #if SQLITE_THREADSAFE
25145 /* # include <pthread.h> */
25146 # define SQLITE_UNIX_THREADS 1
25147 #endif
25148
25149 /*
25150 ** Default permissions when creating a new file
25151 */
25152 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
25153 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
25154 #endif
25155
25156 /*
25157 ** Default permissions when creating auto proxy dir
25158 */
25159 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
25160 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
25161 #endif
25162
25163 /*
25164 ** Maximum supported path-length.
25165 */
25166 #define MAX_PATHNAME 512
25167
25168 /*
25169 ** Only set the lastErrno if the error code is a real error and not
25170 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
25171 */
25172 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
25173
25174 /* Forward references */
25175 typedef struct unixShm unixShm;               /* Connection shared memory */
25176 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
25177 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
25178 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
25179
25180 /*
25181 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
25182 ** cannot be closed immediately. In these cases, instances of the following
25183 ** structure are used to store the file descriptor while waiting for an
25184 ** opportunity to either close or reuse it.
25185 */
25186 struct UnixUnusedFd {
25187   int fd;                   /* File descriptor to close */
25188   int flags;                /* Flags this file descriptor was opened with */
25189   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
25190 };
25191
25192 /*
25193 ** The unixFile structure is subclass of sqlite3_file specific to the unix
25194 ** VFS implementations.
25195 */
25196 typedef struct unixFile unixFile;
25197 struct unixFile {
25198   sqlite3_io_methods const *pMethod;  /* Always the first entry */
25199   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
25200   unixInodeInfo *pInode;              /* Info about locks on this inode */
25201   int h;                              /* The file descriptor */
25202   unsigned char eFileLock;            /* The type of lock held on this fd */
25203   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
25204   int lastErrno;                      /* The unix errno from last I/O error */
25205   void *lockingContext;               /* Locking style specific state */
25206   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
25207   const char *zPath;                  /* Name of the file */
25208   unixShm *pShm;                      /* Shared memory segment information */
25209   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
25210 #ifdef __QNXNTO__
25211   int sectorSize;                     /* Device sector size */
25212   int deviceCharacteristics;          /* Precomputed device characteristics */
25213 #endif
25214 #if SQLITE_ENABLE_LOCKING_STYLE
25215   int openFlags;                      /* The flags specified at open() */
25216 #endif
25217 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
25218   unsigned fsFlags;                   /* cached details from statfs() */
25219 #endif
25220 #if OS_VXWORKS
25221   struct vxworksFileId *pId;          /* Unique file ID */
25222 #endif
25223 #ifdef SQLITE_DEBUG
25224   /* The next group of variables are used to track whether or not the
25225   ** transaction counter in bytes 24-27 of database files are updated
25226   ** whenever any part of the database changes.  An assertion fault will
25227   ** occur if a file is updated without also updating the transaction
25228   ** counter.  This test is made to avoid new problems similar to the
25229   ** one described by ticket #3584.
25230   */
25231   unsigned char transCntrChng;   /* True if the transaction counter changed */
25232   unsigned char dbUpdate;        /* True if any part of database file changed */
25233   unsigned char inNormalWrite;   /* True if in a normal write operation */
25234 #endif
25235 #ifdef SQLITE_TEST
25236   /* In test mode, increase the size of this structure a bit so that
25237   ** it is larger than the struct CrashFile defined in test6.c.
25238   */
25239   char aPadding[32];
25240 #endif
25241 };
25242
25243 /*
25244 ** Allowed values for the unixFile.ctrlFlags bitmask:
25245 */
25246 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
25247 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
25248 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
25249 #ifndef SQLITE_DISABLE_DIRSYNC
25250 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
25251 #else
25252 # define UNIXFILE_DIRSYNC    0x00
25253 #endif
25254 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
25255 #define UNIXFILE_DELETE      0x20     /* Delete on close */
25256 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
25257 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
25258
25259 /*
25260 ** Include code that is common to all os_*.c files
25261 */
25262 /************** Include os_common.h in the middle of os_unix.c ***************/
25263 /************** Begin file os_common.h ***************************************/
25264 /*
25265 ** 2004 May 22
25266 **
25267 ** The author disclaims copyright to this source code.  In place of
25268 ** a legal notice, here is a blessing:
25269 **
25270 **    May you do good and not evil.
25271 **    May you find forgiveness for yourself and forgive others.
25272 **    May you share freely, never taking more than you give.
25273 **
25274 ******************************************************************************
25275 **
25276 ** This file contains macros and a little bit of code that is common to
25277 ** all of the platform-specific files (os_*.c) and is #included into those
25278 ** files.
25279 **
25280 ** This file should be #included by the os_*.c files only.  It is not a
25281 ** general purpose header file.
25282 */
25283 #ifndef _OS_COMMON_H_
25284 #define _OS_COMMON_H_
25285
25286 /*
25287 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
25288 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
25289 ** switch.  The following code should catch this problem at compile-time.
25290 */
25291 #ifdef MEMORY_DEBUG
25292 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
25293 #endif
25294
25295 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25296 # ifndef SQLITE_DEBUG_OS_TRACE
25297 #   define SQLITE_DEBUG_OS_TRACE 0
25298 # endif
25299   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
25300 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
25301 #else
25302 # define OSTRACE(X)
25303 #endif
25304
25305 /*
25306 ** Macros for performance tracing.  Normally turned off.  Only works
25307 ** on i486 hardware.
25308 */
25309 #ifdef SQLITE_PERFORMANCE_TRACE
25310
25311 /*
25312 ** hwtime.h contains inline assembler code for implementing
25313 ** high-performance timing routines.
25314 */
25315 /************** Include hwtime.h in the middle of os_common.h ****************/
25316 /************** Begin file hwtime.h ******************************************/
25317 /*
25318 ** 2008 May 27
25319 **
25320 ** The author disclaims copyright to this source code.  In place of
25321 ** a legal notice, here is a blessing:
25322 **
25323 **    May you do good and not evil.
25324 **    May you find forgiveness for yourself and forgive others.
25325 **    May you share freely, never taking more than you give.
25326 **
25327 ******************************************************************************
25328 **
25329 ** This file contains inline asm code for retrieving "high-performance"
25330 ** counters for x86 class CPUs.
25331 */
25332 #ifndef _HWTIME_H_
25333 #define _HWTIME_H_
25334
25335 /*
25336 ** The following routine only works on pentium-class (or newer) processors.
25337 ** It uses the RDTSC opcode to read the cycle count value out of the
25338 ** processor and returns that value.  This can be used for high-res
25339 ** profiling.
25340 */
25341 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
25342       (defined(i386) || defined(__i386__) || defined(_M_IX86))
25343
25344   #if defined(__GNUC__)
25345
25346   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25347      unsigned int lo, hi;
25348      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25349      return (sqlite_uint64)hi << 32 | lo;
25350   }
25351
25352   #elif defined(_MSC_VER)
25353
25354   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25355      __asm {
25356         rdtsc
25357         ret       ; return value at EDX:EAX
25358      }
25359   }
25360
25361   #endif
25362
25363 #elif (defined(__GNUC__) && defined(__x86_64__))
25364
25365   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25366       unsigned long val;
25367       __asm__ __volatile__ ("rdtsc" : "=A" (val));
25368       return val;
25369   }
25370
25371 #elif (defined(__GNUC__) && defined(__ppc__))
25372
25373   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25374       unsigned long long retval;
25375       unsigned long junk;
25376       __asm__ __volatile__ ("\n\
25377           1:      mftbu   %1\n\
25378                   mftb    %L0\n\
25379                   mftbu   %0\n\
25380                   cmpw    %0,%1\n\
25381                   bne     1b"
25382                   : "=r" (retval), "=r" (junk));
25383       return retval;
25384   }
25385
25386 #else
25387
25388   #error Need implementation of sqlite3Hwtime() for your platform.
25389
25390   /*
25391   ** To compile without implementing sqlite3Hwtime() for your platform,
25392   ** you can remove the above #error and use the following
25393   ** stub function.  You will lose timing support for many
25394   ** of the debugging and testing utilities, but it should at
25395   ** least compile and run.
25396   */
25397 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25398
25399 #endif
25400
25401 #endif /* !defined(_HWTIME_H_) */
25402
25403 /************** End of hwtime.h **********************************************/
25404 /************** Continuing where we left off in os_common.h ******************/
25405
25406 static sqlite_uint64 g_start;
25407 static sqlite_uint64 g_elapsed;
25408 #define TIMER_START       g_start=sqlite3Hwtime()
25409 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25410 #define TIMER_ELAPSED     g_elapsed
25411 #else
25412 #define TIMER_START
25413 #define TIMER_END
25414 #define TIMER_ELAPSED     ((sqlite_uint64)0)
25415 #endif
25416
25417 /*
25418 ** If we compile with the SQLITE_TEST macro set, then the following block
25419 ** of code will give us the ability to simulate a disk I/O error.  This
25420 ** is used for testing the I/O recovery logic.
25421 */
25422 #ifdef SQLITE_TEST
25423 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25424 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25425 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25426 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25427 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25428 SQLITE_API int sqlite3_diskfull_pending = 0;
25429 SQLITE_API int sqlite3_diskfull = 0;
25430 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25431 #define SimulateIOError(CODE)  \
25432   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25433        || sqlite3_io_error_pending-- == 1 )  \
25434               { local_ioerr(); CODE; }
25435 static void local_ioerr(){
25436   IOTRACE(("IOERR\n"));
25437   sqlite3_io_error_hit++;
25438   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25439 }
25440 #define SimulateDiskfullError(CODE) \
25441    if( sqlite3_diskfull_pending ){ \
25442      if( sqlite3_diskfull_pending == 1 ){ \
25443        local_ioerr(); \
25444        sqlite3_diskfull = 1; \
25445        sqlite3_io_error_hit = 1; \
25446        CODE; \
25447      }else{ \
25448        sqlite3_diskfull_pending--; \
25449      } \
25450    }
25451 #else
25452 #define SimulateIOErrorBenign(X)
25453 #define SimulateIOError(A)
25454 #define SimulateDiskfullError(A)
25455 #endif
25456
25457 /*
25458 ** When testing, keep a count of the number of open files.
25459 */
25460 #ifdef SQLITE_TEST
25461 SQLITE_API int sqlite3_open_file_count = 0;
25462 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
25463 #else
25464 #define OpenCounter(X)
25465 #endif
25466
25467 #endif /* !defined(_OS_COMMON_H_) */
25468
25469 /************** End of os_common.h *******************************************/
25470 /************** Continuing where we left off in os_unix.c ********************/
25471
25472 /*
25473 ** Define various macros that are missing from some systems.
25474 */
25475 #ifndef O_LARGEFILE
25476 # define O_LARGEFILE 0
25477 #endif
25478 #ifdef SQLITE_DISABLE_LFS
25479 # undef O_LARGEFILE
25480 # define O_LARGEFILE 0
25481 #endif
25482 #ifndef O_NOFOLLOW
25483 # define O_NOFOLLOW 0
25484 #endif
25485 #ifndef O_BINARY
25486 # define O_BINARY 0
25487 #endif
25488
25489 /*
25490 ** The threadid macro resolves to the thread-id or to 0.  Used for
25491 ** testing and debugging only.
25492 */
25493 #if SQLITE_THREADSAFE
25494 #define threadid pthread_self()
25495 #else
25496 #define threadid 0
25497 #endif
25498
25499 /*
25500 ** Different Unix systems declare open() in different ways.  Same use
25501 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
25502 ** The difference is important when using a pointer to the function.
25503 **
25504 ** The safest way to deal with the problem is to always use this wrapper
25505 ** which always has the same well-defined interface.
25506 */
25507 static int posixOpen(const char *zFile, int flags, int mode){
25508   return open(zFile, flags, mode);
25509 }
25510
25511 /*
25512 ** On some systems, calls to fchown() will trigger a message in a security
25513 ** log if they come from non-root processes.  So avoid calling fchown() if
25514 ** we are not running as root.
25515 */
25516 static int posixFchown(int fd, uid_t uid, gid_t gid){
25517   return geteuid() ? 0 : fchown(fd,uid,gid);
25518 }
25519
25520 /* Forward reference */
25521 static int openDirectory(const char*, int*);
25522
25523 /*
25524 ** Many system calls are accessed through pointer-to-functions so that
25525 ** they may be overridden at runtime to facilitate fault injection during
25526 ** testing and sandboxing.  The following array holds the names and pointers
25527 ** to all overrideable system calls.
25528 */
25529 static struct unix_syscall {
25530   const char *zName;            /* Name of the sytem call */
25531   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25532   sqlite3_syscall_ptr pDefault; /* Default value */
25533 } aSyscall[] = {
25534   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
25535 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25536
25537   { "close",        (sqlite3_syscall_ptr)close,      0  },
25538 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
25539
25540   { "access",       (sqlite3_syscall_ptr)access,     0  },
25541 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
25542
25543   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
25544 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25545
25546   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
25547 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25548
25549 /*
25550 ** The DJGPP compiler environment looks mostly like Unix, but it
25551 ** lacks the fcntl() system call.  So redefine fcntl() to be something
25552 ** that always succeeds.  This means that locking does not occur under
25553 ** DJGPP.  But it is DOS - what did you expect?
25554 */
25555 #ifdef __DJGPP__
25556   { "fstat",        0,                 0  },
25557 #define osFstat(a,b,c)    0
25558 #else
25559   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
25560 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25561 #endif
25562
25563   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
25564 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25565
25566   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
25567 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
25568
25569   { "read",         (sqlite3_syscall_ptr)read,       0  },
25570 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25571
25572 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25573   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
25574 #else
25575   { "pread",        (sqlite3_syscall_ptr)0,          0  },
25576 #endif
25577 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25578
25579 #if defined(USE_PREAD64)
25580   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
25581 #else
25582   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
25583 #endif
25584 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25585
25586   { "write",        (sqlite3_syscall_ptr)write,      0  },
25587 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25588
25589 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25590   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
25591 #else
25592   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
25593 #endif
25594 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
25595                     aSyscall[12].pCurrent)
25596
25597 #if defined(USE_PREAD64)
25598   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
25599 #else
25600   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
25601 #endif
25602 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
25603                     aSyscall[13].pCurrent)
25604
25605 #if SQLITE_ENABLE_LOCKING_STYLE
25606   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
25607 #else
25608   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
25609 #endif
25610 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25611
25612 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25613   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
25614 #else
25615   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
25616 #endif
25617 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25618
25619   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
25620 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
25621
25622   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
25623 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25624
25625   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
25626 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25627
25628   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
25629 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
25630
25631   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
25632 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25633
25634   { "umask",        (sqlite3_syscall_ptr)umask,           0 },
25635 #define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
25636
25637 }; /* End of the overrideable system calls */
25638
25639 /*
25640 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25641 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
25642 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25643 ** system call named zName.
25644 */
25645 static int unixSetSystemCall(
25646   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
25647   const char *zName,            /* Name of system call to override */
25648   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
25649 ){
25650   unsigned int i;
25651   int rc = SQLITE_NOTFOUND;
25652
25653   UNUSED_PARAMETER(pNotUsed);
25654   if( zName==0 ){
25655     /* If no zName is given, restore all system calls to their default
25656     ** settings and return NULL
25657     */
25658     rc = SQLITE_OK;
25659     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25660       if( aSyscall[i].pDefault ){
25661         aSyscall[i].pCurrent = aSyscall[i].pDefault;
25662       }
25663     }
25664   }else{
25665     /* If zName is specified, operate on only the one system call
25666     ** specified.
25667     */
25668     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25669       if( strcmp(zName, aSyscall[i].zName)==0 ){
25670         if( aSyscall[i].pDefault==0 ){
25671           aSyscall[i].pDefault = aSyscall[i].pCurrent;
25672         }
25673         rc = SQLITE_OK;
25674         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25675         aSyscall[i].pCurrent = pNewFunc;
25676         break;
25677       }
25678     }
25679   }
25680   return rc;
25681 }
25682
25683 /*
25684 ** Return the value of a system call.  Return NULL if zName is not a
25685 ** recognized system call name.  NULL is also returned if the system call
25686 ** is currently undefined.
25687 */
25688 static sqlite3_syscall_ptr unixGetSystemCall(
25689   sqlite3_vfs *pNotUsed,
25690   const char *zName
25691 ){
25692   unsigned int i;
25693
25694   UNUSED_PARAMETER(pNotUsed);
25695   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25696     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25697   }
25698   return 0;
25699 }
25700
25701 /*
25702 ** Return the name of the first system call after zName.  If zName==NULL
25703 ** then return the name of the first system call.  Return NULL if zName
25704 ** is the last system call or if zName is not the name of a valid
25705 ** system call.
25706 */
25707 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25708   int i = -1;
25709
25710   UNUSED_PARAMETER(p);
25711   if( zName ){
25712     for(i=0; i<ArraySize(aSyscall)-1; i++){
25713       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25714     }
25715   }
25716   for(i++; i<ArraySize(aSyscall); i++){
25717     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25718   }
25719   return 0;
25720 }
25721
25722 /*
25723 ** Invoke open().  Do so multiple times, until it either succeeds or
25724 ** fails for some reason other than EINTR.
25725 **
25726 ** If the file creation mode "m" is 0 then set it to the default for
25727 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25728 ** 0644) as modified by the system umask.  If m is not 0, then
25729 ** make the file creation mode be exactly m ignoring the umask.
25730 **
25731 ** The m parameter will be non-zero only when creating -wal, -journal,
25732 ** and -shm files.  We want those files to have *exactly* the same
25733 ** permissions as their original database, unadulterated by the umask.
25734 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25735 ** transaction crashes and leaves behind hot journals, then any
25736 ** process that is able to write to the database will also be able to
25737 ** recover the hot journals.
25738 */
25739 static int robust_open(const char *z, int f, mode_t m){
25740   int fd;
25741   mode_t m2;
25742   mode_t origM = 0;
25743   if( m==0 ){
25744     m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
25745   }else{
25746     m2 = m;
25747     origM = osUmask(0);
25748   }
25749   do{
25750 #if defined(O_CLOEXEC)
25751     fd = osOpen(z,f|O_CLOEXEC,m2);
25752 #else
25753     fd = osOpen(z,f,m2);
25754 #endif
25755   }while( fd<0 && errno==EINTR );
25756   if( m ){
25757     osUmask(origM);
25758   }
25759 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
25760   if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25761 #endif
25762   return fd;
25763 }
25764
25765 /*
25766 ** Helper functions to obtain and relinquish the global mutex. The
25767 ** global mutex is used to protect the unixInodeInfo and
25768 ** vxworksFileId objects used by this file, all of which may be
25769 ** shared by multiple threads.
25770 **
25771 ** Function unixMutexHeld() is used to assert() that the global mutex
25772 ** is held when required. This function is only used as part of assert()
25773 ** statements. e.g.
25774 **
25775 **   unixEnterMutex()
25776 **     assert( unixMutexHeld() );
25777 **   unixEnterLeave()
25778 */
25779 static void unixEnterMutex(void){
25780   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25781 }
25782 static void unixLeaveMutex(void){
25783   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25784 }
25785 #ifdef SQLITE_DEBUG
25786 static int unixMutexHeld(void) {
25787   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25788 }
25789 #endif
25790
25791
25792 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25793 /*
25794 ** Helper function for printing out trace information from debugging
25795 ** binaries. This returns the string represetation of the supplied
25796 ** integer lock-type.
25797 */
25798 static const char *azFileLock(int eFileLock){
25799   switch( eFileLock ){
25800     case NO_LOCK: return "NONE";
25801     case SHARED_LOCK: return "SHARED";
25802     case RESERVED_LOCK: return "RESERVED";
25803     case PENDING_LOCK: return "PENDING";
25804     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25805   }
25806   return "ERROR";
25807 }
25808 #endif
25809
25810 #ifdef SQLITE_LOCK_TRACE
25811 /*
25812 ** Print out information about all locking operations.
25813 **
25814 ** This routine is used for troubleshooting locks on multithreaded
25815 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
25816 ** command-line option on the compiler.  This code is normally
25817 ** turned off.
25818 */
25819 static int lockTrace(int fd, int op, struct flock *p){
25820   char *zOpName, *zType;
25821   int s;
25822   int savedErrno;
25823   if( op==F_GETLK ){
25824     zOpName = "GETLK";
25825   }else if( op==F_SETLK ){
25826     zOpName = "SETLK";
25827   }else{
25828     s = osFcntl(fd, op, p);
25829     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25830     return s;
25831   }
25832   if( p->l_type==F_RDLCK ){
25833     zType = "RDLCK";
25834   }else if( p->l_type==F_WRLCK ){
25835     zType = "WRLCK";
25836   }else if( p->l_type==F_UNLCK ){
25837     zType = "UNLCK";
25838   }else{
25839     assert( 0 );
25840   }
25841   assert( p->l_whence==SEEK_SET );
25842   s = osFcntl(fd, op, p);
25843   savedErrno = errno;
25844   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25845      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25846      (int)p->l_pid, s);
25847   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25848     struct flock l2;
25849     l2 = *p;
25850     osFcntl(fd, F_GETLK, &l2);
25851     if( l2.l_type==F_RDLCK ){
25852       zType = "RDLCK";
25853     }else if( l2.l_type==F_WRLCK ){
25854       zType = "WRLCK";
25855     }else if( l2.l_type==F_UNLCK ){
25856       zType = "UNLCK";
25857     }else{
25858       assert( 0 );
25859     }
25860     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25861        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25862   }
25863   errno = savedErrno;
25864   return s;
25865 }
25866 #undef osFcntl
25867 #define osFcntl lockTrace
25868 #endif /* SQLITE_LOCK_TRACE */
25869
25870 /*
25871 ** Retry ftruncate() calls that fail due to EINTR
25872 */
25873 static int robust_ftruncate(int h, sqlite3_int64 sz){
25874   int rc;
25875   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25876   return rc;
25877 }
25878
25879 /*
25880 ** This routine translates a standard POSIX errno code into something
25881 ** useful to the clients of the sqlite3 functions.  Specifically, it is
25882 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25883 ** and a variety of "please close the file descriptor NOW" errors into
25884 ** SQLITE_IOERR
25885 **
25886 ** Errors during initialization of locks, or file system support for locks,
25887 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25888 */
25889 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25890   switch (posixError) {
25891 #if 0
25892   /* At one point this code was not commented out. In theory, this branch
25893   ** should never be hit, as this function should only be called after
25894   ** a locking-related function (i.e. fcntl()) has returned non-zero with
25895   ** the value of errno as the first argument. Since a system call has failed,
25896   ** errno should be non-zero.
25897   **
25898   ** Despite this, if errno really is zero, we still don't want to return
25899   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25900   ** propagated back to the caller. Commenting this branch out means errno==0
25901   ** will be handled by the "default:" case below.
25902   */
25903   case 0:
25904     return SQLITE_OK;
25905 #endif
25906
25907   case EAGAIN:
25908   case ETIMEDOUT:
25909   case EBUSY:
25910   case EINTR:
25911   case ENOLCK:
25912     /* random NFS retry error, unless during file system support
25913      * introspection, in which it actually means what it says */
25914     return SQLITE_BUSY;
25915
25916   case EACCES:
25917     /* EACCES is like EAGAIN during locking operations, but not any other time*/
25918     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25919         (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25920         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25921         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25922       return SQLITE_BUSY;
25923     }
25924     /* else fall through */
25925   case EPERM:
25926     return SQLITE_PERM;
25927
25928   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
25929   ** this module never makes such a call. And the code in SQLite itself
25930   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
25931   ** this case is also commented out. If the system does set errno to EDEADLK,
25932   ** the default SQLITE_IOERR_XXX code will be returned. */
25933 #if 0
25934   case EDEADLK:
25935     return SQLITE_IOERR_BLOCKED;
25936 #endif
25937
25938 #if EOPNOTSUPP!=ENOTSUP
25939   case EOPNOTSUPP:
25940     /* something went terribly awry, unless during file system support
25941      * introspection, in which it actually means what it says */
25942 #endif
25943 #ifdef ENOTSUP
25944   case ENOTSUP:
25945     /* invalid fd, unless during file system support introspection, in which
25946      * it actually means what it says */
25947 #endif
25948   case EIO:
25949   case EBADF:
25950   case EINVAL:
25951   case ENOTCONN:
25952   case ENODEV:
25953   case ENXIO:
25954   case ENOENT:
25955 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
25956   case ESTALE:
25957 #endif
25958   case ENOSYS:
25959     /* these should force the client to close the file and reconnect */
25960
25961   default:
25962     return sqliteIOErr;
25963   }
25964 }
25965
25966
25967
25968 /******************************************************************************
25969 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25970 **
25971 ** On most versions of unix, we can get a unique ID for a file by concatenating
25972 ** the device number and the inode number.  But this does not work on VxWorks.
25973 ** On VxWorks, a unique file id must be based on the canonical filename.
25974 **
25975 ** A pointer to an instance of the following structure can be used as a
25976 ** unique file ID in VxWorks.  Each instance of this structure contains
25977 ** a copy of the canonical filename.  There is also a reference count.
25978 ** The structure is reclaimed when the number of pointers to it drops to
25979 ** zero.
25980 **
25981 ** There are never very many files open at one time and lookups are not
25982 ** a performance-critical path, so it is sufficient to put these
25983 ** structures on a linked list.
25984 */
25985 struct vxworksFileId {
25986   struct vxworksFileId *pNext;  /* Next in a list of them all */
25987   int nRef;                     /* Number of references to this one */
25988   int nName;                    /* Length of the zCanonicalName[] string */
25989   char *zCanonicalName;         /* Canonical filename */
25990 };
25991
25992 #if OS_VXWORKS
25993 /*
25994 ** All unique filenames are held on a linked list headed by this
25995 ** variable:
25996 */
25997 static struct vxworksFileId *vxworksFileList = 0;
25998
25999 /*
26000 ** Simplify a filename into its canonical form
26001 ** by making the following changes:
26002 **
26003 **  * removing any trailing and duplicate /
26004 **  * convert /./ into just /
26005 **  * convert /A/../ where A is any simple name into just /
26006 **
26007 ** Changes are made in-place.  Return the new name length.
26008 **
26009 ** The original filename is in z[0..n-1].  Return the number of
26010 ** characters in the simplified name.
26011 */
26012 static int vxworksSimplifyName(char *z, int n){
26013   int i, j;
26014   while( n>1 && z[n-1]=='/' ){ n--; }
26015   for(i=j=0; i<n; i++){
26016     if( z[i]=='/' ){
26017       if( z[i+1]=='/' ) continue;
26018       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
26019         i += 1;
26020         continue;
26021       }
26022       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
26023         while( j>0 && z[j-1]!='/' ){ j--; }
26024         if( j>0 ){ j--; }
26025         i += 2;
26026         continue;
26027       }
26028     }
26029     z[j++] = z[i];
26030   }
26031   z[j] = 0;
26032   return j;
26033 }
26034
26035 /*
26036 ** Find a unique file ID for the given absolute pathname.  Return
26037 ** a pointer to the vxworksFileId object.  This pointer is the unique
26038 ** file ID.
26039 **
26040 ** The nRef field of the vxworksFileId object is incremented before
26041 ** the object is returned.  A new vxworksFileId object is created
26042 ** and added to the global list if necessary.
26043 **
26044 ** If a memory allocation error occurs, return NULL.
26045 */
26046 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
26047   struct vxworksFileId *pNew;         /* search key and new file ID */
26048   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
26049   int n;                              /* Length of zAbsoluteName string */
26050
26051   assert( zAbsoluteName[0]=='/' );
26052   n = (int)strlen(zAbsoluteName);
26053   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
26054   if( pNew==0 ) return 0;
26055   pNew->zCanonicalName = (char*)&pNew[1];
26056   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
26057   n = vxworksSimplifyName(pNew->zCanonicalName, n);
26058
26059   /* Search for an existing entry that matching the canonical name.
26060   ** If found, increment the reference count and return a pointer to
26061   ** the existing file ID.
26062   */
26063   unixEnterMutex();
26064   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
26065     if( pCandidate->nName==n
26066      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
26067     ){
26068        sqlite3_free(pNew);
26069        pCandidate->nRef++;
26070        unixLeaveMutex();
26071        return pCandidate;
26072     }
26073   }
26074
26075   /* No match was found.  We will make a new file ID */
26076   pNew->nRef = 1;
26077   pNew->nName = n;
26078   pNew->pNext = vxworksFileList;
26079   vxworksFileList = pNew;
26080   unixLeaveMutex();
26081   return pNew;
26082 }
26083
26084 /*
26085 ** Decrement the reference count on a vxworksFileId object.  Free
26086 ** the object when the reference count reaches zero.
26087 */
26088 static void vxworksReleaseFileId(struct vxworksFileId *pId){
26089   unixEnterMutex();
26090   assert( pId->nRef>0 );
26091   pId->nRef--;
26092   if( pId->nRef==0 ){
26093     struct vxworksFileId **pp;
26094     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
26095     assert( *pp==pId );
26096     *pp = pId->pNext;
26097     sqlite3_free(pId);
26098   }
26099   unixLeaveMutex();
26100 }
26101 #endif /* OS_VXWORKS */
26102 /*************** End of Unique File ID Utility Used By VxWorks ****************
26103 ******************************************************************************/
26104
26105
26106 /******************************************************************************
26107 *************************** Posix Advisory Locking ****************************
26108 **
26109 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
26110 ** section 6.5.2.2 lines 483 through 490 specify that when a process
26111 ** sets or clears a lock, that operation overrides any prior locks set
26112 ** by the same process.  It does not explicitly say so, but this implies
26113 ** that it overrides locks set by the same process using a different
26114 ** file descriptor.  Consider this test case:
26115 **
26116 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
26117 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
26118 **
26119 ** Suppose ./file1 and ./file2 are really the same file (because
26120 ** one is a hard or symbolic link to the other) then if you set
26121 ** an exclusive lock on fd1, then try to get an exclusive lock
26122 ** on fd2, it works.  I would have expected the second lock to
26123 ** fail since there was already a lock on the file due to fd1.
26124 ** But not so.  Since both locks came from the same process, the
26125 ** second overrides the first, even though they were on different
26126 ** file descriptors opened on different file names.
26127 **
26128 ** This means that we cannot use POSIX locks to synchronize file access
26129 ** among competing threads of the same process.  POSIX locks will work fine
26130 ** to synchronize access for threads in separate processes, but not
26131 ** threads within the same process.
26132 **
26133 ** To work around the problem, SQLite has to manage file locks internally
26134 ** on its own.  Whenever a new database is opened, we have to find the
26135 ** specific inode of the database file (the inode is determined by the
26136 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
26137 ** and check for locks already existing on that inode.  When locks are
26138 ** created or removed, we have to look at our own internal record of the
26139 ** locks to see if another thread has previously set a lock on that same
26140 ** inode.
26141 **
26142 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
26143 ** For VxWorks, we have to use the alternative unique ID system based on
26144 ** canonical filename and implemented in the previous division.)
26145 **
26146 ** The sqlite3_file structure for POSIX is no longer just an integer file
26147 ** descriptor.  It is now a structure that holds the integer file
26148 ** descriptor and a pointer to a structure that describes the internal
26149 ** locks on the corresponding inode.  There is one locking structure
26150 ** per inode, so if the same inode is opened twice, both unixFile structures
26151 ** point to the same locking structure.  The locking structure keeps
26152 ** a reference count (so we will know when to delete it) and a "cnt"
26153 ** field that tells us its internal lock status.  cnt==0 means the
26154 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
26155 ** cnt>0 means there are cnt shared locks on the file.
26156 **
26157 ** Any attempt to lock or unlock a file first checks the locking
26158 ** structure.  The fcntl() system call is only invoked to set a
26159 ** POSIX lock if the internal lock structure transitions between
26160 ** a locked and an unlocked state.
26161 **
26162 ** But wait:  there are yet more problems with POSIX advisory locks.
26163 **
26164 ** If you close a file descriptor that points to a file that has locks,
26165 ** all locks on that file that are owned by the current process are
26166 ** released.  To work around this problem, each unixInodeInfo object
26167 ** maintains a count of the number of pending locks on tha inode.
26168 ** When an attempt is made to close an unixFile, if there are
26169 ** other unixFile open on the same inode that are holding locks, the call
26170 ** to close() the file descriptor is deferred until all of the locks clear.
26171 ** The unixInodeInfo structure keeps a list of file descriptors that need to
26172 ** be closed and that list is walked (and cleared) when the last lock
26173 ** clears.
26174 **
26175 ** Yet another problem:  LinuxThreads do not play well with posix locks.
26176 **
26177 ** Many older versions of linux use the LinuxThreads library which is
26178 ** not posix compliant.  Under LinuxThreads, a lock created by thread
26179 ** A cannot be modified or overridden by a different thread B.
26180 ** Only thread A can modify the lock.  Locking behavior is correct
26181 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
26182 ** on linux - with NPTL a lock created by thread A can override locks
26183 ** in thread B.  But there is no way to know at compile-time which
26184 ** threading library is being used.  So there is no way to know at
26185 ** compile-time whether or not thread A can override locks on thread B.
26186 ** One has to do a run-time check to discover the behavior of the
26187 ** current process.
26188 **
26189 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
26190 ** was dropped beginning with version 3.7.0.  SQLite will still work with
26191 ** LinuxThreads provided that (1) there is no more than one connection
26192 ** per database file in the same process and (2) database connections
26193 ** do not move across threads.
26194 */
26195
26196 /*
26197 ** An instance of the following structure serves as the key used
26198 ** to locate a particular unixInodeInfo object.
26199 */
26200 struct unixFileId {
26201   dev_t dev;                  /* Device number */
26202 #if OS_VXWORKS
26203   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
26204 #else
26205   ino_t ino;                  /* Inode number */
26206 #endif
26207 };
26208
26209 /*
26210 ** An instance of the following structure is allocated for each open
26211 ** inode.  Or, on LinuxThreads, there is one of these structures for
26212 ** each inode opened by each thread.
26213 **
26214 ** A single inode can have multiple file descriptors, so each unixFile
26215 ** structure contains a pointer to an instance of this object and this
26216 ** object keeps a count of the number of unixFile pointing to it.
26217 */
26218 struct unixInodeInfo {
26219   struct unixFileId fileId;       /* The lookup key */
26220   int nShared;                    /* Number of SHARED locks held */
26221   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
26222   unsigned char bProcessLock;     /* An exclusive process lock is held */
26223   int nRef;                       /* Number of pointers to this structure */
26224   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
26225   int nLock;                      /* Number of outstanding file locks */
26226   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
26227   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
26228   unixInodeInfo *pPrev;           /*    .... doubly linked */
26229 #if SQLITE_ENABLE_LOCKING_STYLE
26230   unsigned long long sharedByte;  /* for AFP simulated shared lock */
26231 #endif
26232 #if OS_VXWORKS
26233   sem_t *pSem;                    /* Named POSIX semaphore */
26234   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
26235 #endif
26236 };
26237
26238 /*
26239 ** A lists of all unixInodeInfo objects.
26240 */
26241 static unixInodeInfo *inodeList = 0;
26242
26243 /*
26244 **
26245 ** This function - unixLogError_x(), is only ever called via the macro
26246 ** unixLogError().
26247 **
26248 ** It is invoked after an error occurs in an OS function and errno has been
26249 ** set. It logs a message using sqlite3_log() containing the current value of
26250 ** errno and, if possible, the human-readable equivalent from strerror() or
26251 ** strerror_r().
26252 **
26253 ** The first argument passed to the macro should be the error code that
26254 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
26255 ** The two subsequent arguments should be the name of the OS function that
26256 ** failed (e.g. "unlink", "open") and the associated file-system path,
26257 ** if any.
26258 */
26259 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
26260 static int unixLogErrorAtLine(
26261   int errcode,                    /* SQLite error code */
26262   const char *zFunc,              /* Name of OS function that failed */
26263   const char *zPath,              /* File path associated with error */
26264   int iLine                       /* Source line number where error occurred */
26265 ){
26266   char *zErr;                     /* Message from strerror() or equivalent */
26267   int iErrno = errno;             /* Saved syscall error number */
26268
26269   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
26270   ** the strerror() function to obtain the human-readable error message
26271   ** equivalent to errno. Otherwise, use strerror_r().
26272   */
26273 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
26274   char aErr[80];
26275   memset(aErr, 0, sizeof(aErr));
26276   zErr = aErr;
26277
26278   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
26279   ** assume that the system provides the GNU version of strerror_r() that
26280   ** returns a pointer to a buffer containing the error message. That pointer
26281   ** may point to aErr[], or it may point to some static storage somewhere.
26282   ** Otherwise, assume that the system provides the POSIX version of
26283   ** strerror_r(), which always writes an error message into aErr[].
26284   **
26285   ** If the code incorrectly assumes that it is the POSIX version that is
26286   ** available, the error message will often be an empty string. Not a
26287   ** huge problem. Incorrectly concluding that the GNU version is available
26288   ** could lead to a segfault though.
26289   */
26290 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
26291   zErr =
26292 # endif
26293   strerror_r(iErrno, aErr, sizeof(aErr)-1);
26294
26295 #elif SQLITE_THREADSAFE
26296   /* This is a threadsafe build, but strerror_r() is not available. */
26297   zErr = "";
26298 #else
26299   /* Non-threadsafe build, use strerror(). */
26300   zErr = strerror(iErrno);
26301 #endif
26302
26303   assert( errcode!=SQLITE_OK );
26304   if( zPath==0 ) zPath = "";
26305   sqlite3_log(errcode,
26306       "os_unix.c:%d: (%d) %s(%s) - %s",
26307       iLine, iErrno, zFunc, zPath, zErr
26308   );
26309
26310   return errcode;
26311 }
26312
26313 /*
26314 ** Close a file descriptor.
26315 **
26316 ** We assume that close() almost always works, since it is only in a
26317 ** very sick application or on a very sick platform that it might fail.
26318 ** If it does fail, simply leak the file descriptor, but do log the
26319 ** error.
26320 **
26321 ** Note that it is not safe to retry close() after EINTR since the
26322 ** file descriptor might have already been reused by another thread.
26323 ** So we don't even try to recover from an EINTR.  Just log the error
26324 ** and move on.
26325 */
26326 static void robust_close(unixFile *pFile, int h, int lineno){
26327   if( osClose(h) ){
26328     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26329                        pFile ? pFile->zPath : 0, lineno);
26330   }
26331 }
26332
26333 /*
26334 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26335 */
26336 static void closePendingFds(unixFile *pFile){
26337   unixInodeInfo *pInode = pFile->pInode;
26338   UnixUnusedFd *p;
26339   UnixUnusedFd *pNext;
26340   for(p=pInode->pUnused; p; p=pNext){
26341     pNext = p->pNext;
26342     robust_close(pFile, p->fd, __LINE__);
26343     sqlite3_free(p);
26344   }
26345   pInode->pUnused = 0;
26346 }
26347
26348 /*
26349 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26350 **
26351 ** The mutex entered using the unixEnterMutex() function must be held
26352 ** when this function is called.
26353 */
26354 static void releaseInodeInfo(unixFile *pFile){
26355   unixInodeInfo *pInode = pFile->pInode;
26356   assert( unixMutexHeld() );
26357   if( ALWAYS(pInode) ){
26358     pInode->nRef--;
26359     if( pInode->nRef==0 ){
26360       assert( pInode->pShmNode==0 );
26361       closePendingFds(pFile);
26362       if( pInode->pPrev ){
26363         assert( pInode->pPrev->pNext==pInode );
26364         pInode->pPrev->pNext = pInode->pNext;
26365       }else{
26366         assert( inodeList==pInode );
26367         inodeList = pInode->pNext;
26368       }
26369       if( pInode->pNext ){
26370         assert( pInode->pNext->pPrev==pInode );
26371         pInode->pNext->pPrev = pInode->pPrev;
26372       }
26373       sqlite3_free(pInode);
26374     }
26375   }
26376 }
26377
26378 /*
26379 ** Given a file descriptor, locate the unixInodeInfo object that
26380 ** describes that file descriptor.  Create a new one if necessary.  The
26381 ** return value might be uninitialized if an error occurs.
26382 **
26383 ** The mutex entered using the unixEnterMutex() function must be held
26384 ** when this function is called.
26385 **
26386 ** Return an appropriate error code.
26387 */
26388 static int findInodeInfo(
26389   unixFile *pFile,               /* Unix file with file desc used in the key */
26390   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
26391 ){
26392   int rc;                        /* System call return code */
26393   int fd;                        /* The file descriptor for pFile */
26394   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
26395   struct stat statbuf;           /* Low-level file information */
26396   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
26397
26398   assert( unixMutexHeld() );
26399
26400   /* Get low-level information about the file that we can used to
26401   ** create a unique name for the file.
26402   */
26403   fd = pFile->h;
26404   rc = osFstat(fd, &statbuf);
26405   if( rc!=0 ){
26406     pFile->lastErrno = errno;
26407 #ifdef EOVERFLOW
26408     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26409 #endif
26410     return SQLITE_IOERR;
26411   }
26412
26413 #ifdef __APPLE__
26414   /* On OS X on an msdos filesystem, the inode number is reported
26415   ** incorrectly for zero-size files.  See ticket #3260.  To work
26416   ** around this problem (we consider it a bug in OS X, not SQLite)
26417   ** we always increase the file size to 1 by writing a single byte
26418   ** prior to accessing the inode number.  The one byte written is
26419   ** an ASCII 'S' character which also happens to be the first byte
26420   ** in the header of every SQLite database.  In this way, if there
26421   ** is a race condition such that another thread has already populated
26422   ** the first page of the database, no damage is done.
26423   */
26424   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26425     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26426     if( rc!=1 ){
26427       pFile->lastErrno = errno;
26428       return SQLITE_IOERR;
26429     }
26430     rc = osFstat(fd, &statbuf);
26431     if( rc!=0 ){
26432       pFile->lastErrno = errno;
26433       return SQLITE_IOERR;
26434     }
26435   }
26436 #endif
26437
26438   memset(&fileId, 0, sizeof(fileId));
26439   fileId.dev = statbuf.st_dev;
26440 #if OS_VXWORKS
26441   fileId.pId = pFile->pId;
26442 #else
26443   fileId.ino = statbuf.st_ino;
26444 #endif
26445   pInode = inodeList;
26446   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26447     pInode = pInode->pNext;
26448   }
26449   if( pInode==0 ){
26450     pInode = sqlite3_malloc( sizeof(*pInode) );
26451     if( pInode==0 ){
26452       return SQLITE_NOMEM;
26453     }
26454     memset(pInode, 0, sizeof(*pInode));
26455     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26456     pInode->nRef = 1;
26457     pInode->pNext = inodeList;
26458     pInode->pPrev = 0;
26459     if( inodeList ) inodeList->pPrev = pInode;
26460     inodeList = pInode;
26461   }else{
26462     pInode->nRef++;
26463   }
26464   *ppInode = pInode;
26465   return SQLITE_OK;
26466 }
26467
26468
26469 /*
26470 ** This routine checks if there is a RESERVED lock held on the specified
26471 ** file by this or any other process. If such a lock is held, set *pResOut
26472 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26473 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26474 */
26475 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26476   int rc = SQLITE_OK;
26477   int reserved = 0;
26478   unixFile *pFile = (unixFile*)id;
26479
26480   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26481
26482   assert( pFile );
26483   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26484
26485   /* Check if a thread in this process holds such a lock */
26486   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26487     reserved = 1;
26488   }
26489
26490   /* Otherwise see if some other process holds it.
26491   */
26492 #ifndef __DJGPP__
26493   if( !reserved && !pFile->pInode->bProcessLock ){
26494     struct flock lock;
26495     lock.l_whence = SEEK_SET;
26496     lock.l_start = RESERVED_BYTE;
26497     lock.l_len = 1;
26498     lock.l_type = F_WRLCK;
26499     if( osFcntl(pFile->h, F_GETLK, &lock) ){
26500       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26501       pFile->lastErrno = errno;
26502     } else if( lock.l_type!=F_UNLCK ){
26503       reserved = 1;
26504     }
26505   }
26506 #endif
26507
26508   unixLeaveMutex();
26509   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26510
26511   *pResOut = reserved;
26512   return rc;
26513 }
26514
26515 /*
26516 ** Attempt to set a system-lock on the file pFile.  The lock is
26517 ** described by pLock.
26518 **
26519 ** If the pFile was opened read/write from unix-excl, then the only lock
26520 ** ever obtained is an exclusive lock, and it is obtained exactly once
26521 ** the first time any lock is attempted.  All subsequent system locking
26522 ** operations become no-ops.  Locking operations still happen internally,
26523 ** in order to coordinate access between separate database connections
26524 ** within this process, but all of that is handled in memory and the
26525 ** operating system does not participate.
26526 **
26527 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26528 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26529 ** and is read-only.
26530 **
26531 ** Zero is returned if the call completes successfully, or -1 if a call
26532 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26533 */
26534 static int unixFileLock(unixFile *pFile, struct flock *pLock){
26535   int rc;
26536   unixInodeInfo *pInode = pFile->pInode;
26537   assert( unixMutexHeld() );
26538   assert( pInode!=0 );
26539   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26540    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26541   ){
26542     if( pInode->bProcessLock==0 ){
26543       struct flock lock;
26544       assert( pInode->nLock==0 );
26545       lock.l_whence = SEEK_SET;
26546       lock.l_start = SHARED_FIRST;
26547       lock.l_len = SHARED_SIZE;
26548       lock.l_type = F_WRLCK;
26549       rc = osFcntl(pFile->h, F_SETLK, &lock);
26550       if( rc<0 ) return rc;
26551       pInode->bProcessLock = 1;
26552       pInode->nLock++;
26553     }else{
26554       rc = 0;
26555     }
26556   }else{
26557     rc = osFcntl(pFile->h, F_SETLK, pLock);
26558   }
26559   return rc;
26560 }
26561
26562 /*
26563 ** Lock the file with the lock specified by parameter eFileLock - one
26564 ** of the following:
26565 **
26566 **     (1) SHARED_LOCK
26567 **     (2) RESERVED_LOCK
26568 **     (3) PENDING_LOCK
26569 **     (4) EXCLUSIVE_LOCK
26570 **
26571 ** Sometimes when requesting one lock state, additional lock states
26572 ** are inserted in between.  The locking might fail on one of the later
26573 ** transitions leaving the lock state different from what it started but
26574 ** still short of its goal.  The following chart shows the allowed
26575 ** transitions and the inserted intermediate states:
26576 **
26577 **    UNLOCKED -> SHARED
26578 **    SHARED -> RESERVED
26579 **    SHARED -> (PENDING) -> EXCLUSIVE
26580 **    RESERVED -> (PENDING) -> EXCLUSIVE
26581 **    PENDING -> EXCLUSIVE
26582 **
26583 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26584 ** routine to lower a locking level.
26585 */
26586 static int unixLock(sqlite3_file *id, int eFileLock){
26587   /* The following describes the implementation of the various locks and
26588   ** lock transitions in terms of the POSIX advisory shared and exclusive
26589   ** lock primitives (called read-locks and write-locks below, to avoid
26590   ** confusion with SQLite lock names). The algorithms are complicated
26591   ** slightly in order to be compatible with windows systems simultaneously
26592   ** accessing the same database file, in case that is ever required.
26593   **
26594   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26595   ** byte', each single bytes at well known offsets, and the 'shared byte
26596   ** range', a range of 510 bytes at a well known offset.
26597   **
26598   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26599   ** byte'.  If this is successful, a random byte from the 'shared byte
26600   ** range' is read-locked and the lock on the 'pending byte' released.
26601   **
26602   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26603   ** A RESERVED lock is implemented by grabbing a write-lock on the
26604   ** 'reserved byte'.
26605   **
26606   ** A process may only obtain a PENDING lock after it has obtained a
26607   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26608   ** on the 'pending byte'. This ensures that no new SHARED locks can be
26609   ** obtained, but existing SHARED locks are allowed to persist. A process
26610   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26611   ** This property is used by the algorithm for rolling back a journal file
26612   ** after a crash.
26613   **
26614   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26615   ** implemented by obtaining a write-lock on the entire 'shared byte
26616   ** range'. Since all other locks require a read-lock on one of the bytes
26617   ** within this range, this ensures that no other locks are held on the
26618   ** database.
26619   **
26620   ** The reason a single byte cannot be used instead of the 'shared byte
26621   ** range' is that some versions of windows do not support read-locks. By
26622   ** locking a random byte from a range, concurrent SHARED locks may exist
26623   ** even if the locking primitive used is always a write-lock.
26624   */
26625   int rc = SQLITE_OK;
26626   unixFile *pFile = (unixFile*)id;
26627   unixInodeInfo *pInode;
26628   struct flock lock;
26629   int tErrno = 0;
26630
26631   assert( pFile );
26632   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26633       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26634       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
26635
26636   /* If there is already a lock of this type or more restrictive on the
26637   ** unixFile, do nothing. Don't use the end_lock: exit path, as
26638   ** unixEnterMutex() hasn't been called yet.
26639   */
26640   if( pFile->eFileLock>=eFileLock ){
26641     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
26642             azFileLock(eFileLock)));
26643     return SQLITE_OK;
26644   }
26645
26646   /* Make sure the locking sequence is correct.
26647   **  (1) We never move from unlocked to anything higher than shared lock.
26648   **  (2) SQLite never explicitly requests a pendig lock.
26649   **  (3) A shared lock is always held when a reserve lock is requested.
26650   */
26651   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26652   assert( eFileLock!=PENDING_LOCK );
26653   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26654
26655   /* This mutex is needed because pFile->pInode is shared across threads
26656   */
26657   unixEnterMutex();
26658   pInode = pFile->pInode;
26659
26660   /* If some thread using this PID has a lock via a different unixFile*
26661   ** handle that precludes the requested lock, return BUSY.
26662   */
26663   if( (pFile->eFileLock!=pInode->eFileLock &&
26664           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26665   ){
26666     rc = SQLITE_BUSY;
26667     goto end_lock;
26668   }
26669
26670   /* If a SHARED lock is requested, and some thread using this PID already
26671   ** has a SHARED or RESERVED lock, then increment reference counts and
26672   ** return SQLITE_OK.
26673   */
26674   if( eFileLock==SHARED_LOCK &&
26675       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26676     assert( eFileLock==SHARED_LOCK );
26677     assert( pFile->eFileLock==0 );
26678     assert( pInode->nShared>0 );
26679     pFile->eFileLock = SHARED_LOCK;
26680     pInode->nShared++;
26681     pInode->nLock++;
26682     goto end_lock;
26683   }
26684
26685
26686   /* A PENDING lock is needed before acquiring a SHARED lock and before
26687   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26688   ** be released.
26689   */
26690   lock.l_len = 1L;
26691   lock.l_whence = SEEK_SET;
26692   if( eFileLock==SHARED_LOCK
26693       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26694   ){
26695     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26696     lock.l_start = PENDING_BYTE;
26697     if( unixFileLock(pFile, &lock) ){
26698       tErrno = errno;
26699       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26700       if( rc!=SQLITE_BUSY ){
26701         pFile->lastErrno = tErrno;
26702       }
26703       goto end_lock;
26704     }
26705   }
26706
26707
26708   /* If control gets to this point, then actually go ahead and make
26709   ** operating system calls for the specified lock.
26710   */
26711   if( eFileLock==SHARED_LOCK ){
26712     assert( pInode->nShared==0 );
26713     assert( pInode->eFileLock==0 );
26714     assert( rc==SQLITE_OK );
26715
26716     /* Now get the read-lock */
26717     lock.l_start = SHARED_FIRST;
26718     lock.l_len = SHARED_SIZE;
26719     if( unixFileLock(pFile, &lock) ){
26720       tErrno = errno;
26721       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26722     }
26723
26724     /* Drop the temporary PENDING lock */
26725     lock.l_start = PENDING_BYTE;
26726     lock.l_len = 1L;
26727     lock.l_type = F_UNLCK;
26728     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26729       /* This could happen with a network mount */
26730       tErrno = errno;
26731       rc = SQLITE_IOERR_UNLOCK;
26732     }
26733
26734     if( rc ){
26735       if( rc!=SQLITE_BUSY ){
26736         pFile->lastErrno = tErrno;
26737       }
26738       goto end_lock;
26739     }else{
26740       pFile->eFileLock = SHARED_LOCK;
26741       pInode->nLock++;
26742       pInode->nShared = 1;
26743     }
26744   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26745     /* We are trying for an exclusive lock but another thread in this
26746     ** same process is still holding a shared lock. */
26747     rc = SQLITE_BUSY;
26748   }else{
26749     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26750     ** assumed that there is a SHARED or greater lock on the file
26751     ** already.
26752     */
26753     assert( 0!=pFile->eFileLock );
26754     lock.l_type = F_WRLCK;
26755
26756     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26757     if( eFileLock==RESERVED_LOCK ){
26758       lock.l_start = RESERVED_BYTE;
26759       lock.l_len = 1L;
26760     }else{
26761       lock.l_start = SHARED_FIRST;
26762       lock.l_len = SHARED_SIZE;
26763     }
26764
26765     if( unixFileLock(pFile, &lock) ){
26766       tErrno = errno;
26767       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26768       if( rc!=SQLITE_BUSY ){
26769         pFile->lastErrno = tErrno;
26770       }
26771     }
26772   }
26773
26774
26775 #ifdef SQLITE_DEBUG
26776   /* Set up the transaction-counter change checking flags when
26777   ** transitioning from a SHARED to a RESERVED lock.  The change
26778   ** from SHARED to RESERVED marks the beginning of a normal
26779   ** write operation (not a hot journal rollback).
26780   */
26781   if( rc==SQLITE_OK
26782    && pFile->eFileLock<=SHARED_LOCK
26783    && eFileLock==RESERVED_LOCK
26784   ){
26785     pFile->transCntrChng = 0;
26786     pFile->dbUpdate = 0;
26787     pFile->inNormalWrite = 1;
26788   }
26789 #endif
26790
26791
26792   if( rc==SQLITE_OK ){
26793     pFile->eFileLock = eFileLock;
26794     pInode->eFileLock = eFileLock;
26795   }else if( eFileLock==EXCLUSIVE_LOCK ){
26796     pFile->eFileLock = PENDING_LOCK;
26797     pInode->eFileLock = PENDING_LOCK;
26798   }
26799
26800 end_lock:
26801   unixLeaveMutex();
26802   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26803       rc==SQLITE_OK ? "ok" : "failed"));
26804   return rc;
26805 }
26806
26807 /*
26808 ** Add the file descriptor used by file handle pFile to the corresponding
26809 ** pUnused list.
26810 */
26811 static void setPendingFd(unixFile *pFile){
26812   unixInodeInfo *pInode = pFile->pInode;
26813   UnixUnusedFd *p = pFile->pUnused;
26814   p->pNext = pInode->pUnused;
26815   pInode->pUnused = p;
26816   pFile->h = -1;
26817   pFile->pUnused = 0;
26818 }
26819
26820 /*
26821 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26822 ** must be either NO_LOCK or SHARED_LOCK.
26823 **
26824 ** If the locking level of the file descriptor is already at or below
26825 ** the requested locking level, this routine is a no-op.
26826 **
26827 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26828 ** the byte range is divided into 2 parts and the first part is unlocked then
26829 ** set to a read lock, then the other part is simply unlocked.  This works
26830 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26831 ** remove the write lock on a region when a read lock is set.
26832 */
26833 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26834   unixFile *pFile = (unixFile*)id;
26835   unixInodeInfo *pInode;
26836   struct flock lock;
26837   int rc = SQLITE_OK;
26838
26839   assert( pFile );
26840   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26841       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26842       getpid()));
26843
26844   assert( eFileLock<=SHARED_LOCK );
26845   if( pFile->eFileLock<=eFileLock ){
26846     return SQLITE_OK;
26847   }
26848   unixEnterMutex();
26849   pInode = pFile->pInode;
26850   assert( pInode->nShared!=0 );
26851   if( pFile->eFileLock>SHARED_LOCK ){
26852     assert( pInode->eFileLock==pFile->eFileLock );
26853
26854 #ifdef SQLITE_DEBUG
26855     /* When reducing a lock such that other processes can start
26856     ** reading the database file again, make sure that the
26857     ** transaction counter was updated if any part of the database
26858     ** file changed.  If the transaction counter is not updated,
26859     ** other connections to the same file might not realize that
26860     ** the file has changed and hence might not know to flush their
26861     ** cache.  The use of a stale cache can lead to database corruption.
26862     */
26863     pFile->inNormalWrite = 0;
26864 #endif
26865
26866     /* downgrading to a shared lock on NFS involves clearing the write lock
26867     ** before establishing the readlock - to avoid a race condition we downgrade
26868     ** the lock in 2 blocks, so that part of the range will be covered by a
26869     ** write lock until the rest is covered by a read lock:
26870     **  1:   [WWWWW]
26871     **  2:   [....W]
26872     **  3:   [RRRRW]
26873     **  4:   [RRRR.]
26874     */
26875     if( eFileLock==SHARED_LOCK ){
26876
26877 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26878       (void)handleNFSUnlock;
26879       assert( handleNFSUnlock==0 );
26880 #endif
26881 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26882       if( handleNFSUnlock ){
26883         int tErrno;               /* Error code from system call errors */
26884         off_t divSize = SHARED_SIZE - 1;
26885
26886         lock.l_type = F_UNLCK;
26887         lock.l_whence = SEEK_SET;
26888         lock.l_start = SHARED_FIRST;
26889         lock.l_len = divSize;
26890         if( unixFileLock(pFile, &lock)==(-1) ){
26891           tErrno = errno;
26892           rc = SQLITE_IOERR_UNLOCK;
26893           if( IS_LOCK_ERROR(rc) ){
26894             pFile->lastErrno = tErrno;
26895           }
26896           goto end_unlock;
26897         }
26898         lock.l_type = F_RDLCK;
26899         lock.l_whence = SEEK_SET;
26900         lock.l_start = SHARED_FIRST;
26901         lock.l_len = divSize;
26902         if( unixFileLock(pFile, &lock)==(-1) ){
26903           tErrno = errno;
26904           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26905           if( IS_LOCK_ERROR(rc) ){
26906             pFile->lastErrno = tErrno;
26907           }
26908           goto end_unlock;
26909         }
26910         lock.l_type = F_UNLCK;
26911         lock.l_whence = SEEK_SET;
26912         lock.l_start = SHARED_FIRST+divSize;
26913         lock.l_len = SHARED_SIZE-divSize;
26914         if( unixFileLock(pFile, &lock)==(-1) ){
26915           tErrno = errno;
26916           rc = SQLITE_IOERR_UNLOCK;
26917           if( IS_LOCK_ERROR(rc) ){
26918             pFile->lastErrno = tErrno;
26919           }
26920           goto end_unlock;
26921         }
26922       }else
26923 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26924       {
26925         lock.l_type = F_RDLCK;
26926         lock.l_whence = SEEK_SET;
26927         lock.l_start = SHARED_FIRST;
26928         lock.l_len = SHARED_SIZE;
26929         if( unixFileLock(pFile, &lock) ){
26930           /* In theory, the call to unixFileLock() cannot fail because another
26931           ** process is holding an incompatible lock. If it does, this
26932           ** indicates that the other process is not following the locking
26933           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26934           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26935           ** an assert to fail). */
26936           rc = SQLITE_IOERR_RDLOCK;
26937           pFile->lastErrno = errno;
26938           goto end_unlock;
26939         }
26940       }
26941     }
26942     lock.l_type = F_UNLCK;
26943     lock.l_whence = SEEK_SET;
26944     lock.l_start = PENDING_BYTE;
26945     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
26946     if( unixFileLock(pFile, &lock)==0 ){
26947       pInode->eFileLock = SHARED_LOCK;
26948     }else{
26949       rc = SQLITE_IOERR_UNLOCK;
26950       pFile->lastErrno = errno;
26951       goto end_unlock;
26952     }
26953   }
26954   if( eFileLock==NO_LOCK ){
26955     /* Decrement the shared lock counter.  Release the lock using an
26956     ** OS call only when all threads in this same process have released
26957     ** the lock.
26958     */
26959     pInode->nShared--;
26960     if( pInode->nShared==0 ){
26961       lock.l_type = F_UNLCK;
26962       lock.l_whence = SEEK_SET;
26963       lock.l_start = lock.l_len = 0L;
26964       if( unixFileLock(pFile, &lock)==0 ){
26965         pInode->eFileLock = NO_LOCK;
26966       }else{
26967         rc = SQLITE_IOERR_UNLOCK;
26968         pFile->lastErrno = errno;
26969         pInode->eFileLock = NO_LOCK;
26970         pFile->eFileLock = NO_LOCK;
26971       }
26972     }
26973
26974     /* Decrement the count of locks against this same file.  When the
26975     ** count reaches zero, close any other file descriptors whose close
26976     ** was deferred because of outstanding locks.
26977     */
26978     pInode->nLock--;
26979     assert( pInode->nLock>=0 );
26980     if( pInode->nLock==0 ){
26981       closePendingFds(pFile);
26982     }
26983   }
26984
26985 end_unlock:
26986   unixLeaveMutex();
26987   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26988   return rc;
26989 }
26990
26991 /*
26992 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26993 ** must be either NO_LOCK or SHARED_LOCK.
26994 **
26995 ** If the locking level of the file descriptor is already at or below
26996 ** the requested locking level, this routine is a no-op.
26997 */
26998 static int unixUnlock(sqlite3_file *id, int eFileLock){
26999   return posixUnlock(id, eFileLock, 0);
27000 }
27001
27002 /*
27003 ** This function performs the parts of the "close file" operation
27004 ** common to all locking schemes. It closes the directory and file
27005 ** handles, if they are valid, and sets all fields of the unixFile
27006 ** structure to 0.
27007 **
27008 ** It is *not* necessary to hold the mutex when this routine is called,
27009 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
27010 ** vxworksReleaseFileId() routine.
27011 */
27012 static int closeUnixFile(sqlite3_file *id){
27013   unixFile *pFile = (unixFile*)id;
27014   if( pFile->h>=0 ){
27015     robust_close(pFile, pFile->h, __LINE__);
27016     pFile->h = -1;
27017   }
27018 #if OS_VXWORKS
27019   if( pFile->pId ){
27020     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
27021       osUnlink(pFile->pId->zCanonicalName);
27022     }
27023     vxworksReleaseFileId(pFile->pId);
27024     pFile->pId = 0;
27025   }
27026 #endif
27027   OSTRACE(("CLOSE   %-3d\n", pFile->h));
27028   OpenCounter(-1);
27029   sqlite3_free(pFile->pUnused);
27030   memset(pFile, 0, sizeof(unixFile));
27031   return SQLITE_OK;
27032 }
27033
27034 /*
27035 ** Close a file.
27036 */
27037 static int unixClose(sqlite3_file *id){
27038   int rc = SQLITE_OK;
27039   unixFile *pFile = (unixFile *)id;
27040   unixUnlock(id, NO_LOCK);
27041   unixEnterMutex();
27042
27043   /* unixFile.pInode is always valid here. Otherwise, a different close
27044   ** routine (e.g. nolockClose()) would be called instead.
27045   */
27046   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
27047   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
27048     /* If there are outstanding locks, do not actually close the file just
27049     ** yet because that would clear those locks.  Instead, add the file
27050     ** descriptor to pInode->pUnused list.  It will be automatically closed
27051     ** when the last lock is cleared.
27052     */
27053     setPendingFd(pFile);
27054   }
27055   releaseInodeInfo(pFile);
27056   rc = closeUnixFile(id);
27057   unixLeaveMutex();
27058   return rc;
27059 }
27060
27061 /************** End of the posix advisory lock implementation *****************
27062 ******************************************************************************/
27063
27064 /******************************************************************************
27065 ****************************** No-op Locking **********************************
27066 **
27067 ** Of the various locking implementations available, this is by far the
27068 ** simplest:  locking is ignored.  No attempt is made to lock the database
27069 ** file for reading or writing.
27070 **
27071 ** This locking mode is appropriate for use on read-only databases
27072 ** (ex: databases that are burned into CD-ROM, for example.)  It can
27073 ** also be used if the application employs some external mechanism to
27074 ** prevent simultaneous access of the same database by two or more
27075 ** database connections.  But there is a serious risk of database
27076 ** corruption if this locking mode is used in situations where multiple
27077 ** database connections are accessing the same database file at the same
27078 ** time and one or more of those connections are writing.
27079 */
27080
27081 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
27082   UNUSED_PARAMETER(NotUsed);
27083   *pResOut = 0;
27084   return SQLITE_OK;
27085 }
27086 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
27087   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27088   return SQLITE_OK;
27089 }
27090 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
27091   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27092   return SQLITE_OK;
27093 }
27094
27095 /*
27096 ** Close the file.
27097 */
27098 static int nolockClose(sqlite3_file *id) {
27099   return closeUnixFile(id);
27100 }
27101
27102 /******************* End of the no-op lock implementation *********************
27103 ******************************************************************************/
27104
27105 /******************************************************************************
27106 ************************* Begin dot-file Locking ******************************
27107 **
27108 ** The dotfile locking implementation uses the existance of separate lock
27109 ** files (really a directory) to control access to the database.  This works
27110 ** on just about every filesystem imaginable.  But there are serious downsides:
27111 **
27112 **    (1)  There is zero concurrency.  A single reader blocks all other
27113 **         connections from reading or writing the database.
27114 **
27115 **    (2)  An application crash or power loss can leave stale lock files
27116 **         sitting around that need to be cleared manually.
27117 **
27118 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
27119 ** other locking strategy is available.
27120 **
27121 ** Dotfile locking works by creating a subdirectory in the same directory as
27122 ** the database and with the same name but with a ".lock" extension added.
27123 ** The existance of a lock directory implies an EXCLUSIVE lock.  All other
27124 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
27125 */
27126
27127 /*
27128 ** The file suffix added to the data base filename in order to create the
27129 ** lock directory.
27130 */
27131 #define DOTLOCK_SUFFIX ".lock"
27132
27133 /*
27134 ** This routine checks if there is a RESERVED lock held on the specified
27135 ** file by this or any other process. If such a lock is held, set *pResOut
27136 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27137 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27138 **
27139 ** In dotfile locking, either a lock exists or it does not.  So in this
27140 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
27141 ** is held on the file and false if the file is unlocked.
27142 */
27143 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
27144   int rc = SQLITE_OK;
27145   int reserved = 0;
27146   unixFile *pFile = (unixFile*)id;
27147
27148   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27149
27150   assert( pFile );
27151
27152   /* Check if a thread in this process holds such a lock */
27153   if( pFile->eFileLock>SHARED_LOCK ){
27154     /* Either this connection or some other connection in the same process
27155     ** holds a lock on the file.  No need to check further. */
27156     reserved = 1;
27157   }else{
27158     /* The lock is held if and only if the lockfile exists */
27159     const char *zLockFile = (const char*)pFile->lockingContext;
27160     reserved = osAccess(zLockFile, 0)==0;
27161   }
27162   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
27163   *pResOut = reserved;
27164   return rc;
27165 }
27166
27167 /*
27168 ** Lock the file with the lock specified by parameter eFileLock - one
27169 ** of the following:
27170 **
27171 **     (1) SHARED_LOCK
27172 **     (2) RESERVED_LOCK
27173 **     (3) PENDING_LOCK
27174 **     (4) EXCLUSIVE_LOCK
27175 **
27176 ** Sometimes when requesting one lock state, additional lock states
27177 ** are inserted in between.  The locking might fail on one of the later
27178 ** transitions leaving the lock state different from what it started but
27179 ** still short of its goal.  The following chart shows the allowed
27180 ** transitions and the inserted intermediate states:
27181 **
27182 **    UNLOCKED -> SHARED
27183 **    SHARED -> RESERVED
27184 **    SHARED -> (PENDING) -> EXCLUSIVE
27185 **    RESERVED -> (PENDING) -> EXCLUSIVE
27186 **    PENDING -> EXCLUSIVE
27187 **
27188 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27189 ** routine to lower a locking level.
27190 **
27191 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
27192 ** But we track the other locking levels internally.
27193 */
27194 static int dotlockLock(sqlite3_file *id, int eFileLock) {
27195   unixFile *pFile = (unixFile*)id;
27196   char *zLockFile = (char *)pFile->lockingContext;
27197   int rc = SQLITE_OK;
27198
27199
27200   /* If we have any lock, then the lock file already exists.  All we have
27201   ** to do is adjust our internal record of the lock level.
27202   */
27203   if( pFile->eFileLock > NO_LOCK ){
27204     pFile->eFileLock = eFileLock;
27205     /* Always update the timestamp on the old file */
27206 #ifdef HAVE_UTIME
27207     utime(zLockFile, NULL);
27208 #else
27209     utimes(zLockFile, NULL);
27210 #endif
27211     return SQLITE_OK;
27212   }
27213
27214   /* grab an exclusive lock */
27215   rc = osMkdir(zLockFile, 0777);
27216   if( rc<0 ){
27217     /* failed to open/create the lock directory */
27218     int tErrno = errno;
27219     if( EEXIST == tErrno ){
27220       rc = SQLITE_BUSY;
27221     } else {
27222       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27223       if( IS_LOCK_ERROR(rc) ){
27224         pFile->lastErrno = tErrno;
27225       }
27226     }
27227     return rc;
27228   }
27229
27230   /* got it, set the type and return ok */
27231   pFile->eFileLock = eFileLock;
27232   return rc;
27233 }
27234
27235 /*
27236 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27237 ** must be either NO_LOCK or SHARED_LOCK.
27238 **
27239 ** If the locking level of the file descriptor is already at or below
27240 ** the requested locking level, this routine is a no-op.
27241 **
27242 ** When the locking level reaches NO_LOCK, delete the lock file.
27243 */
27244 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27245   unixFile *pFile = (unixFile*)id;
27246   char *zLockFile = (char *)pFile->lockingContext;
27247   int rc;
27248
27249   assert( pFile );
27250   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27251            pFile->eFileLock, getpid()));
27252   assert( eFileLock<=SHARED_LOCK );
27253
27254   /* no-op if possible */
27255   if( pFile->eFileLock==eFileLock ){
27256     return SQLITE_OK;
27257   }
27258
27259   /* To downgrade to shared, simply update our internal notion of the
27260   ** lock state.  No need to mess with the file on disk.
27261   */
27262   if( eFileLock==SHARED_LOCK ){
27263     pFile->eFileLock = SHARED_LOCK;
27264     return SQLITE_OK;
27265   }
27266
27267   /* To fully unlock the database, delete the lock file */
27268   assert( eFileLock==NO_LOCK );
27269   rc = osRmdir(zLockFile);
27270   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27271   if( rc<0 ){
27272     int tErrno = errno;
27273     rc = 0;
27274     if( ENOENT != tErrno ){
27275       rc = SQLITE_IOERR_UNLOCK;
27276     }
27277     if( IS_LOCK_ERROR(rc) ){
27278       pFile->lastErrno = tErrno;
27279     }
27280     return rc;
27281   }
27282   pFile->eFileLock = NO_LOCK;
27283   return SQLITE_OK;
27284 }
27285
27286 /*
27287 ** Close a file.  Make sure the lock has been released before closing.
27288 */
27289 static int dotlockClose(sqlite3_file *id) {
27290   int rc = SQLITE_OK;
27291   if( id ){
27292     unixFile *pFile = (unixFile*)id;
27293     dotlockUnlock(id, NO_LOCK);
27294     sqlite3_free(pFile->lockingContext);
27295     rc = closeUnixFile(id);
27296   }
27297   return rc;
27298 }
27299 /****************** End of the dot-file lock implementation *******************
27300 ******************************************************************************/
27301
27302 /******************************************************************************
27303 ************************** Begin flock Locking ********************************
27304 **
27305 ** Use the flock() system call to do file locking.
27306 **
27307 ** flock() locking is like dot-file locking in that the various
27308 ** fine-grain locking levels supported by SQLite are collapsed into
27309 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
27310 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
27311 ** still works when you do this, but concurrency is reduced since
27312 ** only a single process can be reading the database at a time.
27313 **
27314 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
27315 ** compiling for VXWORKS.
27316 */
27317 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27318
27319 /*
27320 ** Retry flock() calls that fail with EINTR
27321 */
27322 #ifdef EINTR
27323 static int robust_flock(int fd, int op){
27324   int rc;
27325   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27326   return rc;
27327 }
27328 #else
27329 # define robust_flock(a,b) flock(a,b)
27330 #endif
27331
27332
27333 /*
27334 ** This routine checks if there is a RESERVED lock held on the specified
27335 ** file by this or any other process. If such a lock is held, set *pResOut
27336 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27337 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27338 */
27339 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27340   int rc = SQLITE_OK;
27341   int reserved = 0;
27342   unixFile *pFile = (unixFile*)id;
27343
27344   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27345
27346   assert( pFile );
27347
27348   /* Check if a thread in this process holds such a lock */
27349   if( pFile->eFileLock>SHARED_LOCK ){
27350     reserved = 1;
27351   }
27352
27353   /* Otherwise see if some other process holds it. */
27354   if( !reserved ){
27355     /* attempt to get the lock */
27356     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27357     if( !lrc ){
27358       /* got the lock, unlock it */
27359       lrc = robust_flock(pFile->h, LOCK_UN);
27360       if ( lrc ) {
27361         int tErrno = errno;
27362         /* unlock failed with an error */
27363         lrc = SQLITE_IOERR_UNLOCK;
27364         if( IS_LOCK_ERROR(lrc) ){
27365           pFile->lastErrno = tErrno;
27366           rc = lrc;
27367         }
27368       }
27369     } else {
27370       int tErrno = errno;
27371       reserved = 1;
27372       /* someone else might have it reserved */
27373       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27374       if( IS_LOCK_ERROR(lrc) ){
27375         pFile->lastErrno = tErrno;
27376         rc = lrc;
27377       }
27378     }
27379   }
27380   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27381
27382 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27383   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27384     rc = SQLITE_OK;
27385     reserved=1;
27386   }
27387 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27388   *pResOut = reserved;
27389   return rc;
27390 }
27391
27392 /*
27393 ** Lock the file with the lock specified by parameter eFileLock - one
27394 ** of the following:
27395 **
27396 **     (1) SHARED_LOCK
27397 **     (2) RESERVED_LOCK
27398 **     (3) PENDING_LOCK
27399 **     (4) EXCLUSIVE_LOCK
27400 **
27401 ** Sometimes when requesting one lock state, additional lock states
27402 ** are inserted in between.  The locking might fail on one of the later
27403 ** transitions leaving the lock state different from what it started but
27404 ** still short of its goal.  The following chart shows the allowed
27405 ** transitions and the inserted intermediate states:
27406 **
27407 **    UNLOCKED -> SHARED
27408 **    SHARED -> RESERVED
27409 **    SHARED -> (PENDING) -> EXCLUSIVE
27410 **    RESERVED -> (PENDING) -> EXCLUSIVE
27411 **    PENDING -> EXCLUSIVE
27412 **
27413 ** flock() only really support EXCLUSIVE locks.  We track intermediate
27414 ** lock states in the sqlite3_file structure, but all locks SHARED or
27415 ** above are really EXCLUSIVE locks and exclude all other processes from
27416 ** access the file.
27417 **
27418 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27419 ** routine to lower a locking level.
27420 */
27421 static int flockLock(sqlite3_file *id, int eFileLock) {
27422   int rc = SQLITE_OK;
27423   unixFile *pFile = (unixFile*)id;
27424
27425   assert( pFile );
27426
27427   /* if we already have a lock, it is exclusive.
27428   ** Just adjust level and punt on outta here. */
27429   if (pFile->eFileLock > NO_LOCK) {
27430     pFile->eFileLock = eFileLock;
27431     return SQLITE_OK;
27432   }
27433
27434   /* grab an exclusive lock */
27435
27436   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27437     int tErrno = errno;
27438     /* didn't get, must be busy */
27439     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27440     if( IS_LOCK_ERROR(rc) ){
27441       pFile->lastErrno = tErrno;
27442     }
27443   } else {
27444     /* got it, set the type and return ok */
27445     pFile->eFileLock = eFileLock;
27446   }
27447   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
27448            rc==SQLITE_OK ? "ok" : "failed"));
27449 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27450   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27451     rc = SQLITE_BUSY;
27452   }
27453 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27454   return rc;
27455 }
27456
27457
27458 /*
27459 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27460 ** must be either NO_LOCK or SHARED_LOCK.
27461 **
27462 ** If the locking level of the file descriptor is already at or below
27463 ** the requested locking level, this routine is a no-op.
27464 */
27465 static int flockUnlock(sqlite3_file *id, int eFileLock) {
27466   unixFile *pFile = (unixFile*)id;
27467
27468   assert( pFile );
27469   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27470            pFile->eFileLock, getpid()));
27471   assert( eFileLock<=SHARED_LOCK );
27472
27473   /* no-op if possible */
27474   if( pFile->eFileLock==eFileLock ){
27475     return SQLITE_OK;
27476   }
27477
27478   /* shared can just be set because we always have an exclusive */
27479   if (eFileLock==SHARED_LOCK) {
27480     pFile->eFileLock = eFileLock;
27481     return SQLITE_OK;
27482   }
27483
27484   /* no, really, unlock. */
27485   if( robust_flock(pFile->h, LOCK_UN) ){
27486 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27487     return SQLITE_OK;
27488 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27489     return SQLITE_IOERR_UNLOCK;
27490   }else{
27491     pFile->eFileLock = NO_LOCK;
27492     return SQLITE_OK;
27493   }
27494 }
27495
27496 /*
27497 ** Close a file.
27498 */
27499 static int flockClose(sqlite3_file *id) {
27500   int rc = SQLITE_OK;
27501   if( id ){
27502     flockUnlock(id, NO_LOCK);
27503     rc = closeUnixFile(id);
27504   }
27505   return rc;
27506 }
27507
27508 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27509
27510 /******************* End of the flock lock implementation *********************
27511 ******************************************************************************/
27512
27513 /******************************************************************************
27514 ************************ Begin Named Semaphore Locking ************************
27515 **
27516 ** Named semaphore locking is only supported on VxWorks.
27517 **
27518 ** Semaphore locking is like dot-lock and flock in that it really only
27519 ** supports EXCLUSIVE locking.  Only a single process can read or write
27520 ** the database file at a time.  This reduces potential concurrency, but
27521 ** makes the lock implementation much easier.
27522 */
27523 #if OS_VXWORKS
27524
27525 /*
27526 ** This routine checks if there is a RESERVED lock held on the specified
27527 ** file by this or any other process. If such a lock is held, set *pResOut
27528 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27529 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27530 */
27531 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
27532   int rc = SQLITE_OK;
27533   int reserved = 0;
27534   unixFile *pFile = (unixFile*)id;
27535
27536   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27537
27538   assert( pFile );
27539
27540   /* Check if a thread in this process holds such a lock */
27541   if( pFile->eFileLock>SHARED_LOCK ){
27542     reserved = 1;
27543   }
27544
27545   /* Otherwise see if some other process holds it. */
27546   if( !reserved ){
27547     sem_t *pSem = pFile->pInode->pSem;
27548     struct stat statBuf;
27549
27550     if( sem_trywait(pSem)==-1 ){
27551       int tErrno = errno;
27552       if( EAGAIN != tErrno ){
27553         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27554         pFile->lastErrno = tErrno;
27555       } else {
27556         /* someone else has the lock when we are in NO_LOCK */
27557         reserved = (pFile->eFileLock < SHARED_LOCK);
27558       }
27559     }else{
27560       /* we could have it if we want it */
27561       sem_post(pSem);
27562     }
27563   }
27564   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27565
27566   *pResOut = reserved;
27567   return rc;
27568 }
27569
27570 /*
27571 ** Lock the file with the lock specified by parameter eFileLock - one
27572 ** of the following:
27573 **
27574 **     (1) SHARED_LOCK
27575 **     (2) RESERVED_LOCK
27576 **     (3) PENDING_LOCK
27577 **     (4) EXCLUSIVE_LOCK
27578 **
27579 ** Sometimes when requesting one lock state, additional lock states
27580 ** are inserted in between.  The locking might fail on one of the later
27581 ** transitions leaving the lock state different from what it started but
27582 ** still short of its goal.  The following chart shows the allowed
27583 ** transitions and the inserted intermediate states:
27584 **
27585 **    UNLOCKED -> SHARED
27586 **    SHARED -> RESERVED
27587 **    SHARED -> (PENDING) -> EXCLUSIVE
27588 **    RESERVED -> (PENDING) -> EXCLUSIVE
27589 **    PENDING -> EXCLUSIVE
27590 **
27591 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
27592 ** lock states in the sqlite3_file structure, but all locks SHARED or
27593 ** above are really EXCLUSIVE locks and exclude all other processes from
27594 ** access the file.
27595 **
27596 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27597 ** routine to lower a locking level.
27598 */
27599 static int semLock(sqlite3_file *id, int eFileLock) {
27600   unixFile *pFile = (unixFile*)id;
27601   int fd;
27602   sem_t *pSem = pFile->pInode->pSem;
27603   int rc = SQLITE_OK;
27604
27605   /* if we already have a lock, it is exclusive.
27606   ** Just adjust level and punt on outta here. */
27607   if (pFile->eFileLock > NO_LOCK) {
27608     pFile->eFileLock = eFileLock;
27609     rc = SQLITE_OK;
27610     goto sem_end_lock;
27611   }
27612
27613   /* lock semaphore now but bail out when already locked. */
27614   if( sem_trywait(pSem)==-1 ){
27615     rc = SQLITE_BUSY;
27616     goto sem_end_lock;
27617   }
27618
27619   /* got it, set the type and return ok */
27620   pFile->eFileLock = eFileLock;
27621
27622  sem_end_lock:
27623   return rc;
27624 }
27625
27626 /*
27627 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27628 ** must be either NO_LOCK or SHARED_LOCK.
27629 **
27630 ** If the locking level of the file descriptor is already at or below
27631 ** the requested locking level, this routine is a no-op.
27632 */
27633 static int semUnlock(sqlite3_file *id, int eFileLock) {
27634   unixFile *pFile = (unixFile*)id;
27635   sem_t *pSem = pFile->pInode->pSem;
27636
27637   assert( pFile );
27638   assert( pSem );
27639   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27640            pFile->eFileLock, getpid()));
27641   assert( eFileLock<=SHARED_LOCK );
27642
27643   /* no-op if possible */
27644   if( pFile->eFileLock==eFileLock ){
27645     return SQLITE_OK;
27646   }
27647
27648   /* shared can just be set because we always have an exclusive */
27649   if (eFileLock==SHARED_LOCK) {
27650     pFile->eFileLock = eFileLock;
27651     return SQLITE_OK;
27652   }
27653
27654   /* no, really unlock. */
27655   if ( sem_post(pSem)==-1 ) {
27656     int rc, tErrno = errno;
27657     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27658     if( IS_LOCK_ERROR(rc) ){
27659       pFile->lastErrno = tErrno;
27660     }
27661     return rc;
27662   }
27663   pFile->eFileLock = NO_LOCK;
27664   return SQLITE_OK;
27665 }
27666
27667 /*
27668  ** Close a file.
27669  */
27670 static int semClose(sqlite3_file *id) {
27671   if( id ){
27672     unixFile *pFile = (unixFile*)id;
27673     semUnlock(id, NO_LOCK);
27674     assert( pFile );
27675     unixEnterMutex();
27676     releaseInodeInfo(pFile);
27677     unixLeaveMutex();
27678     closeUnixFile(id);
27679   }
27680   return SQLITE_OK;
27681 }
27682
27683 #endif /* OS_VXWORKS */
27684 /*
27685 ** Named semaphore locking is only available on VxWorks.
27686 **
27687 *************** End of the named semaphore lock implementation ****************
27688 ******************************************************************************/
27689
27690
27691 /******************************************************************************
27692 *************************** Begin AFP Locking *********************************
27693 **
27694 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
27695 ** on Apple Macintosh computers - both OS9 and OSX.
27696 **
27697 ** Third-party implementations of AFP are available.  But this code here
27698 ** only works on OSX.
27699 */
27700
27701 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27702 /*
27703 ** The afpLockingContext structure contains all afp lock specific state
27704 */
27705 typedef struct afpLockingContext afpLockingContext;
27706 struct afpLockingContext {
27707   int reserved;
27708   const char *dbPath;             /* Name of the open file */
27709 };
27710
27711 struct ByteRangeLockPB2
27712 {
27713   unsigned long long offset;        /* offset to first byte to lock */
27714   unsigned long long length;        /* nbr of bytes to lock */
27715   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27716   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
27717   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
27718   int fd;                           /* file desc to assoc this lock with */
27719 };
27720
27721 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
27722
27723 /*
27724 ** This is a utility for setting or clearing a bit-range lock on an
27725 ** AFP filesystem.
27726 **
27727 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27728 */
27729 static int afpSetLock(
27730   const char *path,              /* Name of the file to be locked or unlocked */
27731   unixFile *pFile,               /* Open file descriptor on path */
27732   unsigned long long offset,     /* First byte to be locked */
27733   unsigned long long length,     /* Number of bytes to lock */
27734   int setLockFlag                /* True to set lock.  False to clear lock */
27735 ){
27736   struct ByteRangeLockPB2 pb;
27737   int err;
27738
27739   pb.unLockFlag = setLockFlag ? 0 : 1;
27740   pb.startEndFlag = 0;
27741   pb.offset = offset;
27742   pb.length = length;
27743   pb.fd = pFile->h;
27744
27745   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27746     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27747     offset, length));
27748   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27749   if ( err==-1 ) {
27750     int rc;
27751     int tErrno = errno;
27752     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27753              path, tErrno, strerror(tErrno)));
27754 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27755     rc = SQLITE_BUSY;
27756 #else
27757     rc = sqliteErrorFromPosixError(tErrno,
27758                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27759 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27760     if( IS_LOCK_ERROR(rc) ){
27761       pFile->lastErrno = tErrno;
27762     }
27763     return rc;
27764   } else {
27765     return SQLITE_OK;
27766   }
27767 }
27768
27769 /*
27770 ** This routine checks if there is a RESERVED lock held on the specified
27771 ** file by this or any other process. If such a lock is held, set *pResOut
27772 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27773 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27774 */
27775 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27776   int rc = SQLITE_OK;
27777   int reserved = 0;
27778   unixFile *pFile = (unixFile*)id;
27779   afpLockingContext *context;
27780
27781   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27782
27783   assert( pFile );
27784   context = (afpLockingContext *) pFile->lockingContext;
27785   if( context->reserved ){
27786     *pResOut = 1;
27787     return SQLITE_OK;
27788   }
27789   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27790
27791   /* Check if a thread in this process holds such a lock */
27792   if( pFile->pInode->eFileLock>SHARED_LOCK ){
27793     reserved = 1;
27794   }
27795
27796   /* Otherwise see if some other process holds it.
27797    */
27798   if( !reserved ){
27799     /* lock the RESERVED byte */
27800     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27801     if( SQLITE_OK==lrc ){
27802       /* if we succeeded in taking the reserved lock, unlock it to restore
27803       ** the original state */
27804       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27805     } else {
27806       /* if we failed to get the lock then someone else must have it */
27807       reserved = 1;
27808     }
27809     if( IS_LOCK_ERROR(lrc) ){
27810       rc=lrc;
27811     }
27812   }
27813
27814   unixLeaveMutex();
27815   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27816
27817   *pResOut = reserved;
27818   return rc;
27819 }
27820
27821 /*
27822 ** Lock the file with the lock specified by parameter eFileLock - one
27823 ** of the following:
27824 **
27825 **     (1) SHARED_LOCK
27826 **     (2) RESERVED_LOCK
27827 **     (3) PENDING_LOCK
27828 **     (4) EXCLUSIVE_LOCK
27829 **
27830 ** Sometimes when requesting one lock state, additional lock states
27831 ** are inserted in between.  The locking might fail on one of the later
27832 ** transitions leaving the lock state different from what it started but
27833 ** still short of its goal.  The following chart shows the allowed
27834 ** transitions and the inserted intermediate states:
27835 **
27836 **    UNLOCKED -> SHARED
27837 **    SHARED -> RESERVED
27838 **    SHARED -> (PENDING) -> EXCLUSIVE
27839 **    RESERVED -> (PENDING) -> EXCLUSIVE
27840 **    PENDING -> EXCLUSIVE
27841 **
27842 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27843 ** routine to lower a locking level.
27844 */
27845 static int afpLock(sqlite3_file *id, int eFileLock){
27846   int rc = SQLITE_OK;
27847   unixFile *pFile = (unixFile*)id;
27848   unixInodeInfo *pInode = pFile->pInode;
27849   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27850
27851   assert( pFile );
27852   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27853            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27854            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27855
27856   /* If there is already a lock of this type or more restrictive on the
27857   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27858   ** unixEnterMutex() hasn't been called yet.
27859   */
27860   if( pFile->eFileLock>=eFileLock ){
27861     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
27862            azFileLock(eFileLock)));
27863     return SQLITE_OK;
27864   }
27865
27866   /* Make sure the locking sequence is correct
27867   **  (1) We never move from unlocked to anything higher than shared lock.
27868   **  (2) SQLite never explicitly requests a pendig lock.
27869   **  (3) A shared lock is always held when a reserve lock is requested.
27870   */
27871   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27872   assert( eFileLock!=PENDING_LOCK );
27873   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27874
27875   /* This mutex is needed because pFile->pInode is shared across threads
27876   */
27877   unixEnterMutex();
27878   pInode = pFile->pInode;
27879
27880   /* If some thread using this PID has a lock via a different unixFile*
27881   ** handle that precludes the requested lock, return BUSY.
27882   */
27883   if( (pFile->eFileLock!=pInode->eFileLock &&
27884        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27885      ){
27886     rc = SQLITE_BUSY;
27887     goto afp_end_lock;
27888   }
27889
27890   /* If a SHARED lock is requested, and some thread using this PID already
27891   ** has a SHARED or RESERVED lock, then increment reference counts and
27892   ** return SQLITE_OK.
27893   */
27894   if( eFileLock==SHARED_LOCK &&
27895      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27896     assert( eFileLock==SHARED_LOCK );
27897     assert( pFile->eFileLock==0 );
27898     assert( pInode->nShared>0 );
27899     pFile->eFileLock = SHARED_LOCK;
27900     pInode->nShared++;
27901     pInode->nLock++;
27902     goto afp_end_lock;
27903   }
27904
27905   /* A PENDING lock is needed before acquiring a SHARED lock and before
27906   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27907   ** be released.
27908   */
27909   if( eFileLock==SHARED_LOCK
27910       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27911   ){
27912     int failed;
27913     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27914     if (failed) {
27915       rc = failed;
27916       goto afp_end_lock;
27917     }
27918   }
27919
27920   /* If control gets to this point, then actually go ahead and make
27921   ** operating system calls for the specified lock.
27922   */
27923   if( eFileLock==SHARED_LOCK ){
27924     int lrc1, lrc2, lrc1Errno = 0;
27925     long lk, mask;
27926
27927     assert( pInode->nShared==0 );
27928     assert( pInode->eFileLock==0 );
27929
27930     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27931     /* Now get the read-lock SHARED_LOCK */
27932     /* note that the quality of the randomness doesn't matter that much */
27933     lk = random();
27934     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27935     lrc1 = afpSetLock(context->dbPath, pFile,
27936           SHARED_FIRST+pInode->sharedByte, 1, 1);
27937     if( IS_LOCK_ERROR(lrc1) ){
27938       lrc1Errno = pFile->lastErrno;
27939     }
27940     /* Drop the temporary PENDING lock */
27941     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27942
27943     if( IS_LOCK_ERROR(lrc1) ) {
27944       pFile->lastErrno = lrc1Errno;
27945       rc = lrc1;
27946       goto afp_end_lock;
27947     } else if( IS_LOCK_ERROR(lrc2) ){
27948       rc = lrc2;
27949       goto afp_end_lock;
27950     } else if( lrc1 != SQLITE_OK ) {
27951       rc = lrc1;
27952     } else {
27953       pFile->eFileLock = SHARED_LOCK;
27954       pInode->nLock++;
27955       pInode->nShared = 1;
27956     }
27957   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27958     /* We are trying for an exclusive lock but another thread in this
27959      ** same process is still holding a shared lock. */
27960     rc = SQLITE_BUSY;
27961   }else{
27962     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27963     ** assumed that there is a SHARED or greater lock on the file
27964     ** already.
27965     */
27966     int failed = 0;
27967     assert( 0!=pFile->eFileLock );
27968     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27969         /* Acquire a RESERVED lock */
27970         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27971       if( !failed ){
27972         context->reserved = 1;
27973       }
27974     }
27975     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27976       /* Acquire an EXCLUSIVE lock */
27977
27978       /* Remove the shared lock before trying the range.  we'll need to
27979       ** reestablish the shared lock if we can't get the  afpUnlock
27980       */
27981       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27982                          pInode->sharedByte, 1, 0)) ){
27983         int failed2 = SQLITE_OK;
27984         /* now attemmpt to get the exclusive lock range */
27985         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27986                                SHARED_SIZE, 1);
27987         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27988                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27989           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
27990           ** a critical I/O error
27991           */
27992           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27993                SQLITE_IOERR_LOCK;
27994           goto afp_end_lock;
27995         }
27996       }else{
27997         rc = failed;
27998       }
27999     }
28000     if( failed ){
28001       rc = failed;
28002     }
28003   }
28004
28005   if( rc==SQLITE_OK ){
28006     pFile->eFileLock = eFileLock;
28007     pInode->eFileLock = eFileLock;
28008   }else if( eFileLock==EXCLUSIVE_LOCK ){
28009     pFile->eFileLock = PENDING_LOCK;
28010     pInode->eFileLock = PENDING_LOCK;
28011   }
28012
28013 afp_end_lock:
28014   unixLeaveMutex();
28015   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
28016          rc==SQLITE_OK ? "ok" : "failed"));
28017   return rc;
28018 }
28019
28020 /*
28021 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28022 ** must be either NO_LOCK or SHARED_LOCK.
28023 **
28024 ** If the locking level of the file descriptor is already at or below
28025 ** the requested locking level, this routine is a no-op.
28026 */
28027 static int afpUnlock(sqlite3_file *id, int eFileLock) {
28028   int rc = SQLITE_OK;
28029   unixFile *pFile = (unixFile*)id;
28030   unixInodeInfo *pInode;
28031   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
28032   int skipShared = 0;
28033 #ifdef SQLITE_TEST
28034   int h = pFile->h;
28035 #endif
28036
28037   assert( pFile );
28038   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
28039            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
28040            getpid()));
28041
28042   assert( eFileLock<=SHARED_LOCK );
28043   if( pFile->eFileLock<=eFileLock ){
28044     return SQLITE_OK;
28045   }
28046   unixEnterMutex();
28047   pInode = pFile->pInode;
28048   assert( pInode->nShared!=0 );
28049   if( pFile->eFileLock>SHARED_LOCK ){
28050     assert( pInode->eFileLock==pFile->eFileLock );
28051     SimulateIOErrorBenign(1);
28052     SimulateIOError( h=(-1) )
28053     SimulateIOErrorBenign(0);
28054
28055 #ifdef SQLITE_DEBUG
28056     /* When reducing a lock such that other processes can start
28057     ** reading the database file again, make sure that the
28058     ** transaction counter was updated if any part of the database
28059     ** file changed.  If the transaction counter is not updated,
28060     ** other connections to the same file might not realize that
28061     ** the file has changed and hence might not know to flush their
28062     ** cache.  The use of a stale cache can lead to database corruption.
28063     */
28064     assert( pFile->inNormalWrite==0
28065            || pFile->dbUpdate==0
28066            || pFile->transCntrChng==1 );
28067     pFile->inNormalWrite = 0;
28068 #endif
28069
28070     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
28071       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
28072       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
28073         /* only re-establish the shared lock if necessary */
28074         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28075         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
28076       } else {
28077         skipShared = 1;
28078       }
28079     }
28080     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
28081       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
28082     }
28083     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
28084       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
28085       if( !rc ){
28086         context->reserved = 0;
28087       }
28088     }
28089     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
28090       pInode->eFileLock = SHARED_LOCK;
28091     }
28092   }
28093   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
28094
28095     /* Decrement the shared lock counter.  Release the lock using an
28096     ** OS call only when all threads in this same process have released
28097     ** the lock.
28098     */
28099     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28100     pInode->nShared--;
28101     if( pInode->nShared==0 ){
28102       SimulateIOErrorBenign(1);
28103       SimulateIOError( h=(-1) )
28104       SimulateIOErrorBenign(0);
28105       if( !skipShared ){
28106         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
28107       }
28108       if( !rc ){
28109         pInode->eFileLock = NO_LOCK;
28110         pFile->eFileLock = NO_LOCK;
28111       }
28112     }
28113     if( rc==SQLITE_OK ){
28114       pInode->nLock--;
28115       assert( pInode->nLock>=0 );
28116       if( pInode->nLock==0 ){
28117         closePendingFds(pFile);
28118       }
28119     }
28120   }
28121
28122   unixLeaveMutex();
28123   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
28124   return rc;
28125 }
28126
28127 /*
28128 ** Close a file & cleanup AFP specific locking context
28129 */
28130 static int afpClose(sqlite3_file *id) {
28131   int rc = SQLITE_OK;
28132   if( id ){
28133     unixFile *pFile = (unixFile*)id;
28134     afpUnlock(id, NO_LOCK);
28135     unixEnterMutex();
28136     if( pFile->pInode && pFile->pInode->nLock ){
28137       /* If there are outstanding locks, do not actually close the file just
28138       ** yet because that would clear those locks.  Instead, add the file
28139       ** descriptor to pInode->aPending.  It will be automatically closed when
28140       ** the last lock is cleared.
28141       */
28142       setPendingFd(pFile);
28143     }
28144     releaseInodeInfo(pFile);
28145     sqlite3_free(pFile->lockingContext);
28146     rc = closeUnixFile(id);
28147     unixLeaveMutex();
28148   }
28149   return rc;
28150 }
28151
28152 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28153 /*
28154 ** The code above is the AFP lock implementation.  The code is specific
28155 ** to MacOSX and does not work on other unix platforms.  No alternative
28156 ** is available.  If you don't compile for a mac, then the "unix-afp"
28157 ** VFS is not available.
28158 **
28159 ********************* End of the AFP lock implementation **********************
28160 ******************************************************************************/
28161
28162 /******************************************************************************
28163 *************************** Begin NFS Locking ********************************/
28164
28165 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28166 /*
28167  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28168  ** must be either NO_LOCK or SHARED_LOCK.
28169  **
28170  ** If the locking level of the file descriptor is already at or below
28171  ** the requested locking level, this routine is a no-op.
28172  */
28173 static int nfsUnlock(sqlite3_file *id, int eFileLock){
28174   return posixUnlock(id, eFileLock, 1);
28175 }
28176
28177 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28178 /*
28179 ** The code above is the NFS lock implementation.  The code is specific
28180 ** to MacOSX and does not work on other unix platforms.  No alternative
28181 ** is available.
28182 **
28183 ********************* End of the NFS lock implementation **********************
28184 ******************************************************************************/
28185
28186 /******************************************************************************
28187 **************** Non-locking sqlite3_file methods *****************************
28188 **
28189 ** The next division contains implementations for all methods of the
28190 ** sqlite3_file object other than the locking methods.  The locking
28191 ** methods were defined in divisions above (one locking method per
28192 ** division).  Those methods that are common to all locking modes
28193 ** are gather together into this division.
28194 */
28195
28196 /*
28197 ** Seek to the offset passed as the second argument, then read cnt
28198 ** bytes into pBuf. Return the number of bytes actually read.
28199 **
28200 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
28201 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
28202 ** one system to another.  Since SQLite does not define USE_PREAD
28203 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
28204 ** See tickets #2741 and #2681.
28205 **
28206 ** To avoid stomping the errno value on a failed read the lastErrno value
28207 ** is set before returning.
28208 */
28209 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
28210   int got;
28211   int prior = 0;
28212 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28213   i64 newOffset;
28214 #endif
28215   TIMER_START;
28216   assert( cnt==(cnt&0x1ffff) );
28217   cnt &= 0x1ffff;
28218   do{
28219 #if defined(USE_PREAD)
28220     got = osPread(id->h, pBuf, cnt, offset);
28221     SimulateIOError( got = -1 );
28222 #elif defined(USE_PREAD64)
28223     got = osPread64(id->h, pBuf, cnt, offset);
28224     SimulateIOError( got = -1 );
28225 #else
28226     newOffset = lseek(id->h, offset, SEEK_SET);
28227     SimulateIOError( newOffset-- );
28228     if( newOffset!=offset ){
28229       if( newOffset == -1 ){
28230         ((unixFile*)id)->lastErrno = errno;
28231       }else{
28232         ((unixFile*)id)->lastErrno = 0;
28233       }
28234       return -1;
28235     }
28236     got = osRead(id->h, pBuf, cnt);
28237 #endif
28238     if( got==cnt ) break;
28239     if( got<0 ){
28240       if( errno==EINTR ){ got = 1; continue; }
28241       prior = 0;
28242       ((unixFile*)id)->lastErrno = errno;
28243       break;
28244     }else if( got>0 ){
28245       cnt -= got;
28246       offset += got;
28247       prior += got;
28248       pBuf = (void*)(got + (char*)pBuf);
28249     }
28250   }while( got>0 );
28251   TIMER_END;
28252   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
28253             id->h, got+prior, offset-prior, TIMER_ELAPSED));
28254   return got+prior;
28255 }
28256
28257 /*
28258 ** Read data from a file into a buffer.  Return SQLITE_OK if all
28259 ** bytes were read successfully and SQLITE_IOERR if anything goes
28260 ** wrong.
28261 */
28262 static int unixRead(
28263   sqlite3_file *id,
28264   void *pBuf,
28265   int amt,
28266   sqlite3_int64 offset
28267 ){
28268   unixFile *pFile = (unixFile *)id;
28269   int got;
28270   assert( id );
28271
28272   /* If this is a database file (not a journal, master-journal or temp
28273   ** file), the bytes in the locking range should never be read or written. */
28274 #if 0
28275   assert( pFile->pUnused==0
28276        || offset>=PENDING_BYTE+512
28277        || offset+amt<=PENDING_BYTE
28278   );
28279 #endif
28280
28281   got = seekAndRead(pFile, offset, pBuf, amt);
28282   if( got==amt ){
28283     return SQLITE_OK;
28284   }else if( got<0 ){
28285     /* lastErrno set by seekAndRead */
28286     return SQLITE_IOERR_READ;
28287   }else{
28288     pFile->lastErrno = 0; /* not a system error */
28289     /* Unread parts of the buffer must be zero-filled */
28290     memset(&((char*)pBuf)[got], 0, amt-got);
28291     return SQLITE_IOERR_SHORT_READ;
28292   }
28293 }
28294
28295 /*
28296 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
28297 ** Return the number of bytes actually read.  Update the offset.
28298 **
28299 ** To avoid stomping the errno value on a failed write the lastErrno value
28300 ** is set before returning.
28301 */
28302 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28303   int got;
28304 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28305   i64 newOffset;
28306 #endif
28307   assert( cnt==(cnt&0x1ffff) );
28308   cnt &= 0x1ffff;
28309   TIMER_START;
28310 #if defined(USE_PREAD)
28311   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
28312 #elif defined(USE_PREAD64)
28313   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
28314 #else
28315   do{
28316     newOffset = lseek(id->h, offset, SEEK_SET);
28317     SimulateIOError( newOffset-- );
28318     if( newOffset!=offset ){
28319       if( newOffset == -1 ){
28320         ((unixFile*)id)->lastErrno = errno;
28321       }else{
28322         ((unixFile*)id)->lastErrno = 0;
28323       }
28324       return -1;
28325     }
28326     got = osWrite(id->h, pBuf, cnt);
28327   }while( got<0 && errno==EINTR );
28328 #endif
28329   TIMER_END;
28330   if( got<0 ){
28331     ((unixFile*)id)->lastErrno = errno;
28332   }
28333
28334   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
28335   return got;
28336 }
28337
28338
28339 /*
28340 ** Write data from a buffer into a file.  Return SQLITE_OK on success
28341 ** or some other error code on failure.
28342 */
28343 static int unixWrite(
28344   sqlite3_file *id,
28345   const void *pBuf,
28346   int amt,
28347   sqlite3_int64 offset
28348 ){
28349   unixFile *pFile = (unixFile*)id;
28350   int wrote = 0;
28351   assert( id );
28352   assert( amt>0 );
28353
28354   /* If this is a database file (not a journal, master-journal or temp
28355   ** file), the bytes in the locking range should never be read or written. */
28356 #if 0
28357   assert( pFile->pUnused==0
28358        || offset>=PENDING_BYTE+512
28359        || offset+amt<=PENDING_BYTE
28360   );
28361 #endif
28362
28363 #ifdef SQLITE_DEBUG
28364   /* If we are doing a normal write to a database file (as opposed to
28365   ** doing a hot-journal rollback or a write to some file other than a
28366   ** normal database file) then record the fact that the database
28367   ** has changed.  If the transaction counter is modified, record that
28368   ** fact too.
28369   */
28370   if( pFile->inNormalWrite ){
28371     pFile->dbUpdate = 1;  /* The database has been modified */
28372     if( offset<=24 && offset+amt>=27 ){
28373       int rc;
28374       char oldCntr[4];
28375       SimulateIOErrorBenign(1);
28376       rc = seekAndRead(pFile, 24, oldCntr, 4);
28377       SimulateIOErrorBenign(0);
28378       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28379         pFile->transCntrChng = 1;  /* The transaction counter has changed */
28380       }
28381     }
28382   }
28383 #endif
28384
28385   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28386     amt -= wrote;
28387     offset += wrote;
28388     pBuf = &((char*)pBuf)[wrote];
28389   }
28390   SimulateIOError(( wrote=(-1), amt=1 ));
28391   SimulateDiskfullError(( wrote=0, amt=1 ));
28392
28393   if( amt>0 ){
28394     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28395       /* lastErrno set by seekAndWrite */
28396       return SQLITE_IOERR_WRITE;
28397     }else{
28398       pFile->lastErrno = 0; /* not a system error */
28399       return SQLITE_FULL;
28400     }
28401   }
28402
28403   return SQLITE_OK;
28404 }
28405
28406 #ifdef SQLITE_TEST
28407 /*
28408 ** Count the number of fullsyncs and normal syncs.  This is used to test
28409 ** that syncs and fullsyncs are occurring at the right times.
28410 */
28411 SQLITE_API int sqlite3_sync_count = 0;
28412 SQLITE_API int sqlite3_fullsync_count = 0;
28413 #endif
28414
28415 /*
28416 ** We do not trust systems to provide a working fdatasync().  Some do.
28417 ** Others do no.  To be safe, we will stick with the (slightly slower)
28418 ** fsync(). If you know that your system does support fdatasync() correctly,
28419 ** then simply compile with -Dfdatasync=fdatasync
28420 */
28421 #if !defined(fdatasync)
28422 # define fdatasync fsync
28423 #endif
28424
28425 /*
28426 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28427 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
28428 ** only available on Mac OS X.  But that could change.
28429 */
28430 #ifdef F_FULLFSYNC
28431 # define HAVE_FULLFSYNC 1
28432 #else
28433 # define HAVE_FULLFSYNC 0
28434 #endif
28435
28436
28437 /*
28438 ** The fsync() system call does not work as advertised on many
28439 ** unix systems.  The following procedure is an attempt to make
28440 ** it work better.
28441 **
28442 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
28443 ** for testing when we want to run through the test suite quickly.
28444 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28445 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28446 ** or power failure will likely corrupt the database file.
28447 **
28448 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
28449 ** The idea behind dataOnly is that it should only write the file content
28450 ** to disk, not the inode.  We only set dataOnly if the file size is
28451 ** unchanged since the file size is part of the inode.  However,
28452 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
28453 ** file size has changed.  The only real difference between fdatasync()
28454 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
28455 ** inode if the mtime or owner or other inode attributes have changed.
28456 ** We only care about the file size, not the other file attributes, so
28457 ** as far as SQLite is concerned, an fdatasync() is always adequate.
28458 ** So, we always use fdatasync() if it is available, regardless of
28459 ** the value of the dataOnly flag.
28460 */
28461 static int full_fsync(int fd, int fullSync, int dataOnly){
28462   int rc;
28463
28464   /* The following "ifdef/elif/else/" block has the same structure as
28465   ** the one below. It is replicated here solely to avoid cluttering
28466   ** up the real code with the UNUSED_PARAMETER() macros.
28467   */
28468 #ifdef SQLITE_NO_SYNC
28469   UNUSED_PARAMETER(fd);
28470   UNUSED_PARAMETER(fullSync);
28471   UNUSED_PARAMETER(dataOnly);
28472 #elif HAVE_FULLFSYNC
28473   UNUSED_PARAMETER(dataOnly);
28474 #else
28475   UNUSED_PARAMETER(fullSync);
28476   UNUSED_PARAMETER(dataOnly);
28477 #endif
28478
28479   /* Record the number of times that we do a normal fsync() and
28480   ** FULLSYNC.  This is used during testing to verify that this procedure
28481   ** gets called with the correct arguments.
28482   */
28483 #ifdef SQLITE_TEST
28484   if( fullSync ) sqlite3_fullsync_count++;
28485   sqlite3_sync_count++;
28486 #endif
28487
28488   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28489   ** no-op
28490   */
28491 #ifdef SQLITE_NO_SYNC
28492   rc = SQLITE_OK;
28493 #elif HAVE_FULLFSYNC
28494   if( fullSync ){
28495     rc = osFcntl(fd, F_FULLFSYNC, 0);
28496   }else{
28497     rc = 1;
28498   }
28499   /* If the FULLFSYNC failed, fall back to attempting an fsync().
28500   ** It shouldn't be possible for fullfsync to fail on the local
28501   ** file system (on OSX), so failure indicates that FULLFSYNC
28502   ** isn't supported for this file system. So, attempt an fsync
28503   ** and (for now) ignore the overhead of a superfluous fcntl call.
28504   ** It'd be better to detect fullfsync support once and avoid
28505   ** the fcntl call every time sync is called.
28506   */
28507   if( rc ) rc = fsync(fd);
28508
28509 #elif defined(__APPLE__)
28510   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28511   ** so currently we default to the macro that redefines fdatasync to fsync
28512   */
28513   rc = fsync(fd);
28514 #else
28515   rc = fdatasync(fd);
28516 #if OS_VXWORKS
28517   if( rc==-1 && errno==ENOTSUP ){
28518     rc = fsync(fd);
28519   }
28520 #endif /* OS_VXWORKS */
28521 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28522
28523   if( OS_VXWORKS && rc!= -1 ){
28524     rc = 0;
28525   }
28526   return rc;
28527 }
28528
28529 /*
28530 ** Open a file descriptor to the directory containing file zFilename.
28531 ** If successful, *pFd is set to the opened file descriptor and
28532 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28533 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28534 ** value.
28535 **
28536 ** The directory file descriptor is used for only one thing - to
28537 ** fsync() a directory to make sure file creation and deletion events
28538 ** are flushed to disk.  Such fsyncs are not needed on newer
28539 ** journaling filesystems, but are required on older filesystems.
28540 **
28541 ** This routine can be overridden using the xSetSysCall interface.
28542 ** The ability to override this routine was added in support of the
28543 ** chromium sandbox.  Opening a directory is a security risk (we are
28544 ** told) so making it overrideable allows the chromium sandbox to
28545 ** replace this routine with a harmless no-op.  To make this routine
28546 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28547 ** *pFd set to a negative number.
28548 **
28549 ** If SQLITE_OK is returned, the caller is responsible for closing
28550 ** the file descriptor *pFd using close().
28551 */
28552 static int openDirectory(const char *zFilename, int *pFd){
28553   int ii;
28554   int fd = -1;
28555   char zDirname[MAX_PATHNAME+1];
28556
28557   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28558   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28559   if( ii>0 ){
28560     zDirname[ii] = '\0';
28561     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28562     if( fd>=0 ){
28563       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28564     }
28565   }
28566   *pFd = fd;
28567   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28568 }
28569
28570 /*
28571 ** Make sure all writes to a particular file are committed to disk.
28572 **
28573 ** If dataOnly==0 then both the file itself and its metadata (file
28574 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
28575 ** file data is synced.
28576 **
28577 ** Under Unix, also make sure that the directory entry for the file
28578 ** has been created by fsync-ing the directory that contains the file.
28579 ** If we do not do this and we encounter a power failure, the directory
28580 ** entry for the journal might not exist after we reboot.  The next
28581 ** SQLite to access the file will not know that the journal exists (because
28582 ** the directory entry for the journal was never created) and the transaction
28583 ** will not roll back - possibly leading to database corruption.
28584 */
28585 static int unixSync(sqlite3_file *id, int flags){
28586   int rc;
28587   unixFile *pFile = (unixFile*)id;
28588
28589   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28590   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28591
28592   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28593   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28594       || (flags&0x0F)==SQLITE_SYNC_FULL
28595   );
28596
28597   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28598   ** line is to test that doing so does not cause any problems.
28599   */
28600   SimulateDiskfullError( return SQLITE_FULL );
28601
28602   assert( pFile );
28603   OSTRACE(("SYNC    %-3d\n", pFile->h));
28604   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28605   SimulateIOError( rc=1 );
28606   if( rc ){
28607     pFile->lastErrno = errno;
28608     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28609   }
28610
28611   /* Also fsync the directory containing the file if the DIRSYNC flag
28612   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
28613   ** are unable to fsync a directory, so ignore errors on the fsync.
28614   */
28615   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28616     int dirfd;
28617     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28618             HAVE_FULLFSYNC, isFullsync));
28619     rc = osOpenDirectory(pFile->zPath, &dirfd);
28620     if( rc==SQLITE_OK && dirfd>=0 ){
28621       full_fsync(dirfd, 0, 0);
28622       robust_close(pFile, dirfd, __LINE__);
28623     }else if( rc==SQLITE_CANTOPEN ){
28624       rc = SQLITE_OK;
28625     }
28626     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28627   }
28628   return rc;
28629 }
28630
28631 /*
28632 ** Truncate an open file to a specified size
28633 */
28634 static int unixTruncate(sqlite3_file *id, i64 nByte){
28635   unixFile *pFile = (unixFile *)id;
28636   int rc;
28637   assert( pFile );
28638   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28639
28640   /* If the user has configured a chunk-size for this file, truncate the
28641   ** file so that it consists of an integer number of chunks (i.e. the
28642   ** actual file size after the operation may be larger than the requested
28643   ** size).
28644   */
28645   if( pFile->szChunk>0 ){
28646     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28647   }
28648
28649   rc = robust_ftruncate(pFile->h, (off_t)nByte);
28650   if( rc ){
28651     pFile->lastErrno = errno;
28652     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28653   }else{
28654 #ifdef SQLITE_DEBUG
28655     /* If we are doing a normal write to a database file (as opposed to
28656     ** doing a hot-journal rollback or a write to some file other than a
28657     ** normal database file) and we truncate the file to zero length,
28658     ** that effectively updates the change counter.  This might happen
28659     ** when restoring a database using the backup API from a zero-length
28660     ** source.
28661     */
28662     if( pFile->inNormalWrite && nByte==0 ){
28663       pFile->transCntrChng = 1;
28664     }
28665 #endif
28666
28667     return SQLITE_OK;
28668   }
28669 }
28670
28671 /*
28672 ** Determine the current size of a file in bytes
28673 */
28674 static int unixFileSize(sqlite3_file *id, i64 *pSize){
28675   int rc;
28676   struct stat buf;
28677   assert( id );
28678   rc = osFstat(((unixFile*)id)->h, &buf);
28679   SimulateIOError( rc=1 );
28680   if( rc!=0 ){
28681     ((unixFile*)id)->lastErrno = errno;
28682     return SQLITE_IOERR_FSTAT;
28683   }
28684   *pSize = buf.st_size;
28685
28686   /* When opening a zero-size database, the findInodeInfo() procedure
28687   ** writes a single byte into that file in order to work around a bug
28688   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
28689   ** layers, we need to report this file size as zero even though it is
28690   ** really 1.   Ticket #3260.
28691   */
28692   if( *pSize==1 ) *pSize = 0;
28693
28694
28695   return SQLITE_OK;
28696 }
28697
28698 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28699 /*
28700 ** Handler for proxy-locking file-control verbs.  Defined below in the
28701 ** proxying locking division.
28702 */
28703 static int proxyFileControl(sqlite3_file*,int,void*);
28704 #endif
28705
28706 /*
28707 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28708 ** file-control operation.  Enlarge the database to nBytes in size
28709 ** (rounded up to the next chunk-size).  If the database is already
28710 ** nBytes or larger, this routine is a no-op.
28711 */
28712 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28713   if( pFile->szChunk>0 ){
28714     i64 nSize;                    /* Required file size */
28715     struct stat buf;              /* Used to hold return values of fstat() */
28716
28717     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28718
28719     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28720     if( nSize>(i64)buf.st_size ){
28721
28722 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28723       /* The code below is handling the return value of osFallocate()
28724       ** correctly. posix_fallocate() is defined to "returns zero on success,
28725       ** or an error number on  failure". See the manpage for details. */
28726       int err;
28727       do{
28728         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28729       }while( err==EINTR );
28730       if( err ) return SQLITE_IOERR_WRITE;
28731 #else
28732       /* If the OS does not have posix_fallocate(), fake it. First use
28733       ** ftruncate() to set the file size, then write a single byte to
28734       ** the last byte in each block within the extended region. This
28735       ** is the same technique used by glibc to implement posix_fallocate()
28736       ** on systems that do not have a real fallocate() system call.
28737       */
28738       int nBlk = buf.st_blksize;  /* File-system block size */
28739       i64 iWrite;                 /* Next offset to write to */
28740
28741       if( robust_ftruncate(pFile->h, nSize) ){
28742         pFile->lastErrno = errno;
28743         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28744       }
28745       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28746       while( iWrite<nSize ){
28747         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28748         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28749         iWrite += nBlk;
28750       }
28751 #endif
28752     }
28753   }
28754
28755   return SQLITE_OK;
28756 }
28757
28758 /*
28759 ** If *pArg is inititially negative then this is a query.  Set *pArg to
28760 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
28761 **
28762 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
28763 */
28764 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
28765   if( *pArg<0 ){
28766     *pArg = (pFile->ctrlFlags & mask)!=0;
28767   }else if( (*pArg)==0 ){
28768     pFile->ctrlFlags &= ~mask;
28769   }else{
28770     pFile->ctrlFlags |= mask;
28771   }
28772 }
28773
28774 /* Forward declaration */
28775 static int unixGetTempname(int nBuf, char *zBuf);
28776
28777 /*
28778 ** Information and control of an open file handle.
28779 */
28780 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28781   unixFile *pFile = (unixFile*)id;
28782   switch( op ){
28783     case SQLITE_FCNTL_LOCKSTATE: {
28784       *(int*)pArg = pFile->eFileLock;
28785       return SQLITE_OK;
28786     }
28787     case SQLITE_LAST_ERRNO: {
28788       *(int*)pArg = pFile->lastErrno;
28789       return SQLITE_OK;
28790     }
28791     case SQLITE_FCNTL_CHUNK_SIZE: {
28792       pFile->szChunk = *(int *)pArg;
28793       return SQLITE_OK;
28794     }
28795     case SQLITE_FCNTL_SIZE_HINT: {
28796       int rc;
28797       SimulateIOErrorBenign(1);
28798       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28799       SimulateIOErrorBenign(0);
28800       return rc;
28801     }
28802     case SQLITE_FCNTL_PERSIST_WAL: {
28803       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
28804       return SQLITE_OK;
28805     }
28806     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
28807       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
28808       return SQLITE_OK;
28809     }
28810     case SQLITE_FCNTL_VFSNAME: {
28811       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
28812       return SQLITE_OK;
28813     }
28814     case SQLITE_FCNTL_TEMPFILENAME: {
28815       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
28816       if( zTFile ){
28817         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
28818         *(char**)pArg = zTFile;
28819       }
28820       return SQLITE_OK;
28821     }
28822 #ifdef SQLITE_DEBUG
28823     /* The pager calls this method to signal that it has done
28824     ** a rollback and that the database is therefore unchanged and
28825     ** it hence it is OK for the transaction change counter to be
28826     ** unchanged.
28827     */
28828     case SQLITE_FCNTL_DB_UNCHANGED: {
28829       ((unixFile*)id)->dbUpdate = 0;
28830       return SQLITE_OK;
28831     }
28832 #endif
28833 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28834     case SQLITE_SET_LOCKPROXYFILE:
28835     case SQLITE_GET_LOCKPROXYFILE: {
28836       return proxyFileControl(id,op,pArg);
28837     }
28838 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28839   }
28840   return SQLITE_NOTFOUND;
28841 }
28842
28843 /*
28844 ** Return the sector size in bytes of the underlying block device for
28845 ** the specified file. This is almost always 512 bytes, but may be
28846 ** larger for some devices.
28847 **
28848 ** SQLite code assumes this function cannot fail. It also assumes that
28849 ** if two files are created in the same file-system directory (i.e.
28850 ** a database and its journal file) that the sector size will be the
28851 ** same for both.
28852 */
28853 #ifndef __QNXNTO__
28854 static int unixSectorSize(sqlite3_file *NotUsed){
28855   UNUSED_PARAMETER(NotUsed);
28856   return SQLITE_DEFAULT_SECTOR_SIZE;
28857 }
28858 #endif
28859
28860 /*
28861 ** The following version of unixSectorSize() is optimized for QNX.
28862 */
28863 #ifdef __QNXNTO__
28864 #include <sys/dcmd_blk.h>
28865 #include <sys/statvfs.h>
28866 static int unixSectorSize(sqlite3_file *id){
28867   unixFile *pFile = (unixFile*)id;
28868   if( pFile->sectorSize == 0 ){
28869     struct statvfs fsInfo;
28870
28871     /* Set defaults for non-supported filesystems */
28872     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28873     pFile->deviceCharacteristics = 0;
28874     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
28875       return pFile->sectorSize;
28876     }
28877
28878     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
28879       pFile->sectorSize = fsInfo.f_bsize;
28880       pFile->deviceCharacteristics =
28881         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
28882         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28883                                       ** the write succeeds */
28884         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28885                                       ** so it is ordered */
28886         0;
28887     }else if( strstr(fsInfo.f_basetype, "etfs") ){
28888       pFile->sectorSize = fsInfo.f_bsize;
28889       pFile->deviceCharacteristics =
28890         /* etfs cluster size writes are atomic */
28891         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
28892         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28893                                       ** the write succeeds */
28894         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28895                                       ** so it is ordered */
28896         0;
28897     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
28898       pFile->sectorSize = fsInfo.f_bsize;
28899       pFile->deviceCharacteristics =
28900         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
28901         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28902                                       ** the write succeeds */
28903         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28904                                       ** so it is ordered */
28905         0;
28906     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
28907       pFile->sectorSize = fsInfo.f_bsize;
28908       pFile->deviceCharacteristics =
28909         /* full bitset of atomics from max sector size and smaller */
28910         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28911         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28912                                       ** so it is ordered */
28913         0;
28914     }else if( strstr(fsInfo.f_basetype, "dos") ){
28915       pFile->sectorSize = fsInfo.f_bsize;
28916       pFile->deviceCharacteristics =
28917         /* full bitset of atomics from max sector size and smaller */
28918         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
28919         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
28920                                       ** so it is ordered */
28921         0;
28922     }else{
28923       pFile->deviceCharacteristics =
28924         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
28925         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
28926                                       ** the write succeeds */
28927         0;
28928     }
28929   }
28930   /* Last chance verification.  If the sector size isn't a multiple of 512
28931   ** then it isn't valid.*/
28932   if( pFile->sectorSize % 512 != 0 ){
28933     pFile->deviceCharacteristics = 0;
28934     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
28935   }
28936   return pFile->sectorSize;
28937 }
28938 #endif /* __QNXNTO__ */
28939
28940 /*
28941 ** Return the device characteristics for the file.
28942 **
28943 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
28944 ** However, that choice is contraversial since technically the underlying
28945 ** file system does not always provide powersafe overwrites.  (In other
28946 ** words, after a power-loss event, parts of the file that were never
28947 ** written might end up being altered.)  However, non-PSOW behavior is very,
28948 ** very rare.  And asserting PSOW makes a large reduction in the amount
28949 ** of required I/O for journaling, since a lot of padding is eliminated.
28950 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
28951 ** available to turn it off and URI query parameter available to turn it off.
28952 */
28953 static int unixDeviceCharacteristics(sqlite3_file *id){
28954   unixFile *p = (unixFile*)id;
28955   int rc = 0;
28956 #ifdef __QNXNTO__
28957   if( p->sectorSize==0 ) unixSectorSize(id);
28958   rc = p->deviceCharacteristics;
28959 #endif
28960   if( p->ctrlFlags & UNIXFILE_PSOW ){
28961     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
28962   }
28963   return rc;
28964 }
28965
28966 #ifndef SQLITE_OMIT_WAL
28967
28968
28969 /*
28970 ** Object used to represent an shared memory buffer.
28971 **
28972 ** When multiple threads all reference the same wal-index, each thread
28973 ** has its own unixShm object, but they all point to a single instance
28974 ** of this unixShmNode object.  In other words, each wal-index is opened
28975 ** only once per process.
28976 **
28977 ** Each unixShmNode object is connected to a single unixInodeInfo object.
28978 ** We could coalesce this object into unixInodeInfo, but that would mean
28979 ** every open file that does not use shared memory (in other words, most
28980 ** open files) would have to carry around this extra information.  So
28981 ** the unixInodeInfo object contains a pointer to this unixShmNode object
28982 ** and the unixShmNode object is created only when needed.
28983 **
28984 ** unixMutexHeld() must be true when creating or destroying
28985 ** this object or while reading or writing the following fields:
28986 **
28987 **      nRef
28988 **
28989 ** The following fields are read-only after the object is created:
28990 **
28991 **      fid
28992 **      zFilename
28993 **
28994 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28995 ** unixMutexHeld() is true when reading or writing any other field
28996 ** in this structure.
28997 */
28998 struct unixShmNode {
28999   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
29000   sqlite3_mutex *mutex;      /* Mutex to access this object */
29001   char *zFilename;           /* Name of the mmapped file */
29002   int h;                     /* Open file descriptor */
29003   int szRegion;              /* Size of shared-memory regions */
29004   u16 nRegion;               /* Size of array apRegion */
29005   u8 isReadonly;             /* True if read-only */
29006   char **apRegion;           /* Array of mapped shared-memory regions */
29007   int nRef;                  /* Number of unixShm objects pointing to this */
29008   unixShm *pFirst;           /* All unixShm objects pointing to this */
29009 #ifdef SQLITE_DEBUG
29010   u8 exclMask;               /* Mask of exclusive locks held */
29011   u8 sharedMask;             /* Mask of shared locks held */
29012   u8 nextShmId;              /* Next available unixShm.id value */
29013 #endif
29014 };
29015
29016 /*
29017 ** Structure used internally by this VFS to record the state of an
29018 ** open shared memory connection.
29019 **
29020 ** The following fields are initialized when this object is created and
29021 ** are read-only thereafter:
29022 **
29023 **    unixShm.pFile
29024 **    unixShm.id
29025 **
29026 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
29027 ** while accessing any read/write fields.
29028 */
29029 struct unixShm {
29030   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
29031   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
29032   u8 hasMutex;               /* True if holding the unixShmNode mutex */
29033   u8 id;                     /* Id of this connection within its unixShmNode */
29034   u16 sharedMask;            /* Mask of shared locks held */
29035   u16 exclMask;              /* Mask of exclusive locks held */
29036 };
29037
29038 /*
29039 ** Constants used for locking
29040 */
29041 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
29042 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
29043
29044 /*
29045 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
29046 **
29047 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
29048 ** otherwise.
29049 */
29050 static int unixShmSystemLock(
29051   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
29052   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
29053   int ofst,              /* First byte of the locking range */
29054   int n                  /* Number of bytes to lock */
29055 ){
29056   struct flock f;       /* The posix advisory locking structure */
29057   int rc = SQLITE_OK;   /* Result code form fcntl() */
29058
29059   /* Access to the unixShmNode object is serialized by the caller */
29060   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
29061
29062   /* Shared locks never span more than one byte */
29063   assert( n==1 || lockType!=F_RDLCK );
29064
29065   /* Locks are within range */
29066   assert( n>=1 && n<SQLITE_SHM_NLOCK );
29067
29068   if( pShmNode->h>=0 ){
29069     /* Initialize the locking parameters */
29070     memset(&f, 0, sizeof(f));
29071     f.l_type = lockType;
29072     f.l_whence = SEEK_SET;
29073     f.l_start = ofst;
29074     f.l_len = n;
29075
29076     rc = osFcntl(pShmNode->h, F_SETLK, &f);
29077     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
29078   }
29079
29080   /* Update the global lock state and do debug tracing */
29081 #ifdef SQLITE_DEBUG
29082   { u16 mask;
29083   OSTRACE(("SHM-LOCK "));
29084   mask = (1<<(ofst+n)) - (1<<ofst);
29085   if( rc==SQLITE_OK ){
29086     if( lockType==F_UNLCK ){
29087       OSTRACE(("unlock %d ok", ofst));
29088       pShmNode->exclMask &= ~mask;
29089       pShmNode->sharedMask &= ~mask;
29090     }else if( lockType==F_RDLCK ){
29091       OSTRACE(("read-lock %d ok", ofst));
29092       pShmNode->exclMask &= ~mask;
29093       pShmNode->sharedMask |= mask;
29094     }else{
29095       assert( lockType==F_WRLCK );
29096       OSTRACE(("write-lock %d ok", ofst));
29097       pShmNode->exclMask |= mask;
29098       pShmNode->sharedMask &= ~mask;
29099     }
29100   }else{
29101     if( lockType==F_UNLCK ){
29102       OSTRACE(("unlock %d failed", ofst));
29103     }else if( lockType==F_RDLCK ){
29104       OSTRACE(("read-lock failed"));
29105     }else{
29106       assert( lockType==F_WRLCK );
29107       OSTRACE(("write-lock %d failed", ofst));
29108     }
29109   }
29110   OSTRACE((" - afterwards %03x,%03x\n",
29111            pShmNode->sharedMask, pShmNode->exclMask));
29112   }
29113 #endif
29114
29115   return rc;
29116 }
29117
29118
29119 /*
29120 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
29121 **
29122 ** This is not a VFS shared-memory method; it is a utility function called
29123 ** by VFS shared-memory methods.
29124 */
29125 static void unixShmPurge(unixFile *pFd){
29126   unixShmNode *p = pFd->pInode->pShmNode;
29127   assert( unixMutexHeld() );
29128   if( p && p->nRef==0 ){
29129     int i;
29130     assert( p->pInode==pFd->pInode );
29131     sqlite3_mutex_free(p->mutex);
29132     for(i=0; i<p->nRegion; i++){
29133       if( p->h>=0 ){
29134         munmap(p->apRegion[i], p->szRegion);
29135       }else{
29136         sqlite3_free(p->apRegion[i]);
29137       }
29138     }
29139     sqlite3_free(p->apRegion);
29140     if( p->h>=0 ){
29141       robust_close(pFd, p->h, __LINE__);
29142       p->h = -1;
29143     }
29144     p->pInode->pShmNode = 0;
29145     sqlite3_free(p);
29146   }
29147 }
29148
29149 /*
29150 ** Open a shared-memory area associated with open database file pDbFd.
29151 ** This particular implementation uses mmapped files.
29152 **
29153 ** The file used to implement shared-memory is in the same directory
29154 ** as the open database file and has the same name as the open database
29155 ** file with the "-shm" suffix added.  For example, if the database file
29156 ** is "/home/user1/config.db" then the file that is created and mmapped
29157 ** for shared memory will be called "/home/user1/config.db-shm".
29158 **
29159 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
29160 ** some other tmpfs mount. But if a file in a different directory
29161 ** from the database file is used, then differing access permissions
29162 ** or a chroot() might cause two different processes on the same
29163 ** database to end up using different files for shared memory -
29164 ** meaning that their memory would not really be shared - resulting
29165 ** in database corruption.  Nevertheless, this tmpfs file usage
29166 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
29167 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
29168 ** option results in an incompatible build of SQLite;  builds of SQLite
29169 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
29170 ** same database file at the same time, database corruption will likely
29171 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
29172 ** "unsupported" and may go away in a future SQLite release.
29173 **
29174 ** When opening a new shared-memory file, if no other instances of that
29175 ** file are currently open, in this process or in other processes, then
29176 ** the file must be truncated to zero length or have its header cleared.
29177 **
29178 ** If the original database file (pDbFd) is using the "unix-excl" VFS
29179 ** that means that an exclusive lock is held on the database file and
29180 ** that no other processes are able to read or write the database.  In
29181 ** that case, we do not really need shared memory.  No shared memory
29182 ** file is created.  The shared memory will be simulated with heap memory.
29183 */
29184 static int unixOpenSharedMemory(unixFile *pDbFd){
29185   struct unixShm *p = 0;          /* The connection to be opened */
29186   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
29187   int rc;                         /* Result code */
29188   unixInodeInfo *pInode;          /* The inode of fd */
29189   char *zShmFilename;             /* Name of the file used for SHM */
29190   int nShmFilename;               /* Size of the SHM filename in bytes */
29191
29192   /* Allocate space for the new unixShm object. */
29193   p = sqlite3_malloc( sizeof(*p) );
29194   if( p==0 ) return SQLITE_NOMEM;
29195   memset(p, 0, sizeof(*p));
29196   assert( pDbFd->pShm==0 );
29197
29198   /* Check to see if a unixShmNode object already exists. Reuse an existing
29199   ** one if present. Create a new one if necessary.
29200   */
29201   unixEnterMutex();
29202   pInode = pDbFd->pInode;
29203   pShmNode = pInode->pShmNode;
29204   if( pShmNode==0 ){
29205     struct stat sStat;                 /* fstat() info for database file */
29206
29207     /* Call fstat() to figure out the permissions on the database file. If
29208     ** a new *-shm file is created, an attempt will be made to create it
29209     ** with the same permissions.
29210     */
29211     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
29212       rc = SQLITE_IOERR_FSTAT;
29213       goto shm_open_err;
29214     }
29215
29216 #ifdef SQLITE_SHM_DIRECTORY
29217     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
29218 #else
29219     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
29220 #endif
29221     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
29222     if( pShmNode==0 ){
29223       rc = SQLITE_NOMEM;
29224       goto shm_open_err;
29225     }
29226     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
29227     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
29228 #ifdef SQLITE_SHM_DIRECTORY
29229     sqlite3_snprintf(nShmFilename, zShmFilename,
29230                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
29231                      (u32)sStat.st_ino, (u32)sStat.st_dev);
29232 #else
29233     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
29234     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
29235 #endif
29236     pShmNode->h = -1;
29237     pDbFd->pInode->pShmNode = pShmNode;
29238     pShmNode->pInode = pDbFd->pInode;
29239     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
29240     if( pShmNode->mutex==0 ){
29241       rc = SQLITE_NOMEM;
29242       goto shm_open_err;
29243     }
29244
29245     if( pInode->bProcessLock==0 ){
29246       int openFlags = O_RDWR | O_CREAT;
29247       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
29248         openFlags = O_RDONLY;
29249         pShmNode->isReadonly = 1;
29250       }
29251       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
29252       if( pShmNode->h<0 ){
29253         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
29254         goto shm_open_err;
29255       }
29256
29257       /* If this process is running as root, make sure that the SHM file
29258       ** is owned by the same user that owns the original database.  Otherwise,
29259       ** the original owner will not be able to connect.
29260       */
29261       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
29262
29263       /* Check to see if another process is holding the dead-man switch.
29264       ** If not, truncate the file to zero length.
29265       */
29266       rc = SQLITE_OK;
29267       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
29268         if( robust_ftruncate(pShmNode->h, 0) ){
29269           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
29270         }
29271       }
29272       if( rc==SQLITE_OK ){
29273         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
29274       }
29275       if( rc ) goto shm_open_err;
29276     }
29277   }
29278
29279   /* Make the new connection a child of the unixShmNode */
29280   p->pShmNode = pShmNode;
29281 #ifdef SQLITE_DEBUG
29282   p->id = pShmNode->nextShmId++;
29283 #endif
29284   pShmNode->nRef++;
29285   pDbFd->pShm = p;
29286   unixLeaveMutex();
29287
29288   /* The reference count on pShmNode has already been incremented under
29289   ** the cover of the unixEnterMutex() mutex and the pointer from the
29290   ** new (struct unixShm) object to the pShmNode has been set. All that is
29291   ** left to do is to link the new object into the linked list starting
29292   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
29293   ** mutex.
29294   */
29295   sqlite3_mutex_enter(pShmNode->mutex);
29296   p->pNext = pShmNode->pFirst;
29297   pShmNode->pFirst = p;
29298   sqlite3_mutex_leave(pShmNode->mutex);
29299   return SQLITE_OK;
29300
29301   /* Jump here on any error */
29302 shm_open_err:
29303   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
29304   sqlite3_free(p);
29305   unixLeaveMutex();
29306   return rc;
29307 }
29308
29309 /*
29310 ** This function is called to obtain a pointer to region iRegion of the
29311 ** shared-memory associated with the database file fd. Shared-memory regions
29312 ** are numbered starting from zero. Each shared-memory region is szRegion
29313 ** bytes in size.
29314 **
29315 ** If an error occurs, an error code is returned and *pp is set to NULL.
29316 **
29317 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29318 ** region has not been allocated (by any client, including one running in a
29319 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
29320 ** bExtend is non-zero and the requested shared-memory region has not yet
29321 ** been allocated, it is allocated by this function.
29322 **
29323 ** If the shared-memory region has already been allocated or is allocated by
29324 ** this call as described above, then it is mapped into this processes
29325 ** address space (if it is not already), *pp is set to point to the mapped
29326 ** memory and SQLITE_OK returned.
29327 */
29328 static int unixShmMap(
29329   sqlite3_file *fd,               /* Handle open on database file */
29330   int iRegion,                    /* Region to retrieve */
29331   int szRegion,                   /* Size of regions */
29332   int bExtend,                    /* True to extend file if necessary */
29333   void volatile **pp              /* OUT: Mapped memory */
29334 ){
29335   unixFile *pDbFd = (unixFile*)fd;
29336   unixShm *p;
29337   unixShmNode *pShmNode;
29338   int rc = SQLITE_OK;
29339
29340   /* If the shared-memory file has not yet been opened, open it now. */
29341   if( pDbFd->pShm==0 ){
29342     rc = unixOpenSharedMemory(pDbFd);
29343     if( rc!=SQLITE_OK ) return rc;
29344   }
29345
29346   p = pDbFd->pShm;
29347   pShmNode = p->pShmNode;
29348   sqlite3_mutex_enter(pShmNode->mutex);
29349   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29350   assert( pShmNode->pInode==pDbFd->pInode );
29351   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29352   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29353
29354   if( pShmNode->nRegion<=iRegion ){
29355     char **apNew;                      /* New apRegion[] array */
29356     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
29357     struct stat sStat;                 /* Used by fstat() */
29358
29359     pShmNode->szRegion = szRegion;
29360
29361     if( pShmNode->h>=0 ){
29362       /* The requested region is not mapped into this processes address space.
29363       ** Check to see if it has been allocated (i.e. if the wal-index file is
29364       ** large enough to contain the requested region).
29365       */
29366       if( osFstat(pShmNode->h, &sStat) ){
29367         rc = SQLITE_IOERR_SHMSIZE;
29368         goto shmpage_out;
29369       }
29370
29371       if( sStat.st_size<nByte ){
29372         /* The requested memory region does not exist. If bExtend is set to
29373         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29374         **
29375         ** Alternatively, if bExtend is true, use ftruncate() to allocate
29376         ** the requested memory region.
29377         */
29378         if( !bExtend ) goto shmpage_out;
29379 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29380         if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
29381           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
29382                             pShmNode->zFilename);
29383           goto shmpage_out;
29384         }
29385 #else
29386         if( robust_ftruncate(pShmNode->h, nByte) ){
29387           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
29388                             pShmNode->zFilename);
29389           goto shmpage_out;
29390         }
29391 #endif
29392       }
29393     }
29394
29395     /* Map the requested memory region into this processes address space. */
29396     apNew = (char **)sqlite3_realloc(
29397         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
29398     );
29399     if( !apNew ){
29400       rc = SQLITE_IOERR_NOMEM;
29401       goto shmpage_out;
29402     }
29403     pShmNode->apRegion = apNew;
29404     while(pShmNode->nRegion<=iRegion){
29405       void *pMem;
29406       if( pShmNode->h>=0 ){
29407         pMem = mmap(0, szRegion,
29408             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
29409             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
29410         );
29411         if( pMem==MAP_FAILED ){
29412           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29413           goto shmpage_out;
29414         }
29415       }else{
29416         pMem = sqlite3_malloc(szRegion);
29417         if( pMem==0 ){
29418           rc = SQLITE_NOMEM;
29419           goto shmpage_out;
29420         }
29421         memset(pMem, 0, szRegion);
29422       }
29423       pShmNode->apRegion[pShmNode->nRegion] = pMem;
29424       pShmNode->nRegion++;
29425     }
29426   }
29427
29428 shmpage_out:
29429   if( pShmNode->nRegion>iRegion ){
29430     *pp = pShmNode->apRegion[iRegion];
29431   }else{
29432     *pp = 0;
29433   }
29434   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29435   sqlite3_mutex_leave(pShmNode->mutex);
29436   return rc;
29437 }
29438
29439 /*
29440 ** Change the lock state for a shared-memory segment.
29441 **
29442 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29443 ** different here than in posix.  In xShmLock(), one can go from unlocked
29444 ** to shared and back or from unlocked to exclusive and back.  But one may
29445 ** not go from shared to exclusive or from exclusive to shared.
29446 */
29447 static int unixShmLock(
29448   sqlite3_file *fd,          /* Database file holding the shared memory */
29449   int ofst,                  /* First lock to acquire or release */
29450   int n,                     /* Number of locks to acquire or release */
29451   int flags                  /* What to do with the lock */
29452 ){
29453   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
29454   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
29455   unixShm *pX;                          /* For looping over all siblings */
29456   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
29457   int rc = SQLITE_OK;                   /* Result code */
29458   u16 mask;                             /* Mask of locks to take or release */
29459
29460   assert( pShmNode==pDbFd->pInode->pShmNode );
29461   assert( pShmNode->pInode==pDbFd->pInode );
29462   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29463   assert( n>=1 );
29464   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29465        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29466        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29467        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29468   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29469   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29470   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29471
29472   mask = (1<<(ofst+n)) - (1<<ofst);
29473   assert( n>1 || mask==(1<<ofst) );
29474   sqlite3_mutex_enter(pShmNode->mutex);
29475   if( flags & SQLITE_SHM_UNLOCK ){
29476     u16 allMask = 0; /* Mask of locks held by siblings */
29477
29478     /* See if any siblings hold this same lock */
29479     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29480       if( pX==p ) continue;
29481       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29482       allMask |= pX->sharedMask;
29483     }
29484
29485     /* Unlock the system-level locks */
29486     if( (mask & allMask)==0 ){
29487       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29488     }else{
29489       rc = SQLITE_OK;
29490     }
29491
29492     /* Undo the local locks */
29493     if( rc==SQLITE_OK ){
29494       p->exclMask &= ~mask;
29495       p->sharedMask &= ~mask;
29496     }
29497   }else if( flags & SQLITE_SHM_SHARED ){
29498     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
29499
29500     /* Find out which shared locks are already held by sibling connections.
29501     ** If any sibling already holds an exclusive lock, go ahead and return
29502     ** SQLITE_BUSY.
29503     */
29504     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29505       if( (pX->exclMask & mask)!=0 ){
29506         rc = SQLITE_BUSY;
29507         break;
29508       }
29509       allShared |= pX->sharedMask;
29510     }
29511
29512     /* Get shared locks at the system level, if necessary */
29513     if( rc==SQLITE_OK ){
29514       if( (allShared & mask)==0 ){
29515         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29516       }else{
29517         rc = SQLITE_OK;
29518       }
29519     }
29520
29521     /* Get the local shared locks */
29522     if( rc==SQLITE_OK ){
29523       p->sharedMask |= mask;
29524     }
29525   }else{
29526     /* Make sure no sibling connections hold locks that will block this
29527     ** lock.  If any do, return SQLITE_BUSY right away.
29528     */
29529     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29530       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
29531         rc = SQLITE_BUSY;
29532         break;
29533       }
29534     }
29535
29536     /* Get the exclusive locks at the system level.  Then if successful
29537     ** also mark the local connection as being locked.
29538     */
29539     if( rc==SQLITE_OK ){
29540       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
29541       if( rc==SQLITE_OK ){
29542         assert( (p->sharedMask & mask)==0 );
29543         p->exclMask |= mask;
29544       }
29545     }
29546   }
29547   sqlite3_mutex_leave(pShmNode->mutex);
29548   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
29549            p->id, getpid(), p->sharedMask, p->exclMask));
29550   return rc;
29551 }
29552
29553 /*
29554 ** Implement a memory barrier or memory fence on shared memory.
29555 **
29556 ** All loads and stores begun before the barrier must complete before
29557 ** any load or store begun after the barrier.
29558 */
29559 static void unixShmBarrier(
29560   sqlite3_file *fd                /* Database file holding the shared memory */
29561 ){
29562   UNUSED_PARAMETER(fd);
29563   unixEnterMutex();
29564   unixLeaveMutex();
29565 }
29566
29567 /*
29568 ** Close a connection to shared-memory.  Delete the underlying
29569 ** storage if deleteFlag is true.
29570 **
29571 ** If there is no shared memory associated with the connection then this
29572 ** routine is a harmless no-op.
29573 */
29574 static int unixShmUnmap(
29575   sqlite3_file *fd,               /* The underlying database file */
29576   int deleteFlag                  /* Delete shared-memory if true */
29577 ){
29578   unixShm *p;                     /* The connection to be closed */
29579   unixShmNode *pShmNode;          /* The underlying shared-memory file */
29580   unixShm **pp;                   /* For looping over sibling connections */
29581   unixFile *pDbFd;                /* The underlying database file */
29582
29583   pDbFd = (unixFile*)fd;
29584   p = pDbFd->pShm;
29585   if( p==0 ) return SQLITE_OK;
29586   pShmNode = p->pShmNode;
29587
29588   assert( pShmNode==pDbFd->pInode->pShmNode );
29589   assert( pShmNode->pInode==pDbFd->pInode );
29590
29591   /* Remove connection p from the set of connections associated
29592   ** with pShmNode */
29593   sqlite3_mutex_enter(pShmNode->mutex);
29594   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
29595   *pp = p->pNext;
29596
29597   /* Free the connection p */
29598   sqlite3_free(p);
29599   pDbFd->pShm = 0;
29600   sqlite3_mutex_leave(pShmNode->mutex);
29601
29602   /* If pShmNode->nRef has reached 0, then close the underlying
29603   ** shared-memory file, too */
29604   unixEnterMutex();
29605   assert( pShmNode->nRef>0 );
29606   pShmNode->nRef--;
29607   if( pShmNode->nRef==0 ){
29608     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
29609     unixShmPurge(pDbFd);
29610   }
29611   unixLeaveMutex();
29612
29613   return SQLITE_OK;
29614 }
29615
29616
29617 #else
29618 # define unixShmMap     0
29619 # define unixShmLock    0
29620 # define unixShmBarrier 0
29621 # define unixShmUnmap   0
29622 #endif /* #ifndef SQLITE_OMIT_WAL */
29623
29624 /*
29625 ** Here ends the implementation of all sqlite3_file methods.
29626 **
29627 ********************** End sqlite3_file Methods *******************************
29628 ******************************************************************************/
29629
29630 /*
29631 ** This division contains definitions of sqlite3_io_methods objects that
29632 ** implement various file locking strategies.  It also contains definitions
29633 ** of "finder" functions.  A finder-function is used to locate the appropriate
29634 ** sqlite3_io_methods object for a particular database file.  The pAppData
29635 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
29636 ** the correct finder-function for that VFS.
29637 **
29638 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
29639 ** object.  The only interesting finder-function is autolockIoFinder, which
29640 ** looks at the filesystem type and tries to guess the best locking
29641 ** strategy from that.
29642 **
29643 ** For finder-funtion F, two objects are created:
29644 **
29645 **    (1) The real finder-function named "FImpt()".
29646 **
29647 **    (2) A constant pointer to this function named just "F".
29648 **
29649 **
29650 ** A pointer to the F pointer is used as the pAppData value for VFS
29651 ** objects.  We have to do this instead of letting pAppData point
29652 ** directly at the finder-function since C90 rules prevent a void*
29653 ** from be cast into a function pointer.
29654 **
29655 **
29656 ** Each instance of this macro generates two objects:
29657 **
29658 **   *  A constant sqlite3_io_methods object call METHOD that has locking
29659 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
29660 **
29661 **   *  An I/O method finder function called FINDER that returns a pointer
29662 **      to the METHOD object in the previous bullet.
29663 */
29664 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
29665 static const sqlite3_io_methods METHOD = {                                   \
29666    VERSION,                    /* iVersion */                                \
29667    CLOSE,                      /* xClose */                                  \
29668    unixRead,                   /* xRead */                                   \
29669    unixWrite,                  /* xWrite */                                  \
29670    unixTruncate,               /* xTruncate */                               \
29671    unixSync,                   /* xSync */                                   \
29672    unixFileSize,               /* xFileSize */                               \
29673    LOCK,                       /* xLock */                                   \
29674    UNLOCK,                     /* xUnlock */                                 \
29675    CKLOCK,                     /* xCheckReservedLock */                      \
29676    unixFileControl,            /* xFileControl */                            \
29677    unixSectorSize,             /* xSectorSize */                             \
29678    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
29679    unixShmMap,                 /* xShmMap */                                 \
29680    unixShmLock,                /* xShmLock */                                \
29681    unixShmBarrier,             /* xShmBarrier */                             \
29682    unixShmUnmap                /* xShmUnmap */                               \
29683 };                                                                           \
29684 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
29685   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
29686   return &METHOD;                                                            \
29687 }                                                                            \
29688 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
29689     = FINDER##Impl;
29690
29691 /*
29692 ** Here are all of the sqlite3_io_methods objects for each of the
29693 ** locking strategies.  Functions that return pointers to these methods
29694 ** are also created.
29695 */
29696 IOMETHODS(
29697   posixIoFinder,            /* Finder function name */
29698   posixIoMethods,           /* sqlite3_io_methods object name */
29699   2,                        /* shared memory is enabled */
29700   unixClose,                /* xClose method */
29701   unixLock,                 /* xLock method */
29702   unixUnlock,               /* xUnlock method */
29703   unixCheckReservedLock     /* xCheckReservedLock method */
29704 )
29705 IOMETHODS(
29706   nolockIoFinder,           /* Finder function name */
29707   nolockIoMethods,          /* sqlite3_io_methods object name */
29708   1,                        /* shared memory is disabled */
29709   nolockClose,              /* xClose method */
29710   nolockLock,               /* xLock method */
29711   nolockUnlock,             /* xUnlock method */
29712   nolockCheckReservedLock   /* xCheckReservedLock method */
29713 )
29714 IOMETHODS(
29715   dotlockIoFinder,          /* Finder function name */
29716   dotlockIoMethods,         /* sqlite3_io_methods object name */
29717   1,                        /* shared memory is disabled */
29718   dotlockClose,             /* xClose method */
29719   dotlockLock,              /* xLock method */
29720   dotlockUnlock,            /* xUnlock method */
29721   dotlockCheckReservedLock  /* xCheckReservedLock method */
29722 )
29723
29724 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
29725 IOMETHODS(
29726   flockIoFinder,            /* Finder function name */
29727   flockIoMethods,           /* sqlite3_io_methods object name */
29728   1,                        /* shared memory is disabled */
29729   flockClose,               /* xClose method */
29730   flockLock,                /* xLock method */
29731   flockUnlock,              /* xUnlock method */
29732   flockCheckReservedLock    /* xCheckReservedLock method */
29733 )
29734 #endif
29735
29736 #if OS_VXWORKS
29737 IOMETHODS(
29738   semIoFinder,              /* Finder function name */
29739   semIoMethods,             /* sqlite3_io_methods object name */
29740   1,                        /* shared memory is disabled */
29741   semClose,                 /* xClose method */
29742   semLock,                  /* xLock method */
29743   semUnlock,                /* xUnlock method */
29744   semCheckReservedLock      /* xCheckReservedLock method */
29745 )
29746 #endif
29747
29748 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29749 IOMETHODS(
29750   afpIoFinder,              /* Finder function name */
29751   afpIoMethods,             /* sqlite3_io_methods object name */
29752   1,                        /* shared memory is disabled */
29753   afpClose,                 /* xClose method */
29754   afpLock,                  /* xLock method */
29755   afpUnlock,                /* xUnlock method */
29756   afpCheckReservedLock      /* xCheckReservedLock method */
29757 )
29758 #endif
29759
29760 /*
29761 ** The proxy locking method is a "super-method" in the sense that it
29762 ** opens secondary file descriptors for the conch and lock files and
29763 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
29764 ** secondary files.  For this reason, the division that implements
29765 ** proxy locking is located much further down in the file.  But we need
29766 ** to go ahead and define the sqlite3_io_methods and finder function
29767 ** for proxy locking here.  So we forward declare the I/O methods.
29768 */
29769 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29770 static int proxyClose(sqlite3_file*);
29771 static int proxyLock(sqlite3_file*, int);
29772 static int proxyUnlock(sqlite3_file*, int);
29773 static int proxyCheckReservedLock(sqlite3_file*, int*);
29774 IOMETHODS(
29775   proxyIoFinder,            /* Finder function name */
29776   proxyIoMethods,           /* sqlite3_io_methods object name */
29777   1,                        /* shared memory is disabled */
29778   proxyClose,               /* xClose method */
29779   proxyLock,                /* xLock method */
29780   proxyUnlock,              /* xUnlock method */
29781   proxyCheckReservedLock    /* xCheckReservedLock method */
29782 )
29783 #endif
29784
29785 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
29786 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29787 IOMETHODS(
29788   nfsIoFinder,               /* Finder function name */
29789   nfsIoMethods,              /* sqlite3_io_methods object name */
29790   1,                         /* shared memory is disabled */
29791   unixClose,                 /* xClose method */
29792   unixLock,                  /* xLock method */
29793   nfsUnlock,                 /* xUnlock method */
29794   unixCheckReservedLock      /* xCheckReservedLock method */
29795 )
29796 #endif
29797
29798 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29799 /*
29800 ** This "finder" function attempts to determine the best locking strategy
29801 ** for the database file "filePath".  It then returns the sqlite3_io_methods
29802 ** object that implements that strategy.
29803 **
29804 ** This is for MacOSX only.
29805 */
29806 static const sqlite3_io_methods *autolockIoFinderImpl(
29807   const char *filePath,    /* name of the database file */
29808   unixFile *pNew           /* open file object for the database file */
29809 ){
29810   static const struct Mapping {
29811     const char *zFilesystem;              /* Filesystem type name */
29812     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
29813   } aMap[] = {
29814     { "hfs",    &posixIoMethods },
29815     { "ufs",    &posixIoMethods },
29816     { "afpfs",  &afpIoMethods },
29817     { "smbfs",  &afpIoMethods },
29818     { "webdav", &nolockIoMethods },
29819     { 0, 0 }
29820   };
29821   int i;
29822   struct statfs fsInfo;
29823   struct flock lockInfo;
29824
29825   if( !filePath ){
29826     /* If filePath==NULL that means we are dealing with a transient file
29827     ** that does not need to be locked. */
29828     return &nolockIoMethods;
29829   }
29830   if( statfs(filePath, &fsInfo) != -1 ){
29831     if( fsInfo.f_flags & MNT_RDONLY ){
29832       return &nolockIoMethods;
29833     }
29834     for(i=0; aMap[i].zFilesystem; i++){
29835       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29836         return aMap[i].pMethods;
29837       }
29838     }
29839   }
29840
29841   /* Default case. Handles, amongst others, "nfs".
29842   ** Test byte-range lock using fcntl(). If the call succeeds,
29843   ** assume that the file-system supports POSIX style locks.
29844   */
29845   lockInfo.l_len = 1;
29846   lockInfo.l_start = 0;
29847   lockInfo.l_whence = SEEK_SET;
29848   lockInfo.l_type = F_RDLCK;
29849   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29850     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29851       return &nfsIoMethods;
29852     } else {
29853       return &posixIoMethods;
29854     }
29855   }else{
29856     return &dotlockIoMethods;
29857   }
29858 }
29859 static const sqlite3_io_methods
29860   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29861
29862 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29863
29864 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29865 /*
29866 ** This "finder" function attempts to determine the best locking strategy
29867 ** for the database file "filePath".  It then returns the sqlite3_io_methods
29868 ** object that implements that strategy.
29869 **
29870 ** This is for VXWorks only.
29871 */
29872 static const sqlite3_io_methods *autolockIoFinderImpl(
29873   const char *filePath,    /* name of the database file */
29874   unixFile *pNew           /* the open file object */
29875 ){
29876   struct flock lockInfo;
29877
29878   if( !filePath ){
29879     /* If filePath==NULL that means we are dealing with a transient file
29880     ** that does not need to be locked. */
29881     return &nolockIoMethods;
29882   }
29883
29884   /* Test if fcntl() is supported and use POSIX style locks.
29885   ** Otherwise fall back to the named semaphore method.
29886   */
29887   lockInfo.l_len = 1;
29888   lockInfo.l_start = 0;
29889   lockInfo.l_whence = SEEK_SET;
29890   lockInfo.l_type = F_RDLCK;
29891   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29892     return &posixIoMethods;
29893   }else{
29894     return &semIoMethods;
29895   }
29896 }
29897 static const sqlite3_io_methods
29898   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29899
29900 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
29901
29902 /*
29903 ** An abstract type for a pointer to a IO method finder function:
29904 */
29905 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
29906
29907
29908 /****************************************************************************
29909 **************************** sqlite3_vfs methods ****************************
29910 **
29911 ** This division contains the implementation of methods on the
29912 ** sqlite3_vfs object.
29913 */
29914
29915 /*
29916 ** Initialize the contents of the unixFile structure pointed to by pId.
29917 */
29918 static int fillInUnixFile(
29919   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
29920   int h,                  /* Open file descriptor of file being opened */
29921   sqlite3_file *pId,      /* Write to the unixFile structure here */
29922   const char *zFilename,  /* Name of the file being opened */
29923   int ctrlFlags           /* Zero or more UNIXFILE_* values */
29924 ){
29925   const sqlite3_io_methods *pLockingStyle;
29926   unixFile *pNew = (unixFile *)pId;
29927   int rc = SQLITE_OK;
29928
29929   assert( pNew->pInode==NULL );
29930
29931   /* Usually the path zFilename should not be a relative pathname. The
29932   ** exception is when opening the proxy "conch" file in builds that
29933   ** include the special Apple locking styles.
29934   */
29935 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29936   assert( zFilename==0 || zFilename[0]=='/'
29937     || pVfs->pAppData==(void*)&autolockIoFinder );
29938 #else
29939   assert( zFilename==0 || zFilename[0]=='/' );
29940 #endif
29941
29942   /* No locking occurs in temporary files */
29943   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
29944
29945   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
29946   pNew->h = h;
29947   pNew->pVfs = pVfs;
29948   pNew->zPath = zFilename;
29949   pNew->ctrlFlags = (u8)ctrlFlags;
29950   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
29951                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
29952     pNew->ctrlFlags |= UNIXFILE_PSOW;
29953   }
29954   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
29955     pNew->ctrlFlags |= UNIXFILE_EXCL;
29956   }
29957
29958 #if OS_VXWORKS
29959   pNew->pId = vxworksFindFileId(zFilename);
29960   if( pNew->pId==0 ){
29961     ctrlFlags |= UNIXFILE_NOLOCK;
29962     rc = SQLITE_NOMEM;
29963   }
29964 #endif
29965
29966   if( ctrlFlags & UNIXFILE_NOLOCK ){
29967     pLockingStyle = &nolockIoMethods;
29968   }else{
29969     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
29970 #if SQLITE_ENABLE_LOCKING_STYLE
29971     /* Cache zFilename in the locking context (AFP and dotlock override) for
29972     ** proxyLock activation is possible (remote proxy is based on db name)
29973     ** zFilename remains valid until file is closed, to support */
29974     pNew->lockingContext = (void*)zFilename;
29975 #endif
29976   }
29977
29978   if( pLockingStyle == &posixIoMethods
29979 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29980     || pLockingStyle == &nfsIoMethods
29981 #endif
29982   ){
29983     unixEnterMutex();
29984     rc = findInodeInfo(pNew, &pNew->pInode);
29985     if( rc!=SQLITE_OK ){
29986       /* If an error occured in findInodeInfo(), close the file descriptor
29987       ** immediately, before releasing the mutex. findInodeInfo() may fail
29988       ** in two scenarios:
29989       **
29990       **   (a) A call to fstat() failed.
29991       **   (b) A malloc failed.
29992       **
29993       ** Scenario (b) may only occur if the process is holding no other
29994       ** file descriptors open on the same file. If there were other file
29995       ** descriptors on this file, then no malloc would be required by
29996       ** findInodeInfo(). If this is the case, it is quite safe to close
29997       ** handle h - as it is guaranteed that no posix locks will be released
29998       ** by doing so.
29999       **
30000       ** If scenario (a) caused the error then things are not so safe. The
30001       ** implicit assumption here is that if fstat() fails, things are in
30002       ** such bad shape that dropping a lock or two doesn't matter much.
30003       */
30004       robust_close(pNew, h, __LINE__);
30005       h = -1;
30006     }
30007     unixLeaveMutex();
30008   }
30009
30010 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30011   else if( pLockingStyle == &afpIoMethods ){
30012     /* AFP locking uses the file path so it needs to be included in
30013     ** the afpLockingContext.
30014     */
30015     afpLockingContext *pCtx;
30016     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
30017     if( pCtx==0 ){
30018       rc = SQLITE_NOMEM;
30019     }else{
30020       /* NB: zFilename exists and remains valid until the file is closed
30021       ** according to requirement F11141.  So we do not need to make a
30022       ** copy of the filename. */
30023       pCtx->dbPath = zFilename;
30024       pCtx->reserved = 0;
30025       srandomdev();
30026       unixEnterMutex();
30027       rc = findInodeInfo(pNew, &pNew->pInode);
30028       if( rc!=SQLITE_OK ){
30029         sqlite3_free(pNew->lockingContext);
30030         robust_close(pNew, h, __LINE__);
30031         h = -1;
30032       }
30033       unixLeaveMutex();
30034     }
30035   }
30036 #endif
30037
30038   else if( pLockingStyle == &dotlockIoMethods ){
30039     /* Dotfile locking uses the file path so it needs to be included in
30040     ** the dotlockLockingContext
30041     */
30042     char *zLockFile;
30043     int nFilename;
30044     assert( zFilename!=0 );
30045     nFilename = (int)strlen(zFilename) + 6;
30046     zLockFile = (char *)sqlite3_malloc(nFilename);
30047     if( zLockFile==0 ){
30048       rc = SQLITE_NOMEM;
30049     }else{
30050       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
30051     }
30052     pNew->lockingContext = zLockFile;
30053   }
30054
30055 #if OS_VXWORKS
30056   else if( pLockingStyle == &semIoMethods ){
30057     /* Named semaphore locking uses the file path so it needs to be
30058     ** included in the semLockingContext
30059     */
30060     unixEnterMutex();
30061     rc = findInodeInfo(pNew, &pNew->pInode);
30062     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
30063       char *zSemName = pNew->pInode->aSemName;
30064       int n;
30065       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
30066                        pNew->pId->zCanonicalName);
30067       for( n=1; zSemName[n]; n++ )
30068         if( zSemName[n]=='/' ) zSemName[n] = '_';
30069       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
30070       if( pNew->pInode->pSem == SEM_FAILED ){
30071         rc = SQLITE_NOMEM;
30072         pNew->pInode->aSemName[0] = '\0';
30073       }
30074     }
30075     unixLeaveMutex();
30076   }
30077 #endif
30078
30079   pNew->lastErrno = 0;
30080 #if OS_VXWORKS
30081   if( rc!=SQLITE_OK ){
30082     if( h>=0 ) robust_close(pNew, h, __LINE__);
30083     h = -1;
30084     osUnlink(zFilename);
30085     isDelete = 0;
30086   }
30087   if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
30088 #endif
30089   if( rc!=SQLITE_OK ){
30090     if( h>=0 ) robust_close(pNew, h, __LINE__);
30091   }else{
30092     pNew->pMethod = pLockingStyle;
30093     OpenCounter(+1);
30094   }
30095   return rc;
30096 }
30097
30098 /*
30099 ** Return the name of a directory in which to put temporary files.
30100 ** If no suitable temporary file directory can be found, return NULL.
30101 */
30102 static const char *unixTempFileDir(void){
30103   static const char *azDirs[] = {
30104      0,
30105      0,
30106      "/var/tmp",
30107      "/usr/tmp",
30108      "/tmp",
30109      0        /* List terminator */
30110   };
30111   unsigned int i;
30112   struct stat buf;
30113   const char *zDir = 0;
30114
30115   azDirs[0] = sqlite3_temp_directory;
30116   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
30117   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
30118     if( zDir==0 ) continue;
30119     if( osStat(zDir, &buf) ) continue;
30120     if( !S_ISDIR(buf.st_mode) ) continue;
30121     if( osAccess(zDir, 07) ) continue;
30122     break;
30123   }
30124   return zDir;
30125 }
30126
30127 /*
30128 ** Create a temporary file name in zBuf.  zBuf must be allocated
30129 ** by the calling process and must be big enough to hold at least
30130 ** pVfs->mxPathname bytes.
30131 */
30132 static int unixGetTempname(int nBuf, char *zBuf){
30133   static const unsigned char zChars[] =
30134     "abcdefghijklmnopqrstuvwxyz"
30135     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30136     "0123456789";
30137   unsigned int i, j;
30138   const char *zDir;
30139
30140   /* It's odd to simulate an io-error here, but really this is just
30141   ** using the io-error infrastructure to test that SQLite handles this
30142   ** function failing.
30143   */
30144   SimulateIOError( return SQLITE_IOERR );
30145
30146   zDir = unixTempFileDir();
30147   if( zDir==0 ) zDir = ".";
30148
30149   /* Check that the output buffer is large enough for the temporary file
30150   ** name. If it is not, return SQLITE_ERROR.
30151   */
30152   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
30153     return SQLITE_ERROR;
30154   }
30155
30156   do{
30157     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
30158     j = (int)strlen(zBuf);
30159     sqlite3_randomness(15, &zBuf[j]);
30160     for(i=0; i<15; i++, j++){
30161       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30162     }
30163     zBuf[j] = 0;
30164     zBuf[j+1] = 0;
30165   }while( osAccess(zBuf,0)==0 );
30166   return SQLITE_OK;
30167 }
30168
30169 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30170 /*
30171 ** Routine to transform a unixFile into a proxy-locking unixFile.
30172 ** Implementation in the proxy-lock division, but used by unixOpen()
30173 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
30174 */
30175 static int proxyTransformUnixFile(unixFile*, const char*);
30176 #endif
30177
30178 /*
30179 ** Search for an unused file descriptor that was opened on the database
30180 ** file (not a journal or master-journal file) identified by pathname
30181 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
30182 ** argument to this function.
30183 **
30184 ** Such a file descriptor may exist if a database connection was closed
30185 ** but the associated file descriptor could not be closed because some
30186 ** other file descriptor open on the same file is holding a file-lock.
30187 ** Refer to comments in the unixClose() function and the lengthy comment
30188 ** describing "Posix Advisory Locking" at the start of this file for
30189 ** further details. Also, ticket #4018.
30190 **
30191 ** If a suitable file descriptor is found, then it is returned. If no
30192 ** such file descriptor is located, -1 is returned.
30193 */
30194 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
30195   UnixUnusedFd *pUnused = 0;
30196
30197   /* Do not search for an unused file descriptor on vxworks. Not because
30198   ** vxworks would not benefit from the change (it might, we're not sure),
30199   ** but because no way to test it is currently available. It is better
30200   ** not to risk breaking vxworks support for the sake of such an obscure
30201   ** feature.  */
30202 #if !OS_VXWORKS
30203   struct stat sStat;                   /* Results of stat() call */
30204
30205   /* A stat() call may fail for various reasons. If this happens, it is
30206   ** almost certain that an open() call on the same path will also fail.
30207   ** For this reason, if an error occurs in the stat() call here, it is
30208   ** ignored and -1 is returned. The caller will try to open a new file
30209   ** descriptor on the same path, fail, and return an error to SQLite.
30210   **
30211   ** Even if a subsequent open() call does succeed, the consequences of
30212   ** not searching for a resusable file descriptor are not dire.  */
30213   if( 0==osStat(zPath, &sStat) ){
30214     unixInodeInfo *pInode;
30215
30216     unixEnterMutex();
30217     pInode = inodeList;
30218     while( pInode && (pInode->fileId.dev!=sStat.st_dev
30219                      || pInode->fileId.ino!=sStat.st_ino) ){
30220        pInode = pInode->pNext;
30221     }
30222     if( pInode ){
30223       UnixUnusedFd **pp;
30224       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
30225       pUnused = *pp;
30226       if( pUnused ){
30227         *pp = pUnused->pNext;
30228       }
30229     }
30230     unixLeaveMutex();
30231   }
30232 #endif    /* if !OS_VXWORKS */
30233   return pUnused;
30234 }
30235
30236 /*
30237 ** This function is called by unixOpen() to determine the unix permissions
30238 ** to create new files with. If no error occurs, then SQLITE_OK is returned
30239 ** and a value suitable for passing as the third argument to open(2) is
30240 ** written to *pMode. If an IO error occurs, an SQLite error code is
30241 ** returned and the value of *pMode is not modified.
30242 **
30243 ** In most cases cases, this routine sets *pMode to 0, which will become
30244 ** an indication to robust_open() to create the file using
30245 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
30246 ** But if the file being opened is a WAL or regular journal file, then
30247 ** this function queries the file-system for the permissions on the
30248 ** corresponding database file and sets *pMode to this value. Whenever
30249 ** possible, WAL and journal files are created using the same permissions
30250 ** as the associated database file.
30251 **
30252 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
30253 ** original filename is unavailable.  But 8_3_NAMES is only used for
30254 ** FAT filesystems and permissions do not matter there, so just use
30255 ** the default permissions.
30256 */
30257 static int findCreateFileMode(
30258   const char *zPath,              /* Path of file (possibly) being created */
30259   int flags,                      /* Flags passed as 4th argument to xOpen() */
30260   mode_t *pMode,                  /* OUT: Permissions to open file with */
30261   uid_t *pUid,                    /* OUT: uid to set on the file */
30262   gid_t *pGid                     /* OUT: gid to set on the file */
30263 ){
30264   int rc = SQLITE_OK;             /* Return Code */
30265   *pMode = 0;
30266   *pUid = 0;
30267   *pGid = 0;
30268   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30269     char zDb[MAX_PATHNAME+1];     /* Database file path */
30270     int nDb;                      /* Number of valid bytes in zDb */
30271     struct stat sStat;            /* Output of stat() on database file */
30272
30273     /* zPath is a path to a WAL or journal file. The following block derives
30274     ** the path to the associated database file from zPath. This block handles
30275     ** the following naming conventions:
30276     **
30277     **   "<path to db>-journal"
30278     **   "<path to db>-wal"
30279     **   "<path to db>-journalNN"
30280     **   "<path to db>-walNN"
30281     **
30282     ** where NN is a decimal number. The NN naming schemes are
30283     ** used by the test_multiplex.c module.
30284     */
30285     nDb = sqlite3Strlen30(zPath) - 1;
30286 #ifdef SQLITE_ENABLE_8_3_NAMES
30287     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
30288     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
30289 #else
30290     while( zPath[nDb]!='-' ){
30291       assert( nDb>0 );
30292       assert( zPath[nDb]!='\n' );
30293       nDb--;
30294     }
30295 #endif
30296     memcpy(zDb, zPath, nDb);
30297     zDb[nDb] = '\0';
30298
30299     if( 0==osStat(zDb, &sStat) ){
30300       *pMode = sStat.st_mode & 0777;
30301       *pUid = sStat.st_uid;
30302       *pGid = sStat.st_gid;
30303     }else{
30304       rc = SQLITE_IOERR_FSTAT;
30305     }
30306   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30307     *pMode = 0600;
30308   }
30309   return rc;
30310 }
30311
30312 /*
30313 ** Open the file zPath.
30314 **
30315 ** Previously, the SQLite OS layer used three functions in place of this
30316 ** one:
30317 **
30318 **     sqlite3OsOpenReadWrite();
30319 **     sqlite3OsOpenReadOnly();
30320 **     sqlite3OsOpenExclusive();
30321 **
30322 ** These calls correspond to the following combinations of flags:
30323 **
30324 **     ReadWrite() ->     (READWRITE | CREATE)
30325 **     ReadOnly()  ->     (READONLY)
30326 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
30327 **
30328 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
30329 ** true, the file was configured to be automatically deleted when the
30330 ** file handle closed. To achieve the same effect using this new
30331 ** interface, add the DELETEONCLOSE flag to those specified above for
30332 ** OpenExclusive().
30333 */
30334 static int unixOpen(
30335   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
30336   const char *zPath,           /* Pathname of file to be opened */
30337   sqlite3_file *pFile,         /* The file descriptor to be filled in */
30338   int flags,                   /* Input flags to control the opening */
30339   int *pOutFlags               /* Output flags returned to SQLite core */
30340 ){
30341   unixFile *p = (unixFile *)pFile;
30342   int fd = -1;                   /* File descriptor returned by open() */
30343   int openFlags = 0;             /* Flags to pass to open() */
30344   int eType = flags&0xFFFFFF00;  /* Type of file to open */
30345   int noLock;                    /* True to omit locking primitives */
30346   int rc = SQLITE_OK;            /* Function Return Code */
30347   int ctrlFlags = 0;             /* UNIXFILE_* flags */
30348
30349   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
30350   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
30351   int isCreate     = (flags & SQLITE_OPEN_CREATE);
30352   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
30353   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
30354 #if SQLITE_ENABLE_LOCKING_STYLE
30355   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
30356 #endif
30357 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30358   struct statfs fsInfo;
30359 #endif
30360
30361   /* If creating a master or main-file journal, this function will open
30362   ** a file-descriptor on the directory too. The first time unixSync()
30363   ** is called the directory file descriptor will be fsync()ed and close()d.
30364   */
30365   int syncDir = (isCreate && (
30366         eType==SQLITE_OPEN_MASTER_JOURNAL
30367      || eType==SQLITE_OPEN_MAIN_JOURNAL
30368      || eType==SQLITE_OPEN_WAL
30369   ));
30370
30371   /* If argument zPath is a NULL pointer, this function is required to open
30372   ** a temporary file. Use this buffer to store the file name in.
30373   */
30374   char zTmpname[MAX_PATHNAME+2];
30375   const char *zName = zPath;
30376
30377   /* Check the following statements are true:
30378   **
30379   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
30380   **   (b) if CREATE is set, then READWRITE must also be set, and
30381   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
30382   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
30383   */
30384   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
30385   assert(isCreate==0 || isReadWrite);
30386   assert(isExclusive==0 || isCreate);
30387   assert(isDelete==0 || isCreate);
30388
30389   /* The main DB, main journal, WAL file and master journal are never
30390   ** automatically deleted. Nor are they ever temporary files.  */
30391   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
30392   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
30393   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
30394   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
30395
30396   /* Assert that the upper layer has set one of the "file-type" flags. */
30397   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
30398        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
30399        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
30400        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
30401   );
30402
30403   memset(p, 0, sizeof(unixFile));
30404
30405   if( eType==SQLITE_OPEN_MAIN_DB ){
30406     UnixUnusedFd *pUnused;
30407     pUnused = findReusableFd(zName, flags);
30408     if( pUnused ){
30409       fd = pUnused->fd;
30410     }else{
30411       pUnused = sqlite3_malloc(sizeof(*pUnused));
30412       if( !pUnused ){
30413         return SQLITE_NOMEM;
30414       }
30415     }
30416     p->pUnused = pUnused;
30417
30418     /* Database filenames are double-zero terminated if they are not
30419     ** URIs with parameters.  Hence, they can always be passed into
30420     ** sqlite3_uri_parameter(). */
30421     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
30422
30423   }else if( !zName ){
30424     /* If zName is NULL, the upper layer is requesting a temp file. */
30425     assert(isDelete && !syncDir);
30426     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
30427     if( rc!=SQLITE_OK ){
30428       return rc;
30429     }
30430     zName = zTmpname;
30431
30432     /* Generated temporary filenames are always double-zero terminated
30433     ** for use by sqlite3_uri_parameter(). */
30434     assert( zName[strlen(zName)+1]==0 );
30435   }
30436
30437   /* Determine the value of the flags parameter passed to POSIX function
30438   ** open(). These must be calculated even if open() is not called, as
30439   ** they may be stored as part of the file handle and used by the
30440   ** 'conch file' locking functions later on.  */
30441   if( isReadonly )  openFlags |= O_RDONLY;
30442   if( isReadWrite ) openFlags |= O_RDWR;
30443   if( isCreate )    openFlags |= O_CREAT;
30444   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
30445   openFlags |= (O_LARGEFILE|O_BINARY);
30446
30447   if( fd<0 ){
30448     mode_t openMode;              /* Permissions to create file with */
30449     uid_t uid;                    /* Userid for the file */
30450     gid_t gid;                    /* Groupid for the file */
30451     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
30452     if( rc!=SQLITE_OK ){
30453       assert( !p->pUnused );
30454       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
30455       return rc;
30456     }
30457     fd = robust_open(zName, openFlags, openMode);
30458     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
30459     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
30460       /* Failed to open the file for read/write access. Try read-only. */
30461       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30462       openFlags &= ~(O_RDWR|O_CREAT);
30463       flags |= SQLITE_OPEN_READONLY;
30464       openFlags |= O_RDONLY;
30465       isReadonly = 1;
30466       fd = robust_open(zName, openFlags, openMode);
30467     }
30468     if( fd<0 ){
30469       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
30470       goto open_finished;
30471     }
30472
30473     /* If this process is running as root and if creating a new rollback
30474     ** journal or WAL file, set the ownership of the journal or WAL to be
30475     ** the same as the original database.
30476     */
30477     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30478       osFchown(fd, uid, gid);
30479     }
30480   }
30481   assert( fd>=0 );
30482   if( pOutFlags ){
30483     *pOutFlags = flags;
30484   }
30485
30486   if( p->pUnused ){
30487     p->pUnused->fd = fd;
30488     p->pUnused->flags = flags;
30489   }
30490
30491   if( isDelete ){
30492 #if OS_VXWORKS
30493     zPath = zName;
30494 #else
30495     osUnlink(zName);
30496 #endif
30497   }
30498 #if SQLITE_ENABLE_LOCKING_STYLE
30499   else{
30500     p->openFlags = openFlags;
30501   }
30502 #endif
30503
30504   noLock = eType!=SQLITE_OPEN_MAIN_DB;
30505
30506
30507 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30508   if( fstatfs(fd, &fsInfo) == -1 ){
30509     ((unixFile*)pFile)->lastErrno = errno;
30510     robust_close(p, fd, __LINE__);
30511     return SQLITE_IOERR_ACCESS;
30512   }
30513   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
30514     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
30515   }
30516 #endif
30517
30518   /* Set up appropriate ctrlFlags */
30519   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
30520   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
30521   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
30522   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
30523   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
30524
30525 #if SQLITE_ENABLE_LOCKING_STYLE
30526 #if SQLITE_PREFER_PROXY_LOCKING
30527   isAutoProxy = 1;
30528 #endif
30529   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
30530     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
30531     int useProxy = 0;
30532
30533     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
30534     ** never use proxy, NULL means use proxy for non-local files only.  */
30535     if( envforce!=NULL ){
30536       useProxy = atoi(envforce)>0;
30537     }else{
30538       if( statfs(zPath, &fsInfo) == -1 ){
30539         /* In theory, the close(fd) call is sub-optimal. If the file opened
30540         ** with fd is a database file, and there are other connections open
30541         ** on that file that are currently holding advisory locks on it,
30542         ** then the call to close() will cancel those locks. In practice,
30543         ** we're assuming that statfs() doesn't fail very often. At least
30544         ** not while other file descriptors opened by the same process on
30545         ** the same file are working.  */
30546         p->lastErrno = errno;
30547         robust_close(p, fd, __LINE__);
30548         rc = SQLITE_IOERR_ACCESS;
30549         goto open_finished;
30550       }
30551       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
30552     }
30553     if( useProxy ){
30554       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30555       if( rc==SQLITE_OK ){
30556         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
30557         if( rc!=SQLITE_OK ){
30558           /* Use unixClose to clean up the resources added in fillInUnixFile
30559           ** and clear all the structure's references.  Specifically,
30560           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
30561           */
30562           unixClose(pFile);
30563           return rc;
30564         }
30565       }
30566       goto open_finished;
30567     }
30568   }
30569 #endif
30570
30571   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30572
30573 open_finished:
30574   if( rc!=SQLITE_OK ){
30575     sqlite3_free(p->pUnused);
30576   }
30577   return rc;
30578 }
30579
30580
30581 /*
30582 ** Delete the file at zPath. If the dirSync argument is true, fsync()
30583 ** the directory after deleting the file.
30584 */
30585 static int unixDelete(
30586   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
30587   const char *zPath,        /* Name of file to be deleted */
30588   int dirSync               /* If true, fsync() directory after deleting file */
30589 ){
30590   int rc = SQLITE_OK;
30591   UNUSED_PARAMETER(NotUsed);
30592   SimulateIOError(return SQLITE_IOERR_DELETE);
30593   if( osUnlink(zPath)==(-1) ){
30594     if( errno==ENOENT ){
30595       rc = SQLITE_IOERR_DELETE_NOENT;
30596     }else{
30597       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
30598     }
30599     return rc;
30600   }
30601 #ifndef SQLITE_DISABLE_DIRSYNC
30602   if( (dirSync & 1)!=0 ){
30603     int fd;
30604     rc = osOpenDirectory(zPath, &fd);
30605     if( rc==SQLITE_OK ){
30606 #if OS_VXWORKS
30607       if( fsync(fd)==-1 )
30608 #else
30609       if( fsync(fd) )
30610 #endif
30611       {
30612         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
30613       }
30614       robust_close(0, fd, __LINE__);
30615     }else if( rc==SQLITE_CANTOPEN ){
30616       rc = SQLITE_OK;
30617     }
30618   }
30619 #endif
30620   return rc;
30621 }
30622
30623 /*
30624 ** Test the existance of or access permissions of file zPath. The
30625 ** test performed depends on the value of flags:
30626 **
30627 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
30628 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
30629 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
30630 **
30631 ** Otherwise return 0.
30632 */
30633 static int unixAccess(
30634   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
30635   const char *zPath,      /* Path of the file to examine */
30636   int flags,              /* What do we want to learn about the zPath file? */
30637   int *pResOut            /* Write result boolean here */
30638 ){
30639   int amode = 0;
30640   UNUSED_PARAMETER(NotUsed);
30641   SimulateIOError( return SQLITE_IOERR_ACCESS; );
30642   switch( flags ){
30643     case SQLITE_ACCESS_EXISTS:
30644       amode = F_OK;
30645       break;
30646     case SQLITE_ACCESS_READWRITE:
30647       amode = W_OK|R_OK;
30648       break;
30649     case SQLITE_ACCESS_READ:
30650       amode = R_OK;
30651       break;
30652
30653     default:
30654       assert(!"Invalid flags argument");
30655   }
30656   *pResOut = (osAccess(zPath, amode)==0);
30657   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
30658     struct stat buf;
30659     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
30660       *pResOut = 0;
30661     }
30662   }
30663   return SQLITE_OK;
30664 }
30665
30666
30667 /*
30668 ** Turn a relative pathname into a full pathname. The relative path
30669 ** is stored as a nul-terminated string in the buffer pointed to by
30670 ** zPath.
30671 **
30672 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
30673 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
30674 ** this buffer before returning.
30675 */
30676 static int unixFullPathname(
30677   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
30678   const char *zPath,            /* Possibly relative input path */
30679   int nOut,                     /* Size of output buffer in bytes */
30680   char *zOut                    /* Output buffer */
30681 ){
30682
30683   /* It's odd to simulate an io-error here, but really this is just
30684   ** using the io-error infrastructure to test that SQLite handles this
30685   ** function failing. This function could fail if, for example, the
30686   ** current working directory has been unlinked.
30687   */
30688   SimulateIOError( return SQLITE_ERROR );
30689
30690   assert( pVfs->mxPathname==MAX_PATHNAME );
30691   UNUSED_PARAMETER(pVfs);
30692
30693   zOut[nOut-1] = '\0';
30694   if( zPath[0]=='/' ){
30695     sqlite3_snprintf(nOut, zOut, "%s", zPath);
30696   }else{
30697     int nCwd;
30698     if( osGetcwd(zOut, nOut-1)==0 ){
30699       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
30700     }
30701     nCwd = (int)strlen(zOut);
30702     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
30703   }
30704   return SQLITE_OK;
30705 }
30706
30707
30708 #ifndef SQLITE_OMIT_LOAD_EXTENSION
30709 /*
30710 ** Interfaces for opening a shared library, finding entry points
30711 ** within the shared library, and closing the shared library.
30712 */
30713 #include <dlfcn.h>
30714 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
30715   UNUSED_PARAMETER(NotUsed);
30716   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
30717 }
30718
30719 /*
30720 ** SQLite calls this function immediately after a call to unixDlSym() or
30721 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
30722 ** message is available, it is written to zBufOut. If no error message
30723 ** is available, zBufOut is left unmodified and SQLite uses a default
30724 ** error message.
30725 */
30726 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
30727   const char *zErr;
30728   UNUSED_PARAMETER(NotUsed);
30729   unixEnterMutex();
30730   zErr = dlerror();
30731   if( zErr ){
30732     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
30733   }
30734   unixLeaveMutex();
30735 }
30736 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
30737   /*
30738   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
30739   ** cast into a pointer to a function.  And yet the library dlsym() routine
30740   ** returns a void* which is really a pointer to a function.  So how do we
30741   ** use dlsym() with -pedantic-errors?
30742   **
30743   ** Variable x below is defined to be a pointer to a function taking
30744   ** parameters void* and const char* and returning a pointer to a function.
30745   ** We initialize x by assigning it a pointer to the dlsym() function.
30746   ** (That assignment requires a cast.)  Then we call the function that
30747   ** x points to.
30748   **
30749   ** This work-around is unlikely to work correctly on any system where
30750   ** you really cannot cast a function pointer into void*.  But then, on the
30751   ** other hand, dlsym() will not work on such a system either, so we have
30752   ** not really lost anything.
30753   */
30754   void (*(*x)(void*,const char*))(void);
30755   UNUSED_PARAMETER(NotUsed);
30756   x = (void(*(*)(void*,const char*))(void))dlsym;
30757   return (*x)(p, zSym);
30758 }
30759 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
30760   UNUSED_PARAMETER(NotUsed);
30761   dlclose(pHandle);
30762 }
30763 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
30764   #define unixDlOpen  0
30765   #define unixDlError 0
30766   #define unixDlSym   0
30767   #define unixDlClose 0
30768 #endif
30769
30770 /*
30771 ** Write nBuf bytes of random data to the supplied buffer zBuf.
30772 */
30773 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
30774   UNUSED_PARAMETER(NotUsed);
30775   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
30776
30777   /* We have to initialize zBuf to prevent valgrind from reporting
30778   ** errors.  The reports issued by valgrind are incorrect - we would
30779   ** prefer that the randomness be increased by making use of the
30780   ** uninitialized space in zBuf - but valgrind errors tend to worry
30781   ** some users.  Rather than argue, it seems easier just to initialize
30782   ** the whole array and silence valgrind, even if that means less randomness
30783   ** in the random seed.
30784   **
30785   ** When testing, initializing zBuf[] to zero is all we do.  That means
30786   ** that we always use the same random number sequence.  This makes the
30787   ** tests repeatable.
30788   */
30789   memset(zBuf, 0, nBuf);
30790 #if !defined(SQLITE_TEST)
30791   {
30792     int pid, fd, got;
30793     fd = robust_open("/dev/urandom", O_RDONLY, 0);
30794     if( fd<0 ){
30795       time_t t;
30796       time(&t);
30797       memcpy(zBuf, &t, sizeof(t));
30798       pid = getpid();
30799       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
30800       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
30801       nBuf = sizeof(t) + sizeof(pid);
30802     }else{
30803       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
30804       robust_close(0, fd, __LINE__);
30805     }
30806   }
30807 #endif
30808   return nBuf;
30809 }
30810
30811
30812 /*
30813 ** Sleep for a little while.  Return the amount of time slept.
30814 ** The argument is the number of microseconds we want to sleep.
30815 ** The return value is the number of microseconds of sleep actually
30816 ** requested from the underlying operating system, a number which
30817 ** might be greater than or equal to the argument, but not less
30818 ** than the argument.
30819 */
30820 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
30821 #if OS_VXWORKS
30822   struct timespec sp;
30823
30824   sp.tv_sec = microseconds / 1000000;
30825   sp.tv_nsec = (microseconds % 1000000) * 1000;
30826   nanosleep(&sp, NULL);
30827   UNUSED_PARAMETER(NotUsed);
30828   return microseconds;
30829 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
30830   usleep(microseconds);
30831   UNUSED_PARAMETER(NotUsed);
30832   return microseconds;
30833 #else
30834   int seconds = (microseconds+999999)/1000000;
30835   sleep(seconds);
30836   UNUSED_PARAMETER(NotUsed);
30837   return seconds*1000000;
30838 #endif
30839 }
30840
30841 /*
30842 ** The following variable, if set to a non-zero value, is interpreted as
30843 ** the number of seconds since 1970 and is used to set the result of
30844 ** sqlite3OsCurrentTime() during testing.
30845 */
30846 #ifdef SQLITE_TEST
30847 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
30848 #endif
30849
30850 /*
30851 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
30852 ** the current time and date as a Julian Day number times 86_400_000.  In
30853 ** other words, write into *piNow the number of milliseconds since the Julian
30854 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
30855 ** proleptic Gregorian calendar.
30856 **
30857 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
30858 ** cannot be found.
30859 */
30860 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30861   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30862   int rc = SQLITE_OK;
30863 #if defined(NO_GETTOD)
30864   time_t t;
30865   time(&t);
30866   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30867 #elif OS_VXWORKS
30868   struct timespec sNow;
30869   clock_gettime(CLOCK_REALTIME, &sNow);
30870   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
30871 #else
30872   struct timeval sNow;
30873   if( gettimeofday(&sNow, 0)==0 ){
30874     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
30875   }else{
30876     rc = SQLITE_ERROR;
30877   }
30878 #endif
30879
30880 #ifdef SQLITE_TEST
30881   if( sqlite3_current_time ){
30882     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
30883   }
30884 #endif
30885   UNUSED_PARAMETER(NotUsed);
30886   return rc;
30887 }
30888
30889 /*
30890 ** Find the current time (in Universal Coordinated Time).  Write the
30891 ** current time and date as a Julian Day number into *prNow and
30892 ** return 0.  Return 1 if the time and date cannot be found.
30893 */
30894 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
30895   sqlite3_int64 i = 0;
30896   int rc;
30897   UNUSED_PARAMETER(NotUsed);
30898   rc = unixCurrentTimeInt64(0, &i);
30899   *prNow = i/86400000.0;
30900   return rc;
30901 }
30902
30903 /*
30904 ** We added the xGetLastError() method with the intention of providing
30905 ** better low-level error messages when operating-system problems come up
30906 ** during SQLite operation.  But so far, none of that has been implemented
30907 ** in the core.  So this routine is never called.  For now, it is merely
30908 ** a place-holder.
30909 */
30910 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
30911   UNUSED_PARAMETER(NotUsed);
30912   UNUSED_PARAMETER(NotUsed2);
30913   UNUSED_PARAMETER(NotUsed3);
30914   return 0;
30915 }
30916
30917
30918 /*
30919 ************************ End of sqlite3_vfs methods ***************************
30920 ******************************************************************************/
30921
30922 /******************************************************************************
30923 ************************** Begin Proxy Locking ********************************
30924 **
30925 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
30926 ** other locking methods on secondary lock files.  Proxy locking is a
30927 ** meta-layer over top of the primitive locking implemented above.  For
30928 ** this reason, the division that implements of proxy locking is deferred
30929 ** until late in the file (here) after all of the other I/O methods have
30930 ** been defined - so that the primitive locking methods are available
30931 ** as services to help with the implementation of proxy locking.
30932 **
30933 ****
30934 **
30935 ** The default locking schemes in SQLite use byte-range locks on the
30936 ** database file to coordinate safe, concurrent access by multiple readers
30937 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
30938 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
30939 ** as POSIX read & write locks over fixed set of locations (via fsctl),
30940 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
30941 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
30942 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
30943 ** address in the shared range is taken for a SHARED lock, the entire
30944 ** shared range is taken for an EXCLUSIVE lock):
30945 **
30946 **      PENDING_BYTE        0x40000000
30947 **      RESERVED_BYTE       0x40000001
30948 **      SHARED_RANGE        0x40000002 -> 0x40000200
30949 **
30950 ** This works well on the local file system, but shows a nearly 100x
30951 ** slowdown in read performance on AFP because the AFP client disables
30952 ** the read cache when byte-range locks are present.  Enabling the read
30953 ** cache exposes a cache coherency problem that is present on all OS X
30954 ** supported network file systems.  NFS and AFP both observe the
30955 ** close-to-open semantics for ensuring cache coherency
30956 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
30957 ** address the requirements for concurrent database access by multiple
30958 ** readers and writers
30959 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
30960 **
30961 ** To address the performance and cache coherency issues, proxy file locking
30962 ** changes the way database access is controlled by limiting access to a
30963 ** single host at a time and moving file locks off of the database file
30964 ** and onto a proxy file on the local file system.
30965 **
30966 **
30967 ** Using proxy locks
30968 ** -----------------
30969 **
30970 ** C APIs
30971 **
30972 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
30973 **                       <proxy_path> | ":auto:");
30974 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
30975 **
30976 **
30977 ** SQL pragmas
30978 **
30979 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
30980 **  PRAGMA [database.]lock_proxy_file
30981 **
30982 ** Specifying ":auto:" means that if there is a conch file with a matching
30983 ** host ID in it, the proxy path in the conch file will be used, otherwise
30984 ** a proxy path based on the user's temp dir
30985 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
30986 ** actual proxy file name is generated from the name and path of the
30987 ** database file.  For example:
30988 **
30989 **       For database path "/Users/me/foo.db"
30990 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
30991 **
30992 ** Once a lock proxy is configured for a database connection, it can not
30993 ** be removed, however it may be switched to a different proxy path via
30994 ** the above APIs (assuming the conch file is not being held by another
30995 ** connection or process).
30996 **
30997 **
30998 ** How proxy locking works
30999 ** -----------------------
31000 **
31001 ** Proxy file locking relies primarily on two new supporting files:
31002 **
31003 **   *  conch file to limit access to the database file to a single host
31004 **      at a time
31005 **
31006 **   *  proxy file to act as a proxy for the advisory locks normally
31007 **      taken on the database
31008 **
31009 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
31010 ** by taking an sqlite-style shared lock on the conch file, reading the
31011 ** contents and comparing the host's unique host ID (see below) and lock
31012 ** proxy path against the values stored in the conch.  The conch file is
31013 ** stored in the same directory as the database file and the file name
31014 ** is patterned after the database file name as ".<databasename>-conch".
31015 ** If the conch file does not exist, or it's contents do not match the
31016 ** host ID and/or proxy path, then the lock is escalated to an exclusive
31017 ** lock and the conch file contents is updated with the host ID and proxy
31018 ** path and the lock is downgraded to a shared lock again.  If the conch
31019 ** is held by another process (with a shared lock), the exclusive lock
31020 ** will fail and SQLITE_BUSY is returned.
31021 **
31022 ** The proxy file - a single-byte file used for all advisory file locks
31023 ** normally taken on the database file.   This allows for safe sharing
31024 ** of the database file for multiple readers and writers on the same
31025 ** host (the conch ensures that they all use the same local lock file).
31026 **
31027 ** Requesting the lock proxy does not immediately take the conch, it is
31028 ** only taken when the first request to lock database file is made.
31029 ** This matches the semantics of the traditional locking behavior, where
31030 ** opening a connection to a database file does not take a lock on it.
31031 ** The shared lock and an open file descriptor are maintained until
31032 ** the connection to the database is closed.
31033 **
31034 ** The proxy file and the lock file are never deleted so they only need
31035 ** to be created the first time they are used.
31036 **
31037 ** Configuration options
31038 ** ---------------------
31039 **
31040 **  SQLITE_PREFER_PROXY_LOCKING
31041 **
31042 **       Database files accessed on non-local file systems are
31043 **       automatically configured for proxy locking, lock files are
31044 **       named automatically using the same logic as
31045 **       PRAGMA lock_proxy_file=":auto:"
31046 **
31047 **  SQLITE_PROXY_DEBUG
31048 **
31049 **       Enables the logging of error messages during host id file
31050 **       retrieval and creation
31051 **
31052 **  LOCKPROXYDIR
31053 **
31054 **       Overrides the default directory used for lock proxy files that
31055 **       are named automatically via the ":auto:" setting
31056 **
31057 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
31058 **
31059 **       Permissions to use when creating a directory for storing the
31060 **       lock proxy files, only used when LOCKPROXYDIR is not set.
31061 **
31062 **
31063 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
31064 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
31065 ** force proxy locking to be used for every database file opened, and 0
31066 ** will force automatic proxy locking to be disabled for all database
31067 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
31068 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
31069 */
31070
31071 /*
31072 ** Proxy locking is only available on MacOSX
31073 */
31074 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31075
31076 /*
31077 ** The proxyLockingContext has the path and file structures for the remote
31078 ** and local proxy files in it
31079 */
31080 typedef struct proxyLockingContext proxyLockingContext;
31081 struct proxyLockingContext {
31082   unixFile *conchFile;         /* Open conch file */
31083   char *conchFilePath;         /* Name of the conch file */
31084   unixFile *lockProxy;         /* Open proxy lock file */
31085   char *lockProxyPath;         /* Name of the proxy lock file */
31086   char *dbPath;                /* Name of the open file */
31087   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
31088   void *oldLockingContext;     /* Original lockingcontext to restore on close */
31089   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
31090 };
31091
31092 /*
31093 ** The proxy lock file path for the database at dbPath is written into lPath,
31094 ** which must point to valid, writable memory large enough for a maxLen length
31095 ** file path.
31096 */
31097 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
31098   int len;
31099   int dbLen;
31100   int i;
31101
31102 #ifdef LOCKPROXYDIR
31103   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
31104 #else
31105 # ifdef _CS_DARWIN_USER_TEMP_DIR
31106   {
31107     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
31108       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
31109                lPath, errno, getpid()));
31110       return SQLITE_IOERR_LOCK;
31111     }
31112     len = strlcat(lPath, "sqliteplocks", maxLen);
31113   }
31114 # else
31115   len = strlcpy(lPath, "/tmp/", maxLen);
31116 # endif
31117 #endif
31118
31119   if( lPath[len-1]!='/' ){
31120     len = strlcat(lPath, "/", maxLen);
31121   }
31122
31123   /* transform the db path to a unique cache name */
31124   dbLen = (int)strlen(dbPath);
31125   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
31126     char c = dbPath[i];
31127     lPath[i+len] = (c=='/')?'_':c;
31128   }
31129   lPath[i+len]='\0';
31130   strlcat(lPath, ":auto:", maxLen);
31131   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
31132   return SQLITE_OK;
31133 }
31134
31135 /*
31136  ** Creates the lock file and any missing directories in lockPath
31137  */
31138 static int proxyCreateLockPath(const char *lockPath){
31139   int i, len;
31140   char buf[MAXPATHLEN];
31141   int start = 0;
31142
31143   assert(lockPath!=NULL);
31144   /* try to create all the intermediate directories */
31145   len = (int)strlen(lockPath);
31146   buf[0] = lockPath[0];
31147   for( i=1; i<len; i++ ){
31148     if( lockPath[i] == '/' && (i - start > 0) ){
31149       /* only mkdir if leaf dir != "." or "/" or ".." */
31150       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
31151          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
31152         buf[i]='\0';
31153         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
31154           int err=errno;
31155           if( err!=EEXIST ) {
31156             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
31157                      "'%s' proxy lock path=%s pid=%d\n",
31158                      buf, strerror(err), lockPath, getpid()));
31159             return err;
31160           }
31161         }
31162       }
31163       start=i+1;
31164     }
31165     buf[i] = lockPath[i];
31166   }
31167   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
31168   return 0;
31169 }
31170
31171 /*
31172 ** Create a new VFS file descriptor (stored in memory obtained from
31173 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
31174 **
31175 ** The caller is responsible not only for closing the file descriptor
31176 ** but also for freeing the memory associated with the file descriptor.
31177 */
31178 static int proxyCreateUnixFile(
31179     const char *path,        /* path for the new unixFile */
31180     unixFile **ppFile,       /* unixFile created and returned by ref */
31181     int islockfile           /* if non zero missing dirs will be created */
31182 ) {
31183   int fd = -1;
31184   unixFile *pNew;
31185   int rc = SQLITE_OK;
31186   int openFlags = O_RDWR | O_CREAT;
31187   sqlite3_vfs dummyVfs;
31188   int terrno = 0;
31189   UnixUnusedFd *pUnused = NULL;
31190
31191   /* 1. first try to open/create the file
31192   ** 2. if that fails, and this is a lock file (not-conch), try creating
31193   ** the parent directories and then try again.
31194   ** 3. if that fails, try to open the file read-only
31195   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
31196   */
31197   pUnused = findReusableFd(path, openFlags);
31198   if( pUnused ){
31199     fd = pUnused->fd;
31200   }else{
31201     pUnused = sqlite3_malloc(sizeof(*pUnused));
31202     if( !pUnused ){
31203       return SQLITE_NOMEM;
31204     }
31205   }
31206   if( fd<0 ){
31207     fd = robust_open(path, openFlags, 0);
31208     terrno = errno;
31209     if( fd<0 && errno==ENOENT && islockfile ){
31210       if( proxyCreateLockPath(path) == SQLITE_OK ){
31211         fd = robust_open(path, openFlags, 0);
31212       }
31213     }
31214   }
31215   if( fd<0 ){
31216     openFlags = O_RDONLY;
31217     fd = robust_open(path, openFlags, 0);
31218     terrno = errno;
31219   }
31220   if( fd<0 ){
31221     if( islockfile ){
31222       return SQLITE_BUSY;
31223     }
31224     switch (terrno) {
31225       case EACCES:
31226         return SQLITE_PERM;
31227       case EIO:
31228         return SQLITE_IOERR_LOCK; /* even though it is the conch */
31229       default:
31230         return SQLITE_CANTOPEN_BKPT;
31231     }
31232   }
31233
31234   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
31235   if( pNew==NULL ){
31236     rc = SQLITE_NOMEM;
31237     goto end_create_proxy;
31238   }
31239   memset(pNew, 0, sizeof(unixFile));
31240   pNew->openFlags = openFlags;
31241   memset(&dummyVfs, 0, sizeof(dummyVfs));
31242   dummyVfs.pAppData = (void*)&autolockIoFinder;
31243   dummyVfs.zName = "dummy";
31244   pUnused->fd = fd;
31245   pUnused->flags = openFlags;
31246   pNew->pUnused = pUnused;
31247
31248   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
31249   if( rc==SQLITE_OK ){
31250     *ppFile = pNew;
31251     return SQLITE_OK;
31252   }
31253 end_create_proxy:
31254   robust_close(pNew, fd, __LINE__);
31255   sqlite3_free(pNew);
31256   sqlite3_free(pUnused);
31257   return rc;
31258 }
31259
31260 #ifdef SQLITE_TEST
31261 /* simulate multiple hosts by creating unique hostid file paths */
31262 SQLITE_API int sqlite3_hostid_num = 0;
31263 #endif
31264
31265 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
31266
31267 /* Not always defined in the headers as it ought to be */
31268 extern int gethostuuid(uuid_t id, const struct timespec *wait);
31269
31270 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
31271 ** bytes of writable memory.
31272 */
31273 static int proxyGetHostID(unsigned char *pHostID, int *pError){
31274   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
31275   memset(pHostID, 0, PROXY_HOSTIDLEN);
31276 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
31277                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
31278   {
31279     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
31280     if( gethostuuid(pHostID, &timeout) ){
31281       int err = errno;
31282       if( pError ){
31283         *pError = err;
31284       }
31285       return SQLITE_IOERR;
31286     }
31287   }
31288 #else
31289   UNUSED_PARAMETER(pError);
31290 #endif
31291 #ifdef SQLITE_TEST
31292   /* simulate multiple hosts by creating unique hostid file paths */
31293   if( sqlite3_hostid_num != 0){
31294     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
31295   }
31296 #endif
31297
31298   return SQLITE_OK;
31299 }
31300
31301 /* The conch file contains the header, host id and lock file path
31302  */
31303 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
31304 #define PROXY_HEADERLEN    1   /* conch file header length */
31305 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
31306 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
31307
31308 /*
31309 ** Takes an open conch file, copies the contents to a new path and then moves
31310 ** it back.  The newly created file's file descriptor is assigned to the
31311 ** conch file structure and finally the original conch file descriptor is
31312 ** closed.  Returns zero if successful.
31313 */
31314 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
31315   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31316   unixFile *conchFile = pCtx->conchFile;
31317   char tPath[MAXPATHLEN];
31318   char buf[PROXY_MAXCONCHLEN];
31319   char *cPath = pCtx->conchFilePath;
31320   size_t readLen = 0;
31321   size_t pathLen = 0;
31322   char errmsg[64] = "";
31323   int fd = -1;
31324   int rc = -1;
31325   UNUSED_PARAMETER(myHostID);
31326
31327   /* create a new path by replace the trailing '-conch' with '-break' */
31328   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
31329   if( pathLen>MAXPATHLEN || pathLen<6 ||
31330      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
31331     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
31332     goto end_breaklock;
31333   }
31334   /* read the conch content */
31335   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
31336   if( readLen<PROXY_PATHINDEX ){
31337     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
31338     goto end_breaklock;
31339   }
31340   /* write it out to the temporary break file */
31341   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
31342   if( fd<0 ){
31343     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
31344     goto end_breaklock;
31345   }
31346   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
31347     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
31348     goto end_breaklock;
31349   }
31350   if( rename(tPath, cPath) ){
31351     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
31352     goto end_breaklock;
31353   }
31354   rc = 0;
31355   fprintf(stderr, "broke stale lock on %s\n", cPath);
31356   robust_close(pFile, conchFile->h, __LINE__);
31357   conchFile->h = fd;
31358   conchFile->openFlags = O_RDWR | O_CREAT;
31359
31360 end_breaklock:
31361   if( rc ){
31362     if( fd>=0 ){
31363       osUnlink(tPath);
31364       robust_close(pFile, fd, __LINE__);
31365     }
31366     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
31367   }
31368   return rc;
31369 }
31370
31371 /* Take the requested lock on the conch file and break a stale lock if the
31372 ** host id matches.
31373 */
31374 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
31375   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31376   unixFile *conchFile = pCtx->conchFile;
31377   int rc = SQLITE_OK;
31378   int nTries = 0;
31379   struct timespec conchModTime;
31380
31381   memset(&conchModTime, 0, sizeof(conchModTime));
31382   do {
31383     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31384     nTries ++;
31385     if( rc==SQLITE_BUSY ){
31386       /* If the lock failed (busy):
31387        * 1st try: get the mod time of the conch, wait 0.5s and try again.
31388        * 2nd try: fail if the mod time changed or host id is different, wait
31389        *           10 sec and try again
31390        * 3rd try: break the lock unless the mod time has changed.
31391        */
31392       struct stat buf;
31393       if( osFstat(conchFile->h, &buf) ){
31394         pFile->lastErrno = errno;
31395         return SQLITE_IOERR_LOCK;
31396       }
31397
31398       if( nTries==1 ){
31399         conchModTime = buf.st_mtimespec;
31400         usleep(500000); /* wait 0.5 sec and try the lock again*/
31401         continue;
31402       }
31403
31404       assert( nTries>1 );
31405       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
31406          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
31407         return SQLITE_BUSY;
31408       }
31409
31410       if( nTries==2 ){
31411         char tBuf[PROXY_MAXCONCHLEN];
31412         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
31413         if( len<0 ){
31414           pFile->lastErrno = errno;
31415           return SQLITE_IOERR_LOCK;
31416         }
31417         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
31418           /* don't break the lock if the host id doesn't match */
31419           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
31420             return SQLITE_BUSY;
31421           }
31422         }else{
31423           /* don't break the lock on short read or a version mismatch */
31424           return SQLITE_BUSY;
31425         }
31426         usleep(10000000); /* wait 10 sec and try the lock again */
31427         continue;
31428       }
31429
31430       assert( nTries==3 );
31431       if( 0==proxyBreakConchLock(pFile, myHostID) ){
31432         rc = SQLITE_OK;
31433         if( lockType==EXCLUSIVE_LOCK ){
31434           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
31435         }
31436         if( !rc ){
31437           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31438         }
31439       }
31440     }
31441   } while( rc==SQLITE_BUSY && nTries<3 );
31442
31443   return rc;
31444 }
31445
31446 /* Takes the conch by taking a shared lock and read the contents conch, if
31447 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
31448 ** lockPath means that the lockPath in the conch file will be used if the
31449 ** host IDs match, or a new lock path will be generated automatically
31450 ** and written to the conch file.
31451 */
31452 static int proxyTakeConch(unixFile *pFile){
31453   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31454
31455   if( pCtx->conchHeld!=0 ){
31456     return SQLITE_OK;
31457   }else{
31458     unixFile *conchFile = pCtx->conchFile;
31459     uuid_t myHostID;
31460     int pError = 0;
31461     char readBuf[PROXY_MAXCONCHLEN];
31462     char lockPath[MAXPATHLEN];
31463     char *tempLockPath = NULL;
31464     int rc = SQLITE_OK;
31465     int createConch = 0;
31466     int hostIdMatch = 0;
31467     int readLen = 0;
31468     int tryOldLockPath = 0;
31469     int forceNewLockPath = 0;
31470
31471     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
31472              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
31473
31474     rc = proxyGetHostID(myHostID, &pError);
31475     if( (rc&0xff)==SQLITE_IOERR ){
31476       pFile->lastErrno = pError;
31477       goto end_takeconch;
31478     }
31479     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
31480     if( rc!=SQLITE_OK ){
31481       goto end_takeconch;
31482     }
31483     /* read the existing conch file */
31484     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
31485     if( readLen<0 ){
31486       /* I/O error: lastErrno set by seekAndRead */
31487       pFile->lastErrno = conchFile->lastErrno;
31488       rc = SQLITE_IOERR_READ;
31489       goto end_takeconch;
31490     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
31491              readBuf[0]!=(char)PROXY_CONCHVERSION ){
31492       /* a short read or version format mismatch means we need to create a new
31493       ** conch file.
31494       */
31495       createConch = 1;
31496     }
31497     /* if the host id matches and the lock path already exists in the conch
31498     ** we'll try to use the path there, if we can't open that path, we'll
31499     ** retry with a new auto-generated path
31500     */
31501     do { /* in case we need to try again for an :auto: named lock file */
31502
31503       if( !createConch && !forceNewLockPath ){
31504         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
31505                                   PROXY_HOSTIDLEN);
31506         /* if the conch has data compare the contents */
31507         if( !pCtx->lockProxyPath ){
31508           /* for auto-named local lock file, just check the host ID and we'll
31509            ** use the local lock file path that's already in there
31510            */
31511           if( hostIdMatch ){
31512             size_t pathLen = (readLen - PROXY_PATHINDEX);
31513
31514             if( pathLen>=MAXPATHLEN ){
31515               pathLen=MAXPATHLEN-1;
31516             }
31517             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
31518             lockPath[pathLen] = 0;
31519             tempLockPath = lockPath;
31520             tryOldLockPath = 1;
31521             /* create a copy of the lock path if the conch is taken */
31522             goto end_takeconch;
31523           }
31524         }else if( hostIdMatch
31525                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
31526                            readLen-PROXY_PATHINDEX)
31527         ){
31528           /* conch host and lock path match */
31529           goto end_takeconch;
31530         }
31531       }
31532
31533       /* if the conch isn't writable and doesn't match, we can't take it */
31534       if( (conchFile->openFlags&O_RDWR) == 0 ){
31535         rc = SQLITE_BUSY;
31536         goto end_takeconch;
31537       }
31538
31539       /* either the conch didn't match or we need to create a new one */
31540       if( !pCtx->lockProxyPath ){
31541         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
31542         tempLockPath = lockPath;
31543         /* create a copy of the lock path _only_ if the conch is taken */
31544       }
31545
31546       /* update conch with host and path (this will fail if other process
31547       ** has a shared lock already), if the host id matches, use the big
31548       ** stick.
31549       */
31550       futimes(conchFile->h, NULL);
31551       if( hostIdMatch && !createConch ){
31552         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
31553           /* We are trying for an exclusive lock but another thread in this
31554            ** same process is still holding a shared lock. */
31555           rc = SQLITE_BUSY;
31556         } else {
31557           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
31558         }
31559       }else{
31560         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
31561       }
31562       if( rc==SQLITE_OK ){
31563         char writeBuffer[PROXY_MAXCONCHLEN];
31564         int writeSize = 0;
31565
31566         writeBuffer[0] = (char)PROXY_CONCHVERSION;
31567         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
31568         if( pCtx->lockProxyPath!=NULL ){
31569           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
31570         }else{
31571           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
31572         }
31573         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
31574         robust_ftruncate(conchFile->h, writeSize);
31575         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
31576         fsync(conchFile->h);
31577         /* If we created a new conch file (not just updated the contents of a
31578          ** valid conch file), try to match the permissions of the database
31579          */
31580         if( rc==SQLITE_OK && createConch ){
31581           struct stat buf;
31582           int err = osFstat(pFile->h, &buf);
31583           if( err==0 ){
31584             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
31585                                         S_IROTH|S_IWOTH);
31586             /* try to match the database file R/W permissions, ignore failure */
31587 #ifndef SQLITE_PROXY_DEBUG
31588             osFchmod(conchFile->h, cmode);
31589 #else
31590             do{
31591               rc = osFchmod(conchFile->h, cmode);
31592             }while( rc==(-1) && errno==EINTR );
31593             if( rc!=0 ){
31594               int code = errno;
31595               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
31596                       cmode, code, strerror(code));
31597             } else {
31598               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
31599             }
31600           }else{
31601             int code = errno;
31602             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
31603                     err, code, strerror(code));
31604 #endif
31605           }
31606         }
31607       }
31608       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
31609
31610     end_takeconch:
31611       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
31612       if( rc==SQLITE_OK && pFile->openFlags ){
31613         int fd;
31614         if( pFile->h>=0 ){
31615           robust_close(pFile, pFile->h, __LINE__);
31616         }
31617         pFile->h = -1;
31618         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
31619         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
31620         if( fd>=0 ){
31621           pFile->h = fd;
31622         }else{
31623           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
31624            during locking */
31625         }
31626       }
31627       if( rc==SQLITE_OK && !pCtx->lockProxy ){
31628         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
31629         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
31630         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
31631           /* we couldn't create the proxy lock file with the old lock file path
31632            ** so try again via auto-naming
31633            */
31634           forceNewLockPath = 1;
31635           tryOldLockPath = 0;
31636           continue; /* go back to the do {} while start point, try again */
31637         }
31638       }
31639       if( rc==SQLITE_OK ){
31640         /* Need to make a copy of path if we extracted the value
31641          ** from the conch file or the path was allocated on the stack
31642          */
31643         if( tempLockPath ){
31644           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
31645           if( !pCtx->lockProxyPath ){
31646             rc = SQLITE_NOMEM;
31647           }
31648         }
31649       }
31650       if( rc==SQLITE_OK ){
31651         pCtx->conchHeld = 1;
31652
31653         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
31654           afpLockingContext *afpCtx;
31655           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
31656           afpCtx->dbPath = pCtx->lockProxyPath;
31657         }
31658       } else {
31659         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31660       }
31661       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
31662                rc==SQLITE_OK?"ok":"failed"));
31663       return rc;
31664     } while (1); /* in case we need to retry the :auto: lock file -
31665                  ** we should never get here except via the 'continue' call. */
31666   }
31667 }
31668
31669 /*
31670 ** If pFile holds a lock on a conch file, then release that lock.
31671 */
31672 static int proxyReleaseConch(unixFile *pFile){
31673   int rc = SQLITE_OK;         /* Subroutine return code */
31674   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
31675   unixFile *conchFile;        /* Name of the conch file */
31676
31677   pCtx = (proxyLockingContext *)pFile->lockingContext;
31678   conchFile = pCtx->conchFile;
31679   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
31680            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
31681            getpid()));
31682   if( pCtx->conchHeld>0 ){
31683     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31684   }
31685   pCtx->conchHeld = 0;
31686   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
31687            (rc==SQLITE_OK ? "ok" : "failed")));
31688   return rc;
31689 }
31690
31691 /*
31692 ** Given the name of a database file, compute the name of its conch file.
31693 ** Store the conch filename in memory obtained from sqlite3_malloc().
31694 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
31695 ** or SQLITE_NOMEM if unable to obtain memory.
31696 **
31697 ** The caller is responsible for ensuring that the allocated memory
31698 ** space is eventually freed.
31699 **
31700 ** *pConchPath is set to NULL if a memory allocation error occurs.
31701 */
31702 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
31703   int i;                        /* Loop counter */
31704   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
31705   char *conchPath;              /* buffer in which to construct conch name */
31706
31707   /* Allocate space for the conch filename and initialize the name to
31708   ** the name of the original database file. */
31709   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
31710   if( conchPath==0 ){
31711     return SQLITE_NOMEM;
31712   }
31713   memcpy(conchPath, dbPath, len+1);
31714
31715   /* now insert a "." before the last / character */
31716   for( i=(len-1); i>=0; i-- ){
31717     if( conchPath[i]=='/' ){
31718       i++;
31719       break;
31720     }
31721   }
31722   conchPath[i]='.';
31723   while ( i<len ){
31724     conchPath[i+1]=dbPath[i];
31725     i++;
31726   }
31727
31728   /* append the "-conch" suffix to the file */
31729   memcpy(&conchPath[i+1], "-conch", 7);
31730   assert( (int)strlen(conchPath) == len+7 );
31731
31732   return SQLITE_OK;
31733 }
31734
31735
31736 /* Takes a fully configured proxy locking-style unix file and switches
31737 ** the local lock file path
31738 */
31739 static int switchLockProxyPath(unixFile *pFile, const char *path) {
31740   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31741   char *oldPath = pCtx->lockProxyPath;
31742   int rc = SQLITE_OK;
31743
31744   if( pFile->eFileLock!=NO_LOCK ){
31745     return SQLITE_BUSY;
31746   }
31747
31748   /* nothing to do if the path is NULL, :auto: or matches the existing path */
31749   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
31750     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
31751     return SQLITE_OK;
31752   }else{
31753     unixFile *lockProxy = pCtx->lockProxy;
31754     pCtx->lockProxy=NULL;
31755     pCtx->conchHeld = 0;
31756     if( lockProxy!=NULL ){
31757       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
31758       if( rc ) return rc;
31759       sqlite3_free(lockProxy);
31760     }
31761     sqlite3_free(oldPath);
31762     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
31763   }
31764
31765   return rc;
31766 }
31767
31768 /*
31769 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
31770 ** is a string buffer at least MAXPATHLEN+1 characters in size.
31771 **
31772 ** This routine find the filename associated with pFile and writes it
31773 ** int dbPath.
31774 */
31775 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
31776 #if defined(__APPLE__)
31777   if( pFile->pMethod == &afpIoMethods ){
31778     /* afp style keeps a reference to the db path in the filePath field
31779     ** of the struct */
31780     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31781     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
31782   } else
31783 #endif
31784   if( pFile->pMethod == &dotlockIoMethods ){
31785     /* dot lock style uses the locking context to store the dot lock
31786     ** file path */
31787     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
31788     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
31789   }else{
31790     /* all other styles use the locking context to store the db file path */
31791     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31792     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
31793   }
31794   return SQLITE_OK;
31795 }
31796
31797 /*
31798 ** Takes an already filled in unix file and alters it so all file locking
31799 ** will be performed on the local proxy lock file.  The following fields
31800 ** are preserved in the locking context so that they can be restored and
31801 ** the unix structure properly cleaned up at close time:
31802 **  ->lockingContext
31803 **  ->pMethod
31804 */
31805 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
31806   proxyLockingContext *pCtx;
31807   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
31808   char *lockPath=NULL;
31809   int rc = SQLITE_OK;
31810
31811   if( pFile->eFileLock!=NO_LOCK ){
31812     return SQLITE_BUSY;
31813   }
31814   proxyGetDbPathForUnixFile(pFile, dbPath);
31815   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
31816     lockPath=NULL;
31817   }else{
31818     lockPath=(char *)path;
31819   }
31820
31821   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
31822            (lockPath ? lockPath : ":auto:"), getpid()));
31823
31824   pCtx = sqlite3_malloc( sizeof(*pCtx) );
31825   if( pCtx==0 ){
31826     return SQLITE_NOMEM;
31827   }
31828   memset(pCtx, 0, sizeof(*pCtx));
31829
31830   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
31831   if( rc==SQLITE_OK ){
31832     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
31833     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
31834       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
31835       ** (c) the file system is read-only, then enable no-locking access.
31836       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
31837       ** that openFlags will have only one of O_RDONLY or O_RDWR.
31838       */
31839       struct statfs fsInfo;
31840       struct stat conchInfo;
31841       int goLockless = 0;
31842
31843       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
31844         int err = errno;
31845         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
31846           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
31847         }
31848       }
31849       if( goLockless ){
31850         pCtx->conchHeld = -1; /* read only FS/ lockless */
31851         rc = SQLITE_OK;
31852       }
31853     }
31854   }
31855   if( rc==SQLITE_OK && lockPath ){
31856     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
31857   }
31858
31859   if( rc==SQLITE_OK ){
31860     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31861     if( pCtx->dbPath==NULL ){
31862       rc = SQLITE_NOMEM;
31863     }
31864   }
31865   if( rc==SQLITE_OK ){
31866     /* all memory is allocated, proxys are created and assigned,
31867     ** switch the locking context and pMethod then return.
31868     */
31869     pCtx->oldLockingContext = pFile->lockingContext;
31870     pFile->lockingContext = pCtx;
31871     pCtx->pOldMethod = pFile->pMethod;
31872     pFile->pMethod = &proxyIoMethods;
31873   }else{
31874     if( pCtx->conchFile ){
31875       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
31876       sqlite3_free(pCtx->conchFile);
31877     }
31878     sqlite3DbFree(0, pCtx->lockProxyPath);
31879     sqlite3_free(pCtx->conchFilePath);
31880     sqlite3_free(pCtx);
31881   }
31882   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
31883            (rc==SQLITE_OK ? "ok" : "failed")));
31884   return rc;
31885 }
31886
31887
31888 /*
31889 ** This routine handles sqlite3_file_control() calls that are specific
31890 ** to proxy locking.
31891 */
31892 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
31893   switch( op ){
31894     case SQLITE_GET_LOCKPROXYFILE: {
31895       unixFile *pFile = (unixFile*)id;
31896       if( pFile->pMethod == &proxyIoMethods ){
31897         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31898         proxyTakeConch(pFile);
31899         if( pCtx->lockProxyPath ){
31900           *(const char **)pArg = pCtx->lockProxyPath;
31901         }else{
31902           *(const char **)pArg = ":auto: (not held)";
31903         }
31904       } else {
31905         *(const char **)pArg = NULL;
31906       }
31907       return SQLITE_OK;
31908     }
31909     case SQLITE_SET_LOCKPROXYFILE: {
31910       unixFile *pFile = (unixFile*)id;
31911       int rc = SQLITE_OK;
31912       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
31913       if( pArg==NULL || (const char *)pArg==0 ){
31914         if( isProxyStyle ){
31915           /* turn off proxy locking - not supported */
31916           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
31917         }else{
31918           /* turn off proxy locking - already off - NOOP */
31919           rc = SQLITE_OK;
31920         }
31921       }else{
31922         const char *proxyPath = (const char *)pArg;
31923         if( isProxyStyle ){
31924           proxyLockingContext *pCtx =
31925             (proxyLockingContext*)pFile->lockingContext;
31926           if( !strcmp(pArg, ":auto:")
31927            || (pCtx->lockProxyPath &&
31928                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
31929           ){
31930             rc = SQLITE_OK;
31931           }else{
31932             rc = switchLockProxyPath(pFile, proxyPath);
31933           }
31934         }else{
31935           /* turn on proxy file locking */
31936           rc = proxyTransformUnixFile(pFile, proxyPath);
31937         }
31938       }
31939       return rc;
31940     }
31941     default: {
31942       assert( 0 );  /* The call assures that only valid opcodes are sent */
31943     }
31944   }
31945   /*NOTREACHED*/
31946   return SQLITE_ERROR;
31947 }
31948
31949 /*
31950 ** Within this division (the proxying locking implementation) the procedures
31951 ** above this point are all utilities.  The lock-related methods of the
31952 ** proxy-locking sqlite3_io_method object follow.
31953 */
31954
31955
31956 /*
31957 ** This routine checks if there is a RESERVED lock held on the specified
31958 ** file by this or any other process. If such a lock is held, set *pResOut
31959 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
31960 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31961 */
31962 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
31963   unixFile *pFile = (unixFile*)id;
31964   int rc = proxyTakeConch(pFile);
31965   if( rc==SQLITE_OK ){
31966     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31967     if( pCtx->conchHeld>0 ){
31968       unixFile *proxy = pCtx->lockProxy;
31969       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
31970     }else{ /* conchHeld < 0 is lockless */
31971       pResOut=0;
31972     }
31973   }
31974   return rc;
31975 }
31976
31977 /*
31978 ** Lock the file with the lock specified by parameter eFileLock - one
31979 ** of the following:
31980 **
31981 **     (1) SHARED_LOCK
31982 **     (2) RESERVED_LOCK
31983 **     (3) PENDING_LOCK
31984 **     (4) EXCLUSIVE_LOCK
31985 **
31986 ** Sometimes when requesting one lock state, additional lock states
31987 ** are inserted in between.  The locking might fail on one of the later
31988 ** transitions leaving the lock state different from what it started but
31989 ** still short of its goal.  The following chart shows the allowed
31990 ** transitions and the inserted intermediate states:
31991 **
31992 **    UNLOCKED -> SHARED
31993 **    SHARED -> RESERVED
31994 **    SHARED -> (PENDING) -> EXCLUSIVE
31995 **    RESERVED -> (PENDING) -> EXCLUSIVE
31996 **    PENDING -> EXCLUSIVE
31997 **
31998 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31999 ** routine to lower a locking level.
32000 */
32001 static int proxyLock(sqlite3_file *id, int eFileLock) {
32002   unixFile *pFile = (unixFile*)id;
32003   int rc = proxyTakeConch(pFile);
32004   if( rc==SQLITE_OK ){
32005     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32006     if( pCtx->conchHeld>0 ){
32007       unixFile *proxy = pCtx->lockProxy;
32008       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
32009       pFile->eFileLock = proxy->eFileLock;
32010     }else{
32011       /* conchHeld < 0 is lockless */
32012     }
32013   }
32014   return rc;
32015 }
32016
32017
32018 /*
32019 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32020 ** must be either NO_LOCK or SHARED_LOCK.
32021 **
32022 ** If the locking level of the file descriptor is already at or below
32023 ** the requested locking level, this routine is a no-op.
32024 */
32025 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
32026   unixFile *pFile = (unixFile*)id;
32027   int rc = proxyTakeConch(pFile);
32028   if( rc==SQLITE_OK ){
32029     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32030     if( pCtx->conchHeld>0 ){
32031       unixFile *proxy = pCtx->lockProxy;
32032       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
32033       pFile->eFileLock = proxy->eFileLock;
32034     }else{
32035       /* conchHeld < 0 is lockless */
32036     }
32037   }
32038   return rc;
32039 }
32040
32041 /*
32042 ** Close a file that uses proxy locks.
32043 */
32044 static int proxyClose(sqlite3_file *id) {
32045   if( id ){
32046     unixFile *pFile = (unixFile*)id;
32047     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32048     unixFile *lockProxy = pCtx->lockProxy;
32049     unixFile *conchFile = pCtx->conchFile;
32050     int rc = SQLITE_OK;
32051
32052     if( lockProxy ){
32053       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
32054       if( rc ) return rc;
32055       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
32056       if( rc ) return rc;
32057       sqlite3_free(lockProxy);
32058       pCtx->lockProxy = 0;
32059     }
32060     if( conchFile ){
32061       if( pCtx->conchHeld ){
32062         rc = proxyReleaseConch(pFile);
32063         if( rc ) return rc;
32064       }
32065       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
32066       if( rc ) return rc;
32067       sqlite3_free(conchFile);
32068     }
32069     sqlite3DbFree(0, pCtx->lockProxyPath);
32070     sqlite3_free(pCtx->conchFilePath);
32071     sqlite3DbFree(0, pCtx->dbPath);
32072     /* restore the original locking context and pMethod then close it */
32073     pFile->lockingContext = pCtx->oldLockingContext;
32074     pFile->pMethod = pCtx->pOldMethod;
32075     sqlite3_free(pCtx);
32076     return pFile->pMethod->xClose(id);
32077   }
32078   return SQLITE_OK;
32079 }
32080
32081
32082
32083 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32084 /*
32085 ** The proxy locking style is intended for use with AFP filesystems.
32086 ** And since AFP is only supported on MacOSX, the proxy locking is also
32087 ** restricted to MacOSX.
32088 **
32089 **
32090 ******************* End of the proxy lock implementation **********************
32091 ******************************************************************************/
32092
32093 /*
32094 ** Initialize the operating system interface.
32095 **
32096 ** This routine registers all VFS implementations for unix-like operating
32097 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
32098 ** should be the only routines in this file that are visible from other
32099 ** files.
32100 **
32101 ** This routine is called once during SQLite initialization and by a
32102 ** single thread.  The memory allocation and mutex subsystems have not
32103 ** necessarily been initialized when this routine is called, and so they
32104 ** should not be used.
32105 */
32106 SQLITE_API int sqlite3_os_init(void){
32107   /*
32108   ** The following macro defines an initializer for an sqlite3_vfs object.
32109   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
32110   ** to the "finder" function.  (pAppData is a pointer to a pointer because
32111   ** silly C90 rules prohibit a void* from being cast to a function pointer
32112   ** and so we have to go through the intermediate pointer to avoid problems
32113   ** when compiling with -pedantic-errors on GCC.)
32114   **
32115   ** The FINDER parameter to this macro is the name of the pointer to the
32116   ** finder-function.  The finder-function returns a pointer to the
32117   ** sqlite_io_methods object that implements the desired locking
32118   ** behaviors.  See the division above that contains the IOMETHODS
32119   ** macro for addition information on finder-functions.
32120   **
32121   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
32122   ** object.  But the "autolockIoFinder" available on MacOSX does a little
32123   ** more than that; it looks at the filesystem type that hosts the
32124   ** database file and tries to choose an locking method appropriate for
32125   ** that filesystem time.
32126   */
32127   #define UNIXVFS(VFSNAME, FINDER) {                        \
32128     3,                    /* iVersion */                    \
32129     sizeof(unixFile),     /* szOsFile */                    \
32130     MAX_PATHNAME,         /* mxPathname */                  \
32131     0,                    /* pNext */                       \
32132     VFSNAME,              /* zName */                       \
32133     (void*)&FINDER,       /* pAppData */                    \
32134     unixOpen,             /* xOpen */                       \
32135     unixDelete,           /* xDelete */                     \
32136     unixAccess,           /* xAccess */                     \
32137     unixFullPathname,     /* xFullPathname */               \
32138     unixDlOpen,           /* xDlOpen */                     \
32139     unixDlError,          /* xDlError */                    \
32140     unixDlSym,            /* xDlSym */                      \
32141     unixDlClose,          /* xDlClose */                    \
32142     unixRandomness,       /* xRandomness */                 \
32143     unixSleep,            /* xSleep */                      \
32144     unixCurrentTime,      /* xCurrentTime */                \
32145     unixGetLastError,     /* xGetLastError */               \
32146     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
32147     unixSetSystemCall,    /* xSetSystemCall */              \
32148     unixGetSystemCall,    /* xGetSystemCall */              \
32149     unixNextSystemCall,   /* xNextSystemCall */             \
32150   }
32151
32152   /*
32153   ** All default VFSes for unix are contained in the following array.
32154   **
32155   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
32156   ** by the SQLite core when the VFS is registered.  So the following
32157   ** array cannot be const.
32158   */
32159   static sqlite3_vfs aVfs[] = {
32160 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
32161     UNIXVFS("unix",          autolockIoFinder ),
32162 #else
32163     UNIXVFS("unix",          posixIoFinder ),
32164 #endif
32165     UNIXVFS("unix-none",     nolockIoFinder ),
32166     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
32167     UNIXVFS("unix-excl",     posixIoFinder ),
32168 #if OS_VXWORKS
32169     UNIXVFS("unix-namedsem", semIoFinder ),
32170 #endif
32171 #if SQLITE_ENABLE_LOCKING_STYLE
32172     UNIXVFS("unix-posix",    posixIoFinder ),
32173 #if !OS_VXWORKS
32174     UNIXVFS("unix-flock",    flockIoFinder ),
32175 #endif
32176 #endif
32177 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32178     UNIXVFS("unix-afp",      afpIoFinder ),
32179     UNIXVFS("unix-nfs",      nfsIoFinder ),
32180     UNIXVFS("unix-proxy",    proxyIoFinder ),
32181 #endif
32182   };
32183   unsigned int i;          /* Loop counter */
32184
32185   /* Double-check that the aSyscall[] array has been constructed
32186   ** correctly.  See ticket [bb3a86e890c8e96ab] */
32187   assert( ArraySize(aSyscall)==22 );
32188
32189   /* Register all VFSes defined in the aVfs[] array */
32190   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
32191     sqlite3_vfs_register(&aVfs[i], i==0);
32192   }
32193   return SQLITE_OK;
32194 }
32195
32196 /*
32197 ** Shutdown the operating system interface.
32198 **
32199 ** Some operating systems might need to do some cleanup in this routine,
32200 ** to release dynamically allocated objects.  But not on unix.
32201 ** This routine is a no-op for unix.
32202 */
32203 SQLITE_API int sqlite3_os_end(void){
32204   return SQLITE_OK;
32205 }
32206
32207 #endif /* SQLITE_OS_UNIX */
32208
32209 /************** End of os_unix.c *********************************************/
32210 /************** Begin file os_win.c ******************************************/
32211 /*
32212 ** 2004 May 22
32213 **
32214 ** The author disclaims copyright to this source code.  In place of
32215 ** a legal notice, here is a blessing:
32216 **
32217 **    May you do good and not evil.
32218 **    May you find forgiveness for yourself and forgive others.
32219 **    May you share freely, never taking more than you give.
32220 **
32221 ******************************************************************************
32222 **
32223 ** This file contains code that is specific to Windows.
32224 */
32225 #if SQLITE_OS_WIN               /* This file is used for Windows only */
32226
32227 #ifdef __CYGWIN__
32228 # include <sys/cygwin.h>
32229 #endif
32230
32231 /*
32232 ** Include code that is common to all os_*.c files
32233 */
32234 /************** Include os_common.h in the middle of os_win.c ****************/
32235 /************** Begin file os_common.h ***************************************/
32236 /*
32237 ** 2004 May 22
32238 **
32239 ** The author disclaims copyright to this source code.  In place of
32240 ** a legal notice, here is a blessing:
32241 **
32242 **    May you do good and not evil.
32243 **    May you find forgiveness for yourself and forgive others.
32244 **    May you share freely, never taking more than you give.
32245 **
32246 ******************************************************************************
32247 **
32248 ** This file contains macros and a little bit of code that is common to
32249 ** all of the platform-specific files (os_*.c) and is #included into those
32250 ** files.
32251 **
32252 ** This file should be #included by the os_*.c files only.  It is not a
32253 ** general purpose header file.
32254 */
32255 #ifndef _OS_COMMON_H_
32256 #define _OS_COMMON_H_
32257
32258 /*
32259 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
32260 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
32261 ** switch.  The following code should catch this problem at compile-time.
32262 */
32263 #ifdef MEMORY_DEBUG
32264 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
32265 #endif
32266
32267 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
32268 # ifndef SQLITE_DEBUG_OS_TRACE
32269 #   define SQLITE_DEBUG_OS_TRACE 0
32270 # endif
32271   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
32272 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
32273 #else
32274 # define OSTRACE(X)
32275 #endif
32276
32277 /*
32278 ** Macros for performance tracing.  Normally turned off.  Only works
32279 ** on i486 hardware.
32280 */
32281 #ifdef SQLITE_PERFORMANCE_TRACE
32282
32283 /*
32284 ** hwtime.h contains inline assembler code for implementing
32285 ** high-performance timing routines.
32286 */
32287 /************** Include hwtime.h in the middle of os_common.h ****************/
32288 /************** Begin file hwtime.h ******************************************/
32289 /*
32290 ** 2008 May 27
32291 **
32292 ** The author disclaims copyright to this source code.  In place of
32293 ** a legal notice, here is a blessing:
32294 **
32295 **    May you do good and not evil.
32296 **    May you find forgiveness for yourself and forgive others.
32297 **    May you share freely, never taking more than you give.
32298 **
32299 ******************************************************************************
32300 **
32301 ** This file contains inline asm code for retrieving "high-performance"
32302 ** counters for x86 class CPUs.
32303 */
32304 #ifndef _HWTIME_H_
32305 #define _HWTIME_H_
32306
32307 /*
32308 ** The following routine only works on pentium-class (or newer) processors.
32309 ** It uses the RDTSC opcode to read the cycle count value out of the
32310 ** processor and returns that value.  This can be used for high-res
32311 ** profiling.
32312 */
32313 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
32314       (defined(i386) || defined(__i386__) || defined(_M_IX86))
32315
32316   #if defined(__GNUC__)
32317
32318   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32319      unsigned int lo, hi;
32320      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32321      return (sqlite_uint64)hi << 32 | lo;
32322   }
32323
32324   #elif defined(_MSC_VER)
32325
32326   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
32327      __asm {
32328         rdtsc
32329         ret       ; return value at EDX:EAX
32330      }
32331   }
32332
32333   #endif
32334
32335 #elif (defined(__GNUC__) && defined(__x86_64__))
32336
32337   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32338       unsigned long val;
32339       __asm__ __volatile__ ("rdtsc" : "=A" (val));
32340       return val;
32341   }
32342
32343 #elif (defined(__GNUC__) && defined(__ppc__))
32344
32345   __inline__ sqlite_uint64 sqlite3Hwtime(void){
32346       unsigned long long retval;
32347       unsigned long junk;
32348       __asm__ __volatile__ ("\n\
32349           1:      mftbu   %1\n\
32350                   mftb    %L0\n\
32351                   mftbu   %0\n\
32352                   cmpw    %0,%1\n\
32353                   bne     1b"
32354                   : "=r" (retval), "=r" (junk));
32355       return retval;
32356   }
32357
32358 #else
32359
32360   #error Need implementation of sqlite3Hwtime() for your platform.
32361
32362   /*
32363   ** To compile without implementing sqlite3Hwtime() for your platform,
32364   ** you can remove the above #error and use the following
32365   ** stub function.  You will lose timing support for many
32366   ** of the debugging and testing utilities, but it should at
32367   ** least compile and run.
32368   */
32369 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
32370
32371 #endif
32372
32373 #endif /* !defined(_HWTIME_H_) */
32374
32375 /************** End of hwtime.h **********************************************/
32376 /************** Continuing where we left off in os_common.h ******************/
32377
32378 static sqlite_uint64 g_start;
32379 static sqlite_uint64 g_elapsed;
32380 #define TIMER_START       g_start=sqlite3Hwtime()
32381 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
32382 #define TIMER_ELAPSED     g_elapsed
32383 #else
32384 #define TIMER_START
32385 #define TIMER_END
32386 #define TIMER_ELAPSED     ((sqlite_uint64)0)
32387 #endif
32388
32389 /*
32390 ** If we compile with the SQLITE_TEST macro set, then the following block
32391 ** of code will give us the ability to simulate a disk I/O error.  This
32392 ** is used for testing the I/O recovery logic.
32393 */
32394 #ifdef SQLITE_TEST
32395 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
32396 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
32397 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
32398 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
32399 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
32400 SQLITE_API int sqlite3_diskfull_pending = 0;
32401 SQLITE_API int sqlite3_diskfull = 0;
32402 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
32403 #define SimulateIOError(CODE)  \
32404   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
32405        || sqlite3_io_error_pending-- == 1 )  \
32406               { local_ioerr(); CODE; }
32407 static void local_ioerr(){
32408   IOTRACE(("IOERR\n"));
32409   sqlite3_io_error_hit++;
32410   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
32411 }
32412 #define SimulateDiskfullError(CODE) \
32413    if( sqlite3_diskfull_pending ){ \
32414      if( sqlite3_diskfull_pending == 1 ){ \
32415        local_ioerr(); \
32416        sqlite3_diskfull = 1; \
32417        sqlite3_io_error_hit = 1; \
32418        CODE; \
32419      }else{ \
32420        sqlite3_diskfull_pending--; \
32421      } \
32422    }
32423 #else
32424 #define SimulateIOErrorBenign(X)
32425 #define SimulateIOError(A)
32426 #define SimulateDiskfullError(A)
32427 #endif
32428
32429 /*
32430 ** When testing, keep a count of the number of open files.
32431 */
32432 #ifdef SQLITE_TEST
32433 SQLITE_API int sqlite3_open_file_count = 0;
32434 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
32435 #else
32436 #define OpenCounter(X)
32437 #endif
32438
32439 #endif /* !defined(_OS_COMMON_H_) */
32440
32441 /************** End of os_common.h *******************************************/
32442 /************** Continuing where we left off in os_win.c *********************/
32443
32444 /*
32445 ** Compiling and using WAL mode requires several APIs that are only
32446 ** available in Windows platforms based on the NT kernel.
32447 */
32448 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
32449 # error "WAL mode requires support from the Windows NT kernel, compile\
32450  with SQLITE_OMIT_WAL."
32451 #endif
32452
32453 /*
32454 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
32455 ** based on the sub-platform)?
32456 */
32457 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32458 #  define SQLITE_WIN32_HAS_ANSI
32459 #endif
32460
32461 /*
32462 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
32463 ** based on the sub-platform)?
32464 */
32465 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
32466 #  define SQLITE_WIN32_HAS_WIDE
32467 #endif
32468
32469 /*
32470 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
32471 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
32472 ** are not present in the header file)?
32473 */
32474 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
32475 /*
32476 ** Two of the file mapping APIs are different under WinRT.  Figure out which
32477 ** set we need.
32478 */
32479 #if SQLITE_OS_WINRT
32480 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
32481         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
32482
32483 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
32484 #else
32485 #if defined(SQLITE_WIN32_HAS_ANSI)
32486 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
32487         DWORD, DWORD, DWORD, LPCSTR);
32488 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
32489
32490 #if defined(SQLITE_WIN32_HAS_WIDE)
32491 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
32492         DWORD, DWORD, DWORD, LPCWSTR);
32493 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
32494
32495 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
32496 #endif /* SQLITE_OS_WINRT */
32497
32498 /*
32499 ** This file mapping API is common to both Win32 and WinRT.
32500 */
32501 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
32502 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
32503
32504 /*
32505 ** Macro to find the minimum of two numeric values.
32506 */
32507 #ifndef MIN
32508 # define MIN(x,y) ((x)<(y)?(x):(y))
32509 #endif
32510
32511 /*
32512 ** Some Microsoft compilers lack this definition.
32513 */
32514 #ifndef INVALID_FILE_ATTRIBUTES
32515 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
32516 #endif
32517
32518 #ifndef FILE_FLAG_MASK
32519 # define FILE_FLAG_MASK          (0xFF3C0000)
32520 #endif
32521
32522 #ifndef FILE_ATTRIBUTE_MASK
32523 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
32524 #endif
32525
32526 #ifndef SQLITE_OMIT_WAL
32527 /* Forward references */
32528 typedef struct winShm winShm;           /* A connection to shared-memory */
32529 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
32530 #endif
32531
32532 /*
32533 ** WinCE lacks native support for file locking so we have to fake it
32534 ** with some code of our own.
32535 */
32536 #if SQLITE_OS_WINCE
32537 typedef struct winceLock {
32538   int nReaders;       /* Number of reader locks obtained */
32539   BOOL bPending;      /* Indicates a pending lock has been obtained */
32540   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
32541   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
32542 } winceLock;
32543 #endif
32544
32545 /*
32546 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
32547 ** portability layer.
32548 */
32549 typedef struct winFile winFile;
32550 struct winFile {
32551   const sqlite3_io_methods *pMethod; /*** Must be first ***/
32552   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
32553   HANDLE h;               /* Handle for accessing the file */
32554   u8 locktype;            /* Type of lock currently held on this file */
32555   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
32556   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
32557   DWORD lastErrno;        /* The Windows errno from the last I/O error */
32558 #ifndef SQLITE_OMIT_WAL
32559   winShm *pShm;           /* Instance of shared memory on this file */
32560 #endif
32561   const char *zPath;      /* Full pathname of this file */
32562   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
32563 #if SQLITE_OS_WINCE
32564   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
32565   HANDLE hMutex;          /* Mutex used to control access to shared lock */
32566   HANDLE hShared;         /* Shared memory segment used for locking */
32567   winceLock local;        /* Locks obtained by this instance of winFile */
32568   winceLock *shared;      /* Global shared lock memory for the file  */
32569 #endif
32570 };
32571
32572 /*
32573 ** Allowed values for winFile.ctrlFlags
32574 */
32575 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
32576 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
32577
32578 /*
32579  * The size of the buffer used by sqlite3_win32_write_debug().
32580  */
32581 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
32582 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
32583 #endif
32584
32585 /*
32586  * The value used with sqlite3_win32_set_directory() to specify that
32587  * the data directory should be changed.
32588  */
32589 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
32590 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
32591 #endif
32592
32593 /*
32594  * The value used with sqlite3_win32_set_directory() to specify that
32595  * the temporary directory should be changed.
32596  */
32597 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32598 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
32599 #endif
32600
32601 /*
32602  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
32603  * various Win32 API heap functions instead of our own.
32604  */
32605 #ifdef SQLITE_WIN32_MALLOC
32606
32607 /*
32608  * If this is non-zero, an isolated heap will be created by the native Win32
32609  * allocator subsystem; otherwise, the default process heap will be used.  This
32610  * setting has no effect when compiling for WinRT.  By default, this is enabled
32611  * and an isolated heap will be created to store all allocated data.
32612  *
32613  ******************************************************************************
32614  * WARNING: It is important to note that when this setting is non-zero and the
32615  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
32616  *          function), all data that was allocated using the isolated heap will
32617  *          be freed immediately and any attempt to access any of that freed
32618  *          data will almost certainly result in an immediate access violation.
32619  ******************************************************************************
32620  */
32621 #ifndef SQLITE_WIN32_HEAP_CREATE
32622 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
32623 #endif
32624
32625 /*
32626  * The initial size of the Win32-specific heap.  This value may be zero.
32627  */
32628 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
32629 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
32630                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
32631 #endif
32632
32633 /*
32634  * The maximum size of the Win32-specific heap.  This value may be zero.
32635  */
32636 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
32637 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
32638 #endif
32639
32640 /*
32641  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
32642  * zero for the default behavior.
32643  */
32644 #ifndef SQLITE_WIN32_HEAP_FLAGS
32645 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
32646 #endif
32647
32648 /*
32649 ** The winMemData structure stores information required by the Win32-specific
32650 ** sqlite3_mem_methods implementation.
32651 */
32652 typedef struct winMemData winMemData;
32653 struct winMemData {
32654 #ifndef NDEBUG
32655   u32 magic;    /* Magic number to detect structure corruption. */
32656 #endif
32657   HANDLE hHeap; /* The handle to our heap. */
32658   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
32659 };
32660
32661 #ifndef NDEBUG
32662 #define WINMEM_MAGIC     0x42b2830b
32663 #endif
32664
32665 static struct winMemData win_mem_data = {
32666 #ifndef NDEBUG
32667   WINMEM_MAGIC,
32668 #endif
32669   NULL, FALSE
32670 };
32671
32672 #ifndef NDEBUG
32673 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
32674 #else
32675 #define winMemAssertMagic()
32676 #endif
32677
32678 #define winMemGetHeap() win_mem_data.hHeap
32679
32680 static void *winMemMalloc(int nBytes);
32681 static void winMemFree(void *pPrior);
32682 static void *winMemRealloc(void *pPrior, int nBytes);
32683 static int winMemSize(void *p);
32684 static int winMemRoundup(int n);
32685 static int winMemInit(void *pAppData);
32686 static void winMemShutdown(void *pAppData);
32687
32688 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
32689 #endif /* SQLITE_WIN32_MALLOC */
32690
32691 /*
32692 ** The following variable is (normally) set once and never changes
32693 ** thereafter.  It records whether the operating system is Win9x
32694 ** or WinNT.
32695 **
32696 ** 0:   Operating system unknown.
32697 ** 1:   Operating system is Win9x.
32698 ** 2:   Operating system is WinNT.
32699 **
32700 ** In order to facilitate testing on a WinNT system, the test fixture
32701 ** can manually set this value to 1 to emulate Win98 behavior.
32702 */
32703 #ifdef SQLITE_TEST
32704 SQLITE_API int sqlite3_os_type = 0;
32705 #else
32706 static int sqlite3_os_type = 0;
32707 #endif
32708
32709 #ifndef SYSCALL
32710 #  define SYSCALL sqlite3_syscall_ptr
32711 #endif
32712
32713 /*
32714 ** This function is not available on Windows CE or WinRT.
32715  */
32716
32717 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
32718 #  define osAreFileApisANSI()       1
32719 #endif
32720
32721 /*
32722 ** Many system calls are accessed through pointer-to-functions so that
32723 ** they may be overridden at runtime to facilitate fault injection during
32724 ** testing and sandboxing.  The following array holds the names and pointers
32725 ** to all overrideable system calls.
32726 */
32727 static struct win_syscall {
32728   const char *zName;            /* Name of the sytem call */
32729   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
32730   sqlite3_syscall_ptr pDefault; /* Default value */
32731 } aSyscall[] = {
32732 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32733   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
32734 #else
32735   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
32736 #endif
32737
32738 #ifndef osAreFileApisANSI
32739 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
32740 #endif
32741
32742 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32743   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
32744 #else
32745   { "CharLowerW",              (SYSCALL)0,                       0 },
32746 #endif
32747
32748 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
32749
32750 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32751   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
32752 #else
32753   { "CharUpperW",              (SYSCALL)0,                       0 },
32754 #endif
32755
32756 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
32757
32758   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
32759
32760 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
32761
32762 #if defined(SQLITE_WIN32_HAS_ANSI)
32763   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
32764 #else
32765   { "CreateFileA",             (SYSCALL)0,                       0 },
32766 #endif
32767
32768 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
32769         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
32770
32771 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32772   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
32773 #else
32774   { "CreateFileW",             (SYSCALL)0,                       0 },
32775 #endif
32776
32777 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
32778         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
32779
32780 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
32781         !defined(SQLITE_OMIT_WAL))
32782   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
32783 #else
32784   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
32785 #endif
32786
32787 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32788         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
32789
32790 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
32791         !defined(SQLITE_OMIT_WAL))
32792   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
32793 #else
32794   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
32795 #endif
32796
32797 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32798         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
32799
32800 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32801   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
32802 #else
32803   { "CreateMutexW",            (SYSCALL)0,                       0 },
32804 #endif
32805
32806 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
32807         LPCWSTR))aSyscall[8].pCurrent)
32808
32809 #if defined(SQLITE_WIN32_HAS_ANSI)
32810   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
32811 #else
32812   { "DeleteFileA",             (SYSCALL)0,                       0 },
32813 #endif
32814
32815 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
32816
32817 #if defined(SQLITE_WIN32_HAS_WIDE)
32818   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
32819 #else
32820   { "DeleteFileW",             (SYSCALL)0,                       0 },
32821 #endif
32822
32823 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
32824
32825 #if SQLITE_OS_WINCE
32826   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
32827 #else
32828   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
32829 #endif
32830
32831 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32832         LPFILETIME))aSyscall[11].pCurrent)
32833
32834 #if SQLITE_OS_WINCE
32835   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
32836 #else
32837   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
32838 #endif
32839
32840 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32841         LPSYSTEMTIME))aSyscall[12].pCurrent)
32842
32843   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
32844
32845 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
32846
32847 #if defined(SQLITE_WIN32_HAS_ANSI)
32848   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
32849 #else
32850   { "FormatMessageA",          (SYSCALL)0,                       0 },
32851 #endif
32852
32853 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
32854         DWORD,va_list*))aSyscall[14].pCurrent)
32855
32856 #if defined(SQLITE_WIN32_HAS_WIDE)
32857   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
32858 #else
32859   { "FormatMessageW",          (SYSCALL)0,                       0 },
32860 #endif
32861
32862 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
32863         DWORD,va_list*))aSyscall[15].pCurrent)
32864
32865 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
32866   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
32867 #else
32868   { "FreeLibrary",             (SYSCALL)0,                       0 },
32869 #endif
32870
32871 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
32872
32873   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
32874
32875 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
32876
32877 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32878   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
32879 #else
32880   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
32881 #endif
32882
32883 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
32884         LPDWORD))aSyscall[18].pCurrent)
32885
32886 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32887   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
32888 #else
32889   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
32890 #endif
32891
32892 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
32893         LPDWORD))aSyscall[19].pCurrent)
32894
32895 #if defined(SQLITE_WIN32_HAS_ANSI)
32896   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
32897 #else
32898   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
32899 #endif
32900
32901 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
32902
32903 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32904   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
32905 #else
32906   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
32907 #endif
32908
32909 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
32910
32911 #if defined(SQLITE_WIN32_HAS_WIDE)
32912   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
32913 #else
32914   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
32915 #endif
32916
32917 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
32918         LPVOID))aSyscall[22].pCurrent)
32919
32920 #if !SQLITE_OS_WINRT
32921   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
32922 #else
32923   { "GetFileSize",             (SYSCALL)0,                       0 },
32924 #endif
32925
32926 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
32927
32928 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32929   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
32930 #else
32931   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
32932 #endif
32933
32934 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
32935         LPSTR*))aSyscall[24].pCurrent)
32936
32937 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32938   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
32939 #else
32940   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
32941 #endif
32942
32943 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
32944         LPWSTR*))aSyscall[25].pCurrent)
32945
32946   { "GetLastError",            (SYSCALL)GetLastError,            0 },
32947
32948 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
32949
32950 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
32951 #if SQLITE_OS_WINCE
32952   /* The GetProcAddressA() routine is only available on Windows CE. */
32953   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
32954 #else
32955   /* All other Windows platforms expect GetProcAddress() to take
32956   ** an ANSI string regardless of the _UNICODE setting */
32957   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
32958 #endif
32959 #else
32960   { "GetProcAddressA",         (SYSCALL)0,                       0 },
32961 #endif
32962
32963 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
32964         LPCSTR))aSyscall[27].pCurrent)
32965
32966 #if !SQLITE_OS_WINRT
32967   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
32968 #else
32969   { "GetSystemInfo",           (SYSCALL)0,                       0 },
32970 #endif
32971
32972 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
32973
32974   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
32975
32976 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
32977
32978 #if !SQLITE_OS_WINCE
32979   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
32980 #else
32981   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
32982 #endif
32983
32984 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
32985         LPFILETIME))aSyscall[30].pCurrent)
32986
32987 #if defined(SQLITE_WIN32_HAS_ANSI)
32988   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
32989 #else
32990   { "GetTempPathA",            (SYSCALL)0,                       0 },
32991 #endif
32992
32993 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
32994
32995 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32996   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
32997 #else
32998   { "GetTempPathW",            (SYSCALL)0,                       0 },
32999 #endif
33000
33001 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
33002
33003 #if !SQLITE_OS_WINRT
33004   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
33005 #else
33006   { "GetTickCount",            (SYSCALL)0,                       0 },
33007 #endif
33008
33009 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
33010
33011 #if defined(SQLITE_WIN32_HAS_ANSI)
33012   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
33013 #else
33014   { "GetVersionExA",           (SYSCALL)0,                       0 },
33015 #endif
33016
33017 #define osGetVersionExA ((BOOL(WINAPI*)( \
33018         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
33019
33020   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
33021
33022 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
33023         SIZE_T))aSyscall[35].pCurrent)
33024
33025 #if !SQLITE_OS_WINRT
33026   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
33027 #else
33028   { "HeapCreate",              (SYSCALL)0,                       0 },
33029 #endif
33030
33031 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
33032         SIZE_T))aSyscall[36].pCurrent)
33033
33034 #if !SQLITE_OS_WINRT
33035   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
33036 #else
33037   { "HeapDestroy",             (SYSCALL)0,                       0 },
33038 #endif
33039
33040 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
33041
33042   { "HeapFree",                (SYSCALL)HeapFree,                0 },
33043
33044 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
33045
33046   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
33047
33048 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
33049         SIZE_T))aSyscall[39].pCurrent)
33050
33051   { "HeapSize",                (SYSCALL)HeapSize,                0 },
33052
33053 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
33054         LPCVOID))aSyscall[40].pCurrent)
33055
33056 #if !SQLITE_OS_WINRT
33057   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
33058 #else
33059   { "HeapValidate",            (SYSCALL)0,                       0 },
33060 #endif
33061
33062 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
33063         LPCVOID))aSyscall[41].pCurrent)
33064
33065 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33066   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
33067 #else
33068   { "LoadLibraryA",            (SYSCALL)0,                       0 },
33069 #endif
33070
33071 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
33072
33073 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33074         !defined(SQLITE_OMIT_LOAD_EXTENSION)
33075   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
33076 #else
33077   { "LoadLibraryW",            (SYSCALL)0,                       0 },
33078 #endif
33079
33080 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
33081
33082 #if !SQLITE_OS_WINRT
33083   { "LocalFree",               (SYSCALL)LocalFree,               0 },
33084 #else
33085   { "LocalFree",               (SYSCALL)0,                       0 },
33086 #endif
33087
33088 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
33089
33090 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33091   { "LockFile",                (SYSCALL)LockFile,                0 },
33092 #else
33093   { "LockFile",                (SYSCALL)0,                       0 },
33094 #endif
33095
33096 #ifndef osLockFile
33097 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33098         DWORD))aSyscall[45].pCurrent)
33099 #endif
33100
33101 #if !SQLITE_OS_WINCE
33102   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
33103 #else
33104   { "LockFileEx",              (SYSCALL)0,                       0 },
33105 #endif
33106
33107 #ifndef osLockFileEx
33108 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
33109         LPOVERLAPPED))aSyscall[46].pCurrent)
33110 #endif
33111
33112 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
33113   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
33114 #else
33115   { "MapViewOfFile",           (SYSCALL)0,                       0 },
33116 #endif
33117
33118 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33119         SIZE_T))aSyscall[47].pCurrent)
33120
33121   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
33122
33123 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
33124         int))aSyscall[48].pCurrent)
33125
33126   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
33127
33128 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
33129         LARGE_INTEGER*))aSyscall[49].pCurrent)
33130
33131   { "ReadFile",                (SYSCALL)ReadFile,                0 },
33132
33133 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
33134         LPOVERLAPPED))aSyscall[50].pCurrent)
33135
33136   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
33137
33138 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
33139
33140 #if !SQLITE_OS_WINRT
33141   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
33142 #else
33143   { "SetFilePointer",          (SYSCALL)0,                       0 },
33144 #endif
33145
33146 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
33147         DWORD))aSyscall[52].pCurrent)
33148
33149 #if !SQLITE_OS_WINRT
33150   { "Sleep",                   (SYSCALL)Sleep,                   0 },
33151 #else
33152   { "Sleep",                   (SYSCALL)0,                       0 },
33153 #endif
33154
33155 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
33156
33157   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
33158
33159 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
33160         LPFILETIME))aSyscall[54].pCurrent)
33161
33162 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33163   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
33164 #else
33165   { "UnlockFile",              (SYSCALL)0,                       0 },
33166 #endif
33167
33168 #ifndef osUnlockFile
33169 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33170         DWORD))aSyscall[55].pCurrent)
33171 #endif
33172
33173 #if !SQLITE_OS_WINCE
33174   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
33175 #else
33176   { "UnlockFileEx",            (SYSCALL)0,                       0 },
33177 #endif
33178
33179 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33180         LPOVERLAPPED))aSyscall[56].pCurrent)
33181
33182 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
33183   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
33184 #else
33185   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
33186 #endif
33187
33188 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
33189
33190   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
33191
33192 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
33193         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
33194
33195   { "WriteFile",               (SYSCALL)WriteFile,               0 },
33196
33197 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
33198         LPOVERLAPPED))aSyscall[59].pCurrent)
33199
33200 #if SQLITE_OS_WINRT
33201   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
33202 #else
33203   { "CreateEventExW",          (SYSCALL)0,                       0 },
33204 #endif
33205
33206 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
33207         DWORD,DWORD))aSyscall[60].pCurrent)
33208
33209 #if !SQLITE_OS_WINRT
33210   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
33211 #else
33212   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
33213 #endif
33214
33215 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
33216         DWORD))aSyscall[61].pCurrent)
33217
33218 #if SQLITE_OS_WINRT
33219   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
33220 #else
33221   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
33222 #endif
33223
33224 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
33225         BOOL))aSyscall[62].pCurrent)
33226
33227 #if SQLITE_OS_WINRT
33228   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
33229 #else
33230   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
33231 #endif
33232
33233 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
33234         PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
33235
33236 #if SQLITE_OS_WINRT
33237   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
33238 #else
33239   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
33240 #endif
33241
33242 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
33243         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
33244
33245 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33246   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
33247 #else
33248   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
33249 #endif
33250
33251 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
33252         SIZE_T))aSyscall[65].pCurrent)
33253
33254 #if SQLITE_OS_WINRT
33255   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
33256 #else
33257   { "CreateFile2",             (SYSCALL)0,                       0 },
33258 #endif
33259
33260 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
33261         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
33262
33263 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33264   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
33265 #else
33266   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
33267 #endif
33268
33269 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
33270         DWORD))aSyscall[67].pCurrent)
33271
33272 #if SQLITE_OS_WINRT
33273   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
33274 #else
33275   { "GetTickCount64",          (SYSCALL)0,                       0 },
33276 #endif
33277
33278 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
33279
33280 #if SQLITE_OS_WINRT
33281   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
33282 #else
33283   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
33284 #endif
33285
33286 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
33287         LPSYSTEM_INFO))aSyscall[69].pCurrent)
33288
33289 #if defined(SQLITE_WIN32_HAS_ANSI)
33290   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
33291 #else
33292   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
33293 #endif
33294
33295 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
33296
33297 #if defined(SQLITE_WIN32_HAS_WIDE)
33298   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
33299 #else
33300   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
33301 #endif
33302
33303 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
33304
33305   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
33306
33307 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
33308
33309 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
33310   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
33311 #else
33312   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
33313 #endif
33314
33315 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
33316         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
33317
33318 }; /* End of the overrideable system calls */
33319
33320 /*
33321 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
33322 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
33323 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
33324 ** system call named zName.
33325 */
33326 static int winSetSystemCall(
33327   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
33328   const char *zName,            /* Name of system call to override */
33329   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
33330 ){
33331   unsigned int i;
33332   int rc = SQLITE_NOTFOUND;
33333
33334   UNUSED_PARAMETER(pNotUsed);
33335   if( zName==0 ){
33336     /* If no zName is given, restore all system calls to their default
33337     ** settings and return NULL
33338     */
33339     rc = SQLITE_OK;
33340     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33341       if( aSyscall[i].pDefault ){
33342         aSyscall[i].pCurrent = aSyscall[i].pDefault;
33343       }
33344     }
33345   }else{
33346     /* If zName is specified, operate on only the one system call
33347     ** specified.
33348     */
33349     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33350       if( strcmp(zName, aSyscall[i].zName)==0 ){
33351         if( aSyscall[i].pDefault==0 ){
33352           aSyscall[i].pDefault = aSyscall[i].pCurrent;
33353         }
33354         rc = SQLITE_OK;
33355         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
33356         aSyscall[i].pCurrent = pNewFunc;
33357         break;
33358       }
33359     }
33360   }
33361   return rc;
33362 }
33363
33364 /*
33365 ** Return the value of a system call.  Return NULL if zName is not a
33366 ** recognized system call name.  NULL is also returned if the system call
33367 ** is currently undefined.
33368 */
33369 static sqlite3_syscall_ptr winGetSystemCall(
33370   sqlite3_vfs *pNotUsed,
33371   const char *zName
33372 ){
33373   unsigned int i;
33374
33375   UNUSED_PARAMETER(pNotUsed);
33376   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
33377     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
33378   }
33379   return 0;
33380 }
33381
33382 /*
33383 ** Return the name of the first system call after zName.  If zName==NULL
33384 ** then return the name of the first system call.  Return NULL if zName
33385 ** is the last system call or if zName is not the name of a valid
33386 ** system call.
33387 */
33388 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
33389   int i = -1;
33390
33391   UNUSED_PARAMETER(p);
33392   if( zName ){
33393     for(i=0; i<ArraySize(aSyscall)-1; i++){
33394       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
33395     }
33396   }
33397   for(i++; i<ArraySize(aSyscall); i++){
33398     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
33399   }
33400   return 0;
33401 }
33402
33403 /*
33404 ** This function outputs the specified (ANSI) string to the Win32 debugger
33405 ** (if available).
33406 */
33407
33408 SQLITE_API void sqlite3_win32_write_debug(char *zBuf, int nBuf){
33409   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
33410   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
33411   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
33412   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
33413 #if defined(SQLITE_WIN32_HAS_ANSI)
33414   if( nMin>0 ){
33415     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33416     memcpy(zDbgBuf, zBuf, nMin);
33417     osOutputDebugStringA(zDbgBuf);
33418   }else{
33419     osOutputDebugStringA(zBuf);
33420   }
33421 #elif defined(SQLITE_WIN32_HAS_WIDE)
33422   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33423   if ( osMultiByteToWideChar(
33424           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
33425           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
33426     return;
33427   }
33428   osOutputDebugStringW((LPCWSTR)zDbgBuf);
33429 #else
33430   if( nMin>0 ){
33431     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
33432     memcpy(zDbgBuf, zBuf, nMin);
33433     fprintf(stderr, "%s", zDbgBuf);
33434   }else{
33435     fprintf(stderr, "%s", zBuf);
33436   }
33437 #endif
33438 }
33439
33440 /*
33441 ** The following routine suspends the current thread for at least ms
33442 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
33443 */
33444 #if SQLITE_OS_WINRT
33445 static HANDLE sleepObj = NULL;
33446 #endif
33447
33448 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
33449 #if SQLITE_OS_WINRT
33450   if ( sleepObj==NULL ){
33451     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
33452                                 SYNCHRONIZE);
33453   }
33454   assert( sleepObj!=NULL );
33455   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
33456 #else
33457   osSleep(milliseconds);
33458 #endif
33459 }
33460
33461 /*
33462 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
33463 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
33464 **
33465 ** Here is an interesting observation:  Win95, Win98, and WinME lack
33466 ** the LockFileEx() API.  But we can still statically link against that
33467 ** API as long as we don't call it when running Win95/98/ME.  A call to
33468 ** this routine is used to determine if the host is Win95/98/ME or
33469 ** WinNT/2K/XP so that we will know whether or not we can safely call
33470 ** the LockFileEx() API.
33471 */
33472 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
33473 # define isNT()  (1)
33474 #elif !defined(SQLITE_WIN32_HAS_WIDE)
33475 # define isNT()  (0)
33476 #else
33477   static int isNT(void){
33478     if( sqlite3_os_type==0 ){
33479       OSVERSIONINFOA sInfo;
33480       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
33481       osGetVersionExA(&sInfo);
33482       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
33483     }
33484     return sqlite3_os_type==2;
33485   }
33486 #endif
33487
33488 #ifdef SQLITE_WIN32_MALLOC
33489 /*
33490 ** Allocate nBytes of memory.
33491 */
33492 static void *winMemMalloc(int nBytes){
33493   HANDLE hHeap;
33494   void *p;
33495
33496   winMemAssertMagic();
33497   hHeap = winMemGetHeap();
33498   assert( hHeap!=0 );
33499   assert( hHeap!=INVALID_HANDLE_VALUE );
33500 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33501   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33502 #endif
33503   assert( nBytes>=0 );
33504   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33505   if( !p ){
33506     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
33507                 nBytes, osGetLastError(), (void*)hHeap);
33508   }
33509   return p;
33510 }
33511
33512 /*
33513 ** Free memory.
33514 */
33515 static void winMemFree(void *pPrior){
33516   HANDLE hHeap;
33517
33518   winMemAssertMagic();
33519   hHeap = winMemGetHeap();
33520   assert( hHeap!=0 );
33521   assert( hHeap!=INVALID_HANDLE_VALUE );
33522 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33523   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
33524 #endif
33525   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
33526   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
33527     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
33528                 pPrior, osGetLastError(), (void*)hHeap);
33529   }
33530 }
33531
33532 /*
33533 ** Change the size of an existing memory allocation
33534 */
33535 static void *winMemRealloc(void *pPrior, int nBytes){
33536   HANDLE hHeap;
33537   void *p;
33538
33539   winMemAssertMagic();
33540   hHeap = winMemGetHeap();
33541   assert( hHeap!=0 );
33542   assert( hHeap!=INVALID_HANDLE_VALUE );
33543 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33544   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
33545 #endif
33546   assert( nBytes>=0 );
33547   if( !pPrior ){
33548     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33549   }else{
33550     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
33551   }
33552   if( !p ){
33553     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
33554                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
33555                 (void*)hHeap);
33556   }
33557   return p;
33558 }
33559
33560 /*
33561 ** Return the size of an outstanding allocation, in bytes.
33562 */
33563 static int winMemSize(void *p){
33564   HANDLE hHeap;
33565   SIZE_T n;
33566
33567   winMemAssertMagic();
33568   hHeap = winMemGetHeap();
33569   assert( hHeap!=0 );
33570   assert( hHeap!=INVALID_HANDLE_VALUE );
33571 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33572   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33573 #endif
33574   if( !p ) return 0;
33575   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
33576   if( n==(SIZE_T)-1 ){
33577     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
33578                 p, osGetLastError(), (void*)hHeap);
33579     return 0;
33580   }
33581   return (int)n;
33582 }
33583
33584 /*
33585 ** Round up a request size to the next valid allocation size.
33586 */
33587 static int winMemRoundup(int n){
33588   return n;
33589 }
33590
33591 /*
33592 ** Initialize this module.
33593 */
33594 static int winMemInit(void *pAppData){
33595   winMemData *pWinMemData = (winMemData *)pAppData;
33596
33597   if( !pWinMemData ) return SQLITE_ERROR;
33598   assert( pWinMemData->magic==WINMEM_MAGIC );
33599
33600 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
33601   if( !pWinMemData->hHeap ){
33602     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
33603                                       SQLITE_WIN32_HEAP_INIT_SIZE,
33604                                       SQLITE_WIN32_HEAP_MAX_SIZE);
33605     if( !pWinMemData->hHeap ){
33606       sqlite3_log(SQLITE_NOMEM,
33607           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
33608           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
33609           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
33610       return SQLITE_NOMEM;
33611     }
33612     pWinMemData->bOwned = TRUE;
33613     assert( pWinMemData->bOwned );
33614   }
33615 #else
33616   pWinMemData->hHeap = osGetProcessHeap();
33617   if( !pWinMemData->hHeap ){
33618     sqlite3_log(SQLITE_NOMEM,
33619         "failed to GetProcessHeap (%d)", osGetLastError());
33620     return SQLITE_NOMEM;
33621   }
33622   pWinMemData->bOwned = FALSE;
33623   assert( !pWinMemData->bOwned );
33624 #endif
33625   assert( pWinMemData->hHeap!=0 );
33626   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33627 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33628   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33629 #endif
33630   return SQLITE_OK;
33631 }
33632
33633 /*
33634 ** Deinitialize this module.
33635 */
33636 static void winMemShutdown(void *pAppData){
33637   winMemData *pWinMemData = (winMemData *)pAppData;
33638
33639   if( !pWinMemData ) return;
33640   if( pWinMemData->hHeap ){
33641     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33642 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33643     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33644 #endif
33645     if( pWinMemData->bOwned ){
33646       if( !osHeapDestroy(pWinMemData->hHeap) ){
33647         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
33648                     osGetLastError(), (void*)pWinMemData->hHeap);
33649       }
33650       pWinMemData->bOwned = FALSE;
33651     }
33652     pWinMemData->hHeap = NULL;
33653   }
33654 }
33655
33656 /*
33657 ** Populate the low-level memory allocation function pointers in
33658 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
33659 ** arguments specify the block of memory to manage.
33660 **
33661 ** This routine is only called by sqlite3_config(), and therefore
33662 ** is not required to be threadsafe (it is not).
33663 */
33664 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
33665   static const sqlite3_mem_methods winMemMethods = {
33666     winMemMalloc,
33667     winMemFree,
33668     winMemRealloc,
33669     winMemSize,
33670     winMemRoundup,
33671     winMemInit,
33672     winMemShutdown,
33673     &win_mem_data
33674   };
33675   return &winMemMethods;
33676 }
33677
33678 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
33679   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
33680 }
33681 #endif /* SQLITE_WIN32_MALLOC */
33682
33683 /*
33684 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
33685 **
33686 ** Space to hold the returned string is obtained from malloc.
33687 */
33688 static LPWSTR utf8ToUnicode(const char *zFilename){
33689   int nChar;
33690   LPWSTR zWideFilename;
33691
33692   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
33693   if( nChar==0 ){
33694     return 0;
33695   }
33696   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
33697   if( zWideFilename==0 ){
33698     return 0;
33699   }
33700   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
33701                                 nChar);
33702   if( nChar==0 ){
33703     sqlite3_free(zWideFilename);
33704     zWideFilename = 0;
33705   }
33706   return zWideFilename;
33707 }
33708
33709 /*
33710 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
33711 ** obtained from sqlite3_malloc().
33712 */
33713 static char *unicodeToUtf8(LPCWSTR zWideFilename){
33714   int nByte;
33715   char *zFilename;
33716
33717   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
33718   if( nByte == 0 ){
33719     return 0;
33720   }
33721   zFilename = sqlite3MallocZero( nByte );
33722   if( zFilename==0 ){
33723     return 0;
33724   }
33725   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
33726                                 0, 0);
33727   if( nByte == 0 ){
33728     sqlite3_free(zFilename);
33729     zFilename = 0;
33730   }
33731   return zFilename;
33732 }
33733
33734 /*
33735 ** Convert an ANSI string to Microsoft Unicode, based on the
33736 ** current codepage settings for file apis.
33737 **
33738 ** Space to hold the returned string is obtained
33739 ** from sqlite3_malloc.
33740 */
33741 static LPWSTR mbcsToUnicode(const char *zFilename){
33742   int nByte;
33743   LPWSTR zMbcsFilename;
33744   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33745
33746   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
33747                                 0)*sizeof(WCHAR);
33748   if( nByte==0 ){
33749     return 0;
33750   }
33751   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
33752   if( zMbcsFilename==0 ){
33753     return 0;
33754   }
33755   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
33756                                 nByte);
33757   if( nByte==0 ){
33758     sqlite3_free(zMbcsFilename);
33759     zMbcsFilename = 0;
33760   }
33761   return zMbcsFilename;
33762 }
33763
33764 /*
33765 ** Convert Microsoft Unicode to multi-byte character string, based on the
33766 ** user's ANSI codepage.
33767 **
33768 ** Space to hold the returned string is obtained from
33769 ** sqlite3_malloc().
33770 */
33771 static char *unicodeToMbcs(LPCWSTR zWideFilename){
33772   int nByte;
33773   char *zFilename;
33774   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33775
33776   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
33777   if( nByte == 0 ){
33778     return 0;
33779   }
33780   zFilename = sqlite3MallocZero( nByte );
33781   if( zFilename==0 ){
33782     return 0;
33783   }
33784   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
33785                                 nByte, 0, 0);
33786   if( nByte == 0 ){
33787     sqlite3_free(zFilename);
33788     zFilename = 0;
33789   }
33790   return zFilename;
33791 }
33792
33793 /*
33794 ** Convert multibyte character string to UTF-8.  Space to hold the
33795 ** returned string is obtained from sqlite3_malloc().
33796 */
33797 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
33798   char *zFilenameUtf8;
33799   LPWSTR zTmpWide;
33800
33801   zTmpWide = mbcsToUnicode(zFilename);
33802   if( zTmpWide==0 ){
33803     return 0;
33804   }
33805   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
33806   sqlite3_free(zTmpWide);
33807   return zFilenameUtf8;
33808 }
33809
33810 /*
33811 ** Convert UTF-8 to multibyte character string.  Space to hold the
33812 ** returned string is obtained from sqlite3_malloc().
33813 */
33814 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
33815   char *zFilenameMbcs;
33816   LPWSTR zTmpWide;
33817
33818   zTmpWide = utf8ToUnicode(zFilename);
33819   if( zTmpWide==0 ){
33820     return 0;
33821   }
33822   zFilenameMbcs = unicodeToMbcs(zTmpWide);
33823   sqlite3_free(zTmpWide);
33824   return zFilenameMbcs;
33825 }
33826
33827 /*
33828 ** This function sets the data directory or the temporary directory based on
33829 ** the provided arguments.  The type argument must be 1 in order to set the
33830 ** data directory or 2 in order to set the temporary directory.  The zValue
33831 ** argument is the name of the directory to use.  The return value will be
33832 ** SQLITE_OK if successful.
33833 */
33834 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
33835   char **ppDirectory = 0;
33836 #ifndef SQLITE_OMIT_AUTOINIT
33837   int rc = sqlite3_initialize();
33838   if( rc ) return rc;
33839 #endif
33840   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
33841     ppDirectory = &sqlite3_data_directory;
33842   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
33843     ppDirectory = &sqlite3_temp_directory;
33844   }
33845   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
33846           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
33847   );
33848   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
33849   if( ppDirectory ){
33850     char *zValueUtf8 = 0;
33851     if( zValue && zValue[0] ){
33852       zValueUtf8 = unicodeToUtf8(zValue);
33853       if ( zValueUtf8==0 ){
33854         return SQLITE_NOMEM;
33855       }
33856     }
33857     sqlite3_free(*ppDirectory);
33858     *ppDirectory = zValueUtf8;
33859     return SQLITE_OK;
33860   }
33861   return SQLITE_ERROR;
33862 }
33863
33864 /*
33865 ** The return value of getLastErrorMsg
33866 ** is zero if the error message fits in the buffer, or non-zero
33867 ** otherwise (if the message was truncated).
33868 */
33869 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
33870   /* FormatMessage returns 0 on failure.  Otherwise it
33871   ** returns the number of TCHARs written to the output
33872   ** buffer, excluding the terminating null char.
33873   */
33874   DWORD dwLen = 0;
33875   char *zOut = 0;
33876
33877   if( isNT() ){
33878 #if SQLITE_OS_WINRT
33879     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
33880     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
33881                              FORMAT_MESSAGE_IGNORE_INSERTS,
33882                              NULL,
33883                              lastErrno,
33884                              0,
33885                              zTempWide,
33886                              MAX_PATH,
33887                              0);
33888 #else
33889     LPWSTR zTempWide = NULL;
33890     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33891                              FORMAT_MESSAGE_FROM_SYSTEM |
33892                              FORMAT_MESSAGE_IGNORE_INSERTS,
33893                              NULL,
33894                              lastErrno,
33895                              0,
33896                              (LPWSTR) &zTempWide,
33897                              0,
33898                              0);
33899 #endif
33900     if( dwLen > 0 ){
33901       /* allocate a buffer and convert to UTF8 */
33902       sqlite3BeginBenignMalloc();
33903       zOut = unicodeToUtf8(zTempWide);
33904       sqlite3EndBenignMalloc();
33905 #if !SQLITE_OS_WINRT
33906       /* free the system buffer allocated by FormatMessage */
33907       osLocalFree(zTempWide);
33908 #endif
33909     }
33910   }
33911 #ifdef SQLITE_WIN32_HAS_ANSI
33912   else{
33913     char *zTemp = NULL;
33914     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33915                              FORMAT_MESSAGE_FROM_SYSTEM |
33916                              FORMAT_MESSAGE_IGNORE_INSERTS,
33917                              NULL,
33918                              lastErrno,
33919                              0,
33920                              (LPSTR) &zTemp,
33921                              0,
33922                              0);
33923     if( dwLen > 0 ){
33924       /* allocate a buffer and convert to UTF8 */
33925       sqlite3BeginBenignMalloc();
33926       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33927       sqlite3EndBenignMalloc();
33928       /* free the system buffer allocated by FormatMessage */
33929       osLocalFree(zTemp);
33930     }
33931   }
33932 #endif
33933   if( 0 == dwLen ){
33934     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
33935   }else{
33936     /* copy a maximum of nBuf chars to output buffer */
33937     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33938     /* free the UTF8 buffer */
33939     sqlite3_free(zOut);
33940   }
33941   return 0;
33942 }
33943
33944 /*
33945 **
33946 ** This function - winLogErrorAtLine() - is only ever called via the macro
33947 ** winLogError().
33948 **
33949 ** This routine is invoked after an error occurs in an OS function.
33950 ** It logs a message using sqlite3_log() containing the current value of
33951 ** error code and, if possible, the human-readable equivalent from
33952 ** FormatMessage.
33953 **
33954 ** The first argument passed to the macro should be the error code that
33955 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
33956 ** The two subsequent arguments should be the name of the OS function that
33957 ** failed and the associated file-system path, if any.
33958 */
33959 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
33960 static int winLogErrorAtLine(
33961   int errcode,                    /* SQLite error code */
33962   DWORD lastErrno,                /* Win32 last error */
33963   const char *zFunc,              /* Name of OS function that failed */
33964   const char *zPath,              /* File path associated with error */
33965   int iLine                       /* Source line number where error occurred */
33966 ){
33967   char zMsg[500];                 /* Human readable error text */
33968   int i;                          /* Loop counter */
33969
33970   zMsg[0] = 0;
33971   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
33972   assert( errcode!=SQLITE_OK );
33973   if( zPath==0 ) zPath = "";
33974   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
33975   zMsg[i] = 0;
33976   sqlite3_log(errcode,
33977       "os_win.c:%d: (%d) %s(%s) - %s",
33978       iLine, lastErrno, zFunc, zPath, zMsg
33979   );
33980
33981   return errcode;
33982 }
33983
33984 /*
33985 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
33986 ** will be retried following a locking error - probably caused by
33987 ** antivirus software.  Also the initial delay before the first retry.
33988 ** The delay increases linearly with each retry.
33989 */
33990 #ifndef SQLITE_WIN32_IOERR_RETRY
33991 # define SQLITE_WIN32_IOERR_RETRY 10
33992 #endif
33993 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
33994 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
33995 #endif
33996 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
33997 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
33998
33999 /*
34000 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
34001 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
34002 ** to give up with an error.
34003 */
34004 static int retryIoerr(int *pnRetry, DWORD *pError){
34005   DWORD e = osGetLastError();
34006   if( *pnRetry>=win32IoerrRetry ){
34007     if( pError ){
34008       *pError = e;
34009     }
34010     return 0;
34011   }
34012   if( e==ERROR_ACCESS_DENIED ||
34013       e==ERROR_LOCK_VIOLATION ||
34014       e==ERROR_SHARING_VIOLATION ){
34015     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
34016     ++*pnRetry;
34017     return 1;
34018   }
34019   if( pError ){
34020     *pError = e;
34021   }
34022   return 0;
34023 }
34024
34025 /*
34026 ** Log a I/O error retry episode.
34027 */
34028 static void logIoerr(int nRetry){
34029   if( nRetry ){
34030     sqlite3_log(SQLITE_IOERR,
34031       "delayed %dms for lock/sharing conflict",
34032       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
34033     );
34034   }
34035 }
34036
34037 #if SQLITE_OS_WINCE
34038 /*************************************************************************
34039 ** This section contains code for WinCE only.
34040 */
34041 /*
34042 ** Windows CE does not have a localtime() function.  So create a
34043 ** substitute.
34044 */
34045 /* #include <time.h> */
34046 struct tm *__cdecl localtime(const time_t *t)
34047 {
34048   static struct tm y;
34049   FILETIME uTm, lTm;
34050   SYSTEMTIME pTm;
34051   sqlite3_int64 t64;
34052   t64 = *t;
34053   t64 = (t64 + 11644473600)*10000000;
34054   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
34055   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
34056   osFileTimeToLocalFileTime(&uTm,&lTm);
34057   osFileTimeToSystemTime(&lTm,&pTm);
34058   y.tm_year = pTm.wYear - 1900;
34059   y.tm_mon = pTm.wMonth - 1;
34060   y.tm_wday = pTm.wDayOfWeek;
34061   y.tm_mday = pTm.wDay;
34062   y.tm_hour = pTm.wHour;
34063   y.tm_min = pTm.wMinute;
34064   y.tm_sec = pTm.wSecond;
34065   return &y;
34066 }
34067
34068 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
34069
34070 /*
34071 ** Acquire a lock on the handle h
34072 */
34073 static void winceMutexAcquire(HANDLE h){
34074    DWORD dwErr;
34075    do {
34076      dwErr = osWaitForSingleObject(h, INFINITE);
34077    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
34078 }
34079 /*
34080 ** Release a lock acquired by winceMutexAcquire()
34081 */
34082 #define winceMutexRelease(h) ReleaseMutex(h)
34083
34084 /*
34085 ** Create the mutex and shared memory used for locking in the file
34086 ** descriptor pFile
34087 */
34088 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
34089   LPWSTR zTok;
34090   LPWSTR zName;
34091   BOOL bInit = TRUE;
34092
34093   zName = utf8ToUnicode(zFilename);
34094   if( zName==0 ){
34095     /* out of memory */
34096     return FALSE;
34097   }
34098
34099   /* Initialize the local lockdata */
34100   memset(&pFile->local, 0, sizeof(pFile->local));
34101
34102   /* Replace the backslashes from the filename and lowercase it
34103   ** to derive a mutex name. */
34104   zTok = osCharLowerW(zName);
34105   for (;*zTok;zTok++){
34106     if (*zTok == '\\') *zTok = '_';
34107   }
34108
34109   /* Create/open the named mutex */
34110   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
34111   if (!pFile->hMutex){
34112     pFile->lastErrno = osGetLastError();
34113     winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
34114     sqlite3_free(zName);
34115     return FALSE;
34116   }
34117
34118   /* Acquire the mutex before continuing */
34119   winceMutexAcquire(pFile->hMutex);
34120
34121   /* Since the names of named mutexes, semaphores, file mappings etc are
34122   ** case-sensitive, take advantage of that by uppercasing the mutex name
34123   ** and using that as the shared filemapping name.
34124   */
34125   osCharUpperW(zName);
34126   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
34127                                         PAGE_READWRITE, 0, sizeof(winceLock),
34128                                         zName);
34129
34130   /* Set a flag that indicates we're the first to create the memory so it
34131   ** must be zero-initialized */
34132   if (osGetLastError() == ERROR_ALREADY_EXISTS){
34133     bInit = FALSE;
34134   }
34135
34136   sqlite3_free(zName);
34137
34138   /* If we succeeded in making the shared memory handle, map it. */
34139   if (pFile->hShared){
34140     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
34141              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
34142     /* If mapping failed, close the shared memory handle and erase it */
34143     if (!pFile->shared){
34144       pFile->lastErrno = osGetLastError();
34145       winLogError(SQLITE_ERROR, pFile->lastErrno,
34146                "winceCreateLock2", zFilename);
34147       osCloseHandle(pFile->hShared);
34148       pFile->hShared = NULL;
34149     }
34150   }
34151
34152   /* If shared memory could not be created, then close the mutex and fail */
34153   if (pFile->hShared == NULL){
34154     winceMutexRelease(pFile->hMutex);
34155     osCloseHandle(pFile->hMutex);
34156     pFile->hMutex = NULL;
34157     return FALSE;
34158   }
34159
34160   /* Initialize the shared memory if we're supposed to */
34161   if (bInit) {
34162     memset(pFile->shared, 0, sizeof(winceLock));
34163   }
34164
34165   winceMutexRelease(pFile->hMutex);
34166   return TRUE;
34167 }
34168
34169 /*
34170 ** Destroy the part of winFile that deals with wince locks
34171 */
34172 static void winceDestroyLock(winFile *pFile){
34173   if (pFile->hMutex){
34174     /* Acquire the mutex */
34175     winceMutexAcquire(pFile->hMutex);
34176
34177     /* The following blocks should probably assert in debug mode, but they
34178        are to cleanup in case any locks remained open */
34179     if (pFile->local.nReaders){
34180       pFile->shared->nReaders --;
34181     }
34182     if (pFile->local.bReserved){
34183       pFile->shared->bReserved = FALSE;
34184     }
34185     if (pFile->local.bPending){
34186       pFile->shared->bPending = FALSE;
34187     }
34188     if (pFile->local.bExclusive){
34189       pFile->shared->bExclusive = FALSE;
34190     }
34191
34192     /* De-reference and close our copy of the shared memory handle */
34193     osUnmapViewOfFile(pFile->shared);
34194     osCloseHandle(pFile->hShared);
34195
34196     /* Done with the mutex */
34197     winceMutexRelease(pFile->hMutex);
34198     osCloseHandle(pFile->hMutex);
34199     pFile->hMutex = NULL;
34200   }
34201 }
34202
34203 /*
34204 ** An implementation of the LockFile() API of Windows for CE
34205 */
34206 static BOOL winceLockFile(
34207   LPHANDLE phFile,
34208   DWORD dwFileOffsetLow,
34209   DWORD dwFileOffsetHigh,
34210   DWORD nNumberOfBytesToLockLow,
34211   DWORD nNumberOfBytesToLockHigh
34212 ){
34213   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34214   BOOL bReturn = FALSE;
34215
34216   UNUSED_PARAMETER(dwFileOffsetHigh);
34217   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
34218
34219   if (!pFile->hMutex) return TRUE;
34220   winceMutexAcquire(pFile->hMutex);
34221
34222   /* Wanting an exclusive lock? */
34223   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
34224        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
34225     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
34226        pFile->shared->bExclusive = TRUE;
34227        pFile->local.bExclusive = TRUE;
34228        bReturn = TRUE;
34229     }
34230   }
34231
34232   /* Want a read-only lock? */
34233   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
34234            nNumberOfBytesToLockLow == 1){
34235     if (pFile->shared->bExclusive == 0){
34236       pFile->local.nReaders ++;
34237       if (pFile->local.nReaders == 1){
34238         pFile->shared->nReaders ++;
34239       }
34240       bReturn = TRUE;
34241     }
34242   }
34243
34244   /* Want a pending lock? */
34245   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
34246     /* If no pending lock has been acquired, then acquire it */
34247     if (pFile->shared->bPending == 0) {
34248       pFile->shared->bPending = TRUE;
34249       pFile->local.bPending = TRUE;
34250       bReturn = TRUE;
34251     }
34252   }
34253
34254   /* Want a reserved lock? */
34255   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
34256     if (pFile->shared->bReserved == 0) {
34257       pFile->shared->bReserved = TRUE;
34258       pFile->local.bReserved = TRUE;
34259       bReturn = TRUE;
34260     }
34261   }
34262
34263   winceMutexRelease(pFile->hMutex);
34264   return bReturn;
34265 }
34266
34267 /*
34268 ** An implementation of the UnlockFile API of Windows for CE
34269 */
34270 static BOOL winceUnlockFile(
34271   LPHANDLE phFile,
34272   DWORD dwFileOffsetLow,
34273   DWORD dwFileOffsetHigh,
34274   DWORD nNumberOfBytesToUnlockLow,
34275   DWORD nNumberOfBytesToUnlockHigh
34276 ){
34277   winFile *pFile = HANDLE_TO_WINFILE(phFile);
34278   BOOL bReturn = FALSE;
34279
34280   UNUSED_PARAMETER(dwFileOffsetHigh);
34281   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
34282
34283   if (!pFile->hMutex) return TRUE;
34284   winceMutexAcquire(pFile->hMutex);
34285
34286   /* Releasing a reader lock or an exclusive lock */
34287   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
34288     /* Did we have an exclusive lock? */
34289     if (pFile->local.bExclusive){
34290       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
34291       pFile->local.bExclusive = FALSE;
34292       pFile->shared->bExclusive = FALSE;
34293       bReturn = TRUE;
34294     }
34295
34296     /* Did we just have a reader lock? */
34297     else if (pFile->local.nReaders){
34298       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
34299       pFile->local.nReaders --;
34300       if (pFile->local.nReaders == 0)
34301       {
34302         pFile->shared->nReaders --;
34303       }
34304       bReturn = TRUE;
34305     }
34306   }
34307
34308   /* Releasing a pending lock */
34309   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
34310     if (pFile->local.bPending){
34311       pFile->local.bPending = FALSE;
34312       pFile->shared->bPending = FALSE;
34313       bReturn = TRUE;
34314     }
34315   }
34316   /* Releasing a reserved lock */
34317   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
34318     if (pFile->local.bReserved) {
34319       pFile->local.bReserved = FALSE;
34320       pFile->shared->bReserved = FALSE;
34321       bReturn = TRUE;
34322     }
34323   }
34324
34325   winceMutexRelease(pFile->hMutex);
34326   return bReturn;
34327 }
34328 /*
34329 ** End of the special code for wince
34330 *****************************************************************************/
34331 #endif /* SQLITE_OS_WINCE */
34332
34333 /*
34334 ** Lock a file region.
34335 */
34336 static BOOL winLockFile(
34337   LPHANDLE phFile,
34338   DWORD flags,
34339   DWORD offsetLow,
34340   DWORD offsetHigh,
34341   DWORD numBytesLow,
34342   DWORD numBytesHigh
34343 ){
34344 #if SQLITE_OS_WINCE
34345   /*
34346   ** NOTE: Windows CE is handled differently here due its lack of the Win32
34347   **       API LockFile.
34348   */
34349   return winceLockFile(phFile, offsetLow, offsetHigh,
34350                        numBytesLow, numBytesHigh);
34351 #else
34352   if( isNT() ){
34353     OVERLAPPED ovlp;
34354     memset(&ovlp, 0, sizeof(OVERLAPPED));
34355     ovlp.Offset = offsetLow;
34356     ovlp.OffsetHigh = offsetHigh;
34357     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
34358   }else{
34359     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34360                       numBytesHigh);
34361   }
34362 #endif
34363 }
34364
34365 /*
34366 ** Unlock a file region.
34367  */
34368 static BOOL winUnlockFile(
34369   LPHANDLE phFile,
34370   DWORD offsetLow,
34371   DWORD offsetHigh,
34372   DWORD numBytesLow,
34373   DWORD numBytesHigh
34374 ){
34375 #if SQLITE_OS_WINCE
34376   /*
34377   ** NOTE: Windows CE is handled differently here due its lack of the Win32
34378   **       API UnlockFile.
34379   */
34380   return winceUnlockFile(phFile, offsetLow, offsetHigh,
34381                          numBytesLow, numBytesHigh);
34382 #else
34383   if( isNT() ){
34384     OVERLAPPED ovlp;
34385     memset(&ovlp, 0, sizeof(OVERLAPPED));
34386     ovlp.Offset = offsetLow;
34387     ovlp.OffsetHigh = offsetHigh;
34388     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
34389   }else{
34390     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
34391                         numBytesHigh);
34392   }
34393 #endif
34394 }
34395
34396 /*****************************************************************************
34397 ** The next group of routines implement the I/O methods specified
34398 ** by the sqlite3_io_methods object.
34399 ******************************************************************************/
34400
34401 /*
34402 ** Some Microsoft compilers lack this definition.
34403 */
34404 #ifndef INVALID_SET_FILE_POINTER
34405 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
34406 #endif
34407
34408 /*
34409 ** Move the current position of the file handle passed as the first
34410 ** argument to offset iOffset within the file. If successful, return 0.
34411 ** Otherwise, set pFile->lastErrno and return non-zero.
34412 */
34413 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
34414 #if !SQLITE_OS_WINRT
34415   LONG upperBits;                 /* Most sig. 32 bits of new offset */
34416   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
34417   DWORD dwRet;                    /* Value returned by SetFilePointer() */
34418   DWORD lastErrno;                /* Value returned by GetLastError() */
34419
34420   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
34421   lowerBits = (LONG)(iOffset & 0xffffffff);
34422
34423   /* API oddity: If successful, SetFilePointer() returns a dword
34424   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
34425   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
34426   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
34427   ** whether an error has actually occured, it is also necessary to call
34428   ** GetLastError().
34429   */
34430   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
34431
34432   if( (dwRet==INVALID_SET_FILE_POINTER
34433       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
34434     pFile->lastErrno = lastErrno;
34435     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
34436              "seekWinFile", pFile->zPath);
34437     return 1;
34438   }
34439
34440   return 0;
34441 #else
34442   /*
34443   ** Same as above, except that this implementation works for WinRT.
34444   */
34445
34446   LARGE_INTEGER x;                /* The new offset */
34447   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
34448
34449   x.QuadPart = iOffset;
34450   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
34451
34452   if(!bRet){
34453     pFile->lastErrno = osGetLastError();
34454     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
34455              "seekWinFile", pFile->zPath);
34456     return 1;
34457   }
34458
34459   return 0;
34460 #endif
34461 }
34462
34463 /*
34464 ** Close a file.
34465 **
34466 ** It is reported that an attempt to close a handle might sometimes
34467 ** fail.  This is a very unreasonable result, but Windows is notorious
34468 ** for being unreasonable so I do not doubt that it might happen.  If
34469 ** the close fails, we pause for 100 milliseconds and try again.  As
34470 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
34471 ** giving up and returning an error.
34472 */
34473 #define MX_CLOSE_ATTEMPT 3
34474 static int winClose(sqlite3_file *id){
34475   int rc, cnt = 0;
34476   winFile *pFile = (winFile*)id;
34477
34478   assert( id!=0 );
34479 #ifndef SQLITE_OMIT_WAL
34480   assert( pFile->pShm==0 );
34481 #endif
34482   OSTRACE(("CLOSE %d\n", pFile->h));
34483   do{
34484     rc = osCloseHandle(pFile->h);
34485     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
34486   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
34487 #if SQLITE_OS_WINCE
34488 #define WINCE_DELETION_ATTEMPTS 3
34489   winceDestroyLock(pFile);
34490   if( pFile->zDeleteOnClose ){
34491     int cnt = 0;
34492     while(
34493            osDeleteFileW(pFile->zDeleteOnClose)==0
34494         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
34495         && cnt++ < WINCE_DELETION_ATTEMPTS
34496     ){
34497        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
34498     }
34499     sqlite3_free(pFile->zDeleteOnClose);
34500   }
34501 #endif
34502   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
34503   if( rc ){
34504     pFile->h = NULL;
34505   }
34506   OpenCounter(-1);
34507   return rc ? SQLITE_OK
34508             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
34509                           "winClose", pFile->zPath);
34510 }
34511
34512 /*
34513 ** Read data from a file into a buffer.  Return SQLITE_OK if all
34514 ** bytes were read successfully and SQLITE_IOERR if anything goes
34515 ** wrong.
34516 */
34517 static int winRead(
34518   sqlite3_file *id,          /* File to read from */
34519   void *pBuf,                /* Write content into this buffer */
34520   int amt,                   /* Number of bytes to read */
34521   sqlite3_int64 offset       /* Begin reading at this offset */
34522 ){
34523 #if !SQLITE_OS_WINCE
34524   OVERLAPPED overlapped;          /* The offset for ReadFile. */
34525 #endif
34526   winFile *pFile = (winFile*)id;  /* file handle */
34527   DWORD nRead;                    /* Number of bytes actually read from file */
34528   int nRetry = 0;                 /* Number of retrys */
34529
34530   assert( id!=0 );
34531   SimulateIOError(return SQLITE_IOERR_READ);
34532   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
34533
34534 #if SQLITE_OS_WINCE
34535   if( seekWinFile(pFile, offset) ){
34536     return SQLITE_FULL;
34537   }
34538   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
34539 #else
34540   memset(&overlapped, 0, sizeof(OVERLAPPED));
34541   overlapped.Offset = (LONG)(offset & 0xffffffff);
34542   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34543   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
34544          osGetLastError()!=ERROR_HANDLE_EOF ){
34545 #endif
34546     DWORD lastErrno;
34547     if( retryIoerr(&nRetry, &lastErrno) ) continue;
34548     pFile->lastErrno = lastErrno;
34549     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
34550              "winRead", pFile->zPath);
34551   }
34552   logIoerr(nRetry);
34553   if( nRead<(DWORD)amt ){
34554     /* Unread parts of the buffer must be zero-filled */
34555     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
34556     return SQLITE_IOERR_SHORT_READ;
34557   }
34558
34559   return SQLITE_OK;
34560 }
34561
34562 /*
34563 ** Write data from a buffer into a file.  Return SQLITE_OK on success
34564 ** or some other error code on failure.
34565 */
34566 static int winWrite(
34567   sqlite3_file *id,               /* File to write into */
34568   const void *pBuf,               /* The bytes to be written */
34569   int amt,                        /* Number of bytes to write */
34570   sqlite3_int64 offset            /* Offset into the file to begin writing at */
34571 ){
34572   int rc = 0;                     /* True if error has occured, else false */
34573   winFile *pFile = (winFile*)id;  /* File handle */
34574   int nRetry = 0;                 /* Number of retries */
34575
34576   assert( amt>0 );
34577   assert( pFile );
34578   SimulateIOError(return SQLITE_IOERR_WRITE);
34579   SimulateDiskfullError(return SQLITE_FULL);
34580
34581   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
34582
34583 #if SQLITE_OS_WINCE
34584   rc = seekWinFile(pFile, offset);
34585   if( rc==0 ){
34586 #else
34587   {
34588 #endif
34589 #if !SQLITE_OS_WINCE
34590     OVERLAPPED overlapped;        /* The offset for WriteFile. */
34591 #endif
34592     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
34593     int nRem = amt;               /* Number of bytes yet to be written */
34594     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
34595     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
34596
34597 #if !SQLITE_OS_WINCE
34598     memset(&overlapped, 0, sizeof(OVERLAPPED));
34599     overlapped.Offset = (LONG)(offset & 0xffffffff);
34600     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34601 #endif
34602
34603     while( nRem>0 ){
34604 #if SQLITE_OS_WINCE
34605       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
34606 #else
34607       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
34608 #endif
34609         if( retryIoerr(&nRetry, &lastErrno) ) continue;
34610         break;
34611       }
34612       assert( nWrite==0 || nWrite<=(DWORD)nRem );
34613       if( nWrite==0 || nWrite>(DWORD)nRem ){
34614         lastErrno = osGetLastError();
34615         break;
34616       }
34617 #if !SQLITE_OS_WINCE
34618       offset += nWrite;
34619       overlapped.Offset = (LONG)(offset & 0xffffffff);
34620       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34621 #endif
34622       aRem += nWrite;
34623       nRem -= nWrite;
34624     }
34625     if( nRem>0 ){
34626       pFile->lastErrno = lastErrno;
34627       rc = 1;
34628     }
34629   }
34630
34631   if( rc ){
34632     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
34633        || ( pFile->lastErrno==ERROR_DISK_FULL )){
34634       return SQLITE_FULL;
34635     }
34636     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
34637              "winWrite", pFile->zPath);
34638   }else{
34639     logIoerr(nRetry);
34640   }
34641   return SQLITE_OK;
34642 }
34643
34644 /*
34645 ** Truncate an open file to a specified size
34646 */
34647 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
34648   winFile *pFile = (winFile*)id;  /* File handle object */
34649   int rc = SQLITE_OK;             /* Return code for this function */
34650
34651   assert( pFile );
34652
34653   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
34654   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
34655
34656   /* If the user has configured a chunk-size for this file, truncate the
34657   ** file so that it consists of an integer number of chunks (i.e. the
34658   ** actual file size after the operation may be larger than the requested
34659   ** size).
34660   */
34661   if( pFile->szChunk>0 ){
34662     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
34663   }
34664
34665   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
34666   if( seekWinFile(pFile, nByte) ){
34667     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
34668              "winTruncate1", pFile->zPath);
34669   }else if( 0==osSetEndOfFile(pFile->h) ){
34670     pFile->lastErrno = osGetLastError();
34671     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
34672              "winTruncate2", pFile->zPath);
34673   }
34674
34675   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
34676   return rc;
34677 }
34678
34679 #ifdef SQLITE_TEST
34680 /*
34681 ** Count the number of fullsyncs and normal syncs.  This is used to test
34682 ** that syncs and fullsyncs are occuring at the right times.
34683 */
34684 SQLITE_API int sqlite3_sync_count = 0;
34685 SQLITE_API int sqlite3_fullsync_count = 0;
34686 #endif
34687
34688 /*
34689 ** Make sure all writes to a particular file are committed to disk.
34690 */
34691 static int winSync(sqlite3_file *id, int flags){
34692 #ifndef SQLITE_NO_SYNC
34693   /*
34694   ** Used only when SQLITE_NO_SYNC is not defined.
34695    */
34696   BOOL rc;
34697 #endif
34698 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
34699     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
34700   /*
34701   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
34702   ** OSTRACE() macros.
34703    */
34704   winFile *pFile = (winFile*)id;
34705 #else
34706   UNUSED_PARAMETER(id);
34707 #endif
34708
34709   assert( pFile );
34710   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
34711   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
34712       || (flags&0x0F)==SQLITE_SYNC_FULL
34713   );
34714
34715   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
34716
34717   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
34718   ** line is to test that doing so does not cause any problems.
34719   */
34720   SimulateDiskfullError( return SQLITE_FULL );
34721
34722 #ifndef SQLITE_TEST
34723   UNUSED_PARAMETER(flags);
34724 #else
34725   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
34726     sqlite3_fullsync_count++;
34727   }
34728   sqlite3_sync_count++;
34729 #endif
34730
34731   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
34732   ** no-op
34733   */
34734 #ifdef SQLITE_NO_SYNC
34735   return SQLITE_OK;
34736 #else
34737   rc = osFlushFileBuffers(pFile->h);
34738   SimulateIOError( rc=FALSE );
34739   if( rc ){
34740     return SQLITE_OK;
34741   }else{
34742     pFile->lastErrno = osGetLastError();
34743     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
34744              "winSync", pFile->zPath);
34745   }
34746 #endif
34747 }
34748
34749 /*
34750 ** Determine the current size of a file in bytes
34751 */
34752 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
34753   winFile *pFile = (winFile*)id;
34754   int rc = SQLITE_OK;
34755
34756   assert( id!=0 );
34757   SimulateIOError(return SQLITE_IOERR_FSTAT);
34758 #if SQLITE_OS_WINRT
34759   {
34760     FILE_STANDARD_INFO info;
34761     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
34762                                      &info, sizeof(info)) ){
34763       *pSize = info.EndOfFile.QuadPart;
34764     }else{
34765       pFile->lastErrno = osGetLastError();
34766       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
34767                        "winFileSize", pFile->zPath);
34768     }
34769   }
34770 #else
34771   {
34772     DWORD upperBits;
34773     DWORD lowerBits;
34774     DWORD lastErrno;
34775
34776     lowerBits = osGetFileSize(pFile->h, &upperBits);
34777     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
34778     if(   (lowerBits == INVALID_FILE_SIZE)
34779        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
34780       pFile->lastErrno = lastErrno;
34781       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
34782              "winFileSize", pFile->zPath);
34783     }
34784   }
34785 #endif
34786   return rc;
34787 }
34788
34789 /*
34790 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
34791 */
34792 #ifndef LOCKFILE_FAIL_IMMEDIATELY
34793 # define LOCKFILE_FAIL_IMMEDIATELY 1
34794 #endif
34795
34796 #ifndef LOCKFILE_EXCLUSIVE_LOCK
34797 # define LOCKFILE_EXCLUSIVE_LOCK 2
34798 #endif
34799
34800 /*
34801 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
34802 ** When the LockFile function was used, it was always expected to fail
34803 ** immediately if the lock could not be obtained.  Also, it always expected to
34804 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
34805 ** and reflect those expectations; therefore, they should not be changed.
34806 */
34807 #ifndef SQLITE_LOCKFILE_FLAGS
34808 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
34809                                   LOCKFILE_EXCLUSIVE_LOCK)
34810 #endif
34811
34812 /*
34813 ** Currently, SQLite never calls the LockFileEx function without wanting the
34814 ** call to fail immediately if the lock cannot be obtained.
34815 */
34816 #ifndef SQLITE_LOCKFILEEX_FLAGS
34817 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
34818 #endif
34819
34820 /*
34821 ** Acquire a reader lock.
34822 ** Different API routines are called depending on whether or not this
34823 ** is Win9x or WinNT.
34824 */
34825 static int getReadLock(winFile *pFile){
34826   int res;
34827   if( isNT() ){
34828 #if SQLITE_OS_WINCE
34829     /*
34830     ** NOTE: Windows CE is handled differently here due its lack of the Win32
34831     **       API LockFileEx.
34832     */
34833     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
34834 #else
34835     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
34836                       SHARED_SIZE, 0);
34837 #endif
34838   }
34839 #ifdef SQLITE_WIN32_HAS_ANSI
34840   else{
34841     int lk;
34842     sqlite3_randomness(sizeof(lk), &lk);
34843     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
34844     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34845                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34846   }
34847 #endif
34848   if( res == 0 ){
34849     pFile->lastErrno = osGetLastError();
34850     /* No need to log a failure to lock */
34851   }
34852   return res;
34853 }
34854
34855 /*
34856 ** Undo a readlock
34857 */
34858 static int unlockReadLock(winFile *pFile){
34859   int res;
34860   DWORD lastErrno;
34861   if( isNT() ){
34862     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34863   }
34864 #ifdef SQLITE_WIN32_HAS_ANSI
34865   else{
34866     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34867   }
34868 #endif
34869   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
34870     pFile->lastErrno = lastErrno;
34871     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
34872              "unlockReadLock", pFile->zPath);
34873   }
34874   return res;
34875 }
34876
34877 /*
34878 ** Lock the file with the lock specified by parameter locktype - one
34879 ** of the following:
34880 **
34881 **     (1) SHARED_LOCK
34882 **     (2) RESERVED_LOCK
34883 **     (3) PENDING_LOCK
34884 **     (4) EXCLUSIVE_LOCK
34885 **
34886 ** Sometimes when requesting one lock state, additional lock states
34887 ** are inserted in between.  The locking might fail on one of the later
34888 ** transitions leaving the lock state different from what it started but
34889 ** still short of its goal.  The following chart shows the allowed
34890 ** transitions and the inserted intermediate states:
34891 **
34892 **    UNLOCKED -> SHARED
34893 **    SHARED -> RESERVED
34894 **    SHARED -> (PENDING) -> EXCLUSIVE
34895 **    RESERVED -> (PENDING) -> EXCLUSIVE
34896 **    PENDING -> EXCLUSIVE
34897 **
34898 ** This routine will only increase a lock.  The winUnlock() routine
34899 ** erases all locks at once and returns us immediately to locking level 0.
34900 ** It is not possible to lower the locking level one step at a time.  You
34901 ** must go straight to locking level 0.
34902 */
34903 static int winLock(sqlite3_file *id, int locktype){
34904   int rc = SQLITE_OK;    /* Return code from subroutines */
34905   int res = 1;           /* Result of a Windows lock call */
34906   int newLocktype;       /* Set pFile->locktype to this value before exiting */
34907   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
34908   winFile *pFile = (winFile*)id;
34909   DWORD lastErrno = NO_ERROR;
34910
34911   assert( id!=0 );
34912   OSTRACE(("LOCK %d %d was %d(%d)\n",
34913            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
34914
34915   /* If there is already a lock of this type or more restrictive on the
34916   ** OsFile, do nothing. Don't use the end_lock: exit path, as
34917   ** sqlite3OsEnterMutex() hasn't been called yet.
34918   */
34919   if( pFile->locktype>=locktype ){
34920     return SQLITE_OK;
34921   }
34922
34923   /* Make sure the locking sequence is correct
34924   */
34925   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
34926   assert( locktype!=PENDING_LOCK );
34927   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
34928
34929   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
34930   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
34931   ** the PENDING_LOCK byte is temporary.
34932   */
34933   newLocktype = pFile->locktype;
34934   if(   (pFile->locktype==NO_LOCK)
34935      || (   (locktype==EXCLUSIVE_LOCK)
34936          && (pFile->locktype==RESERVED_LOCK))
34937   ){
34938     int cnt = 3;
34939     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34940                                          PENDING_BYTE, 0, 1, 0))==0 ){
34941       /* Try 3 times to get the pending lock.  This is needed to work
34942       ** around problems caused by indexing and/or anti-virus software on
34943       ** Windows systems.
34944       ** If you are using this code as a model for alternative VFSes, do not
34945       ** copy this retry logic.  It is a hack intended for Windows only.
34946       */
34947       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
34948       if( cnt ) sqlite3_win32_sleep(1);
34949     }
34950     gotPendingLock = res;
34951     if( !res ){
34952       lastErrno = osGetLastError();
34953     }
34954   }
34955
34956   /* Acquire a shared lock
34957   */
34958   if( locktype==SHARED_LOCK && res ){
34959     assert( pFile->locktype==NO_LOCK );
34960     res = getReadLock(pFile);
34961     if( res ){
34962       newLocktype = SHARED_LOCK;
34963     }else{
34964       lastErrno = osGetLastError();
34965     }
34966   }
34967
34968   /* Acquire a RESERVED lock
34969   */
34970   if( locktype==RESERVED_LOCK && res ){
34971     assert( pFile->locktype==SHARED_LOCK );
34972     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
34973     if( res ){
34974       newLocktype = RESERVED_LOCK;
34975     }else{
34976       lastErrno = osGetLastError();
34977     }
34978   }
34979
34980   /* Acquire a PENDING lock
34981   */
34982   if( locktype==EXCLUSIVE_LOCK && res ){
34983     newLocktype = PENDING_LOCK;
34984     gotPendingLock = 0;
34985   }
34986
34987   /* Acquire an EXCLUSIVE lock
34988   */
34989   if( locktype==EXCLUSIVE_LOCK && res ){
34990     assert( pFile->locktype>=SHARED_LOCK );
34991     res = unlockReadLock(pFile);
34992     OSTRACE(("unreadlock = %d\n", res));
34993     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
34994                       SHARED_SIZE, 0);
34995     if( res ){
34996       newLocktype = EXCLUSIVE_LOCK;
34997     }else{
34998       lastErrno = osGetLastError();
34999       OSTRACE(("error-code = %d\n", lastErrno));
35000       getReadLock(pFile);
35001     }
35002   }
35003
35004   /* If we are holding a PENDING lock that ought to be released, then
35005   ** release it now.
35006   */
35007   if( gotPendingLock && locktype==SHARED_LOCK ){
35008     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35009   }
35010
35011   /* Update the state of the lock has held in the file descriptor then
35012   ** return the appropriate result code.
35013   */
35014   if( res ){
35015     rc = SQLITE_OK;
35016   }else{
35017     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
35018            locktype, newLocktype));
35019     pFile->lastErrno = lastErrno;
35020     rc = SQLITE_BUSY;
35021   }
35022   pFile->locktype = (u8)newLocktype;
35023   return rc;
35024 }
35025
35026 /*
35027 ** This routine checks if there is a RESERVED lock held on the specified
35028 ** file by this or any other process. If such a lock is held, return
35029 ** non-zero, otherwise zero.
35030 */
35031 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
35032   int rc;
35033   winFile *pFile = (winFile*)id;
35034
35035   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
35036
35037   assert( id!=0 );
35038   if( pFile->locktype>=RESERVED_LOCK ){
35039     rc = 1;
35040     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
35041   }else{
35042     rc = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
35043     if( rc ){
35044       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35045     }
35046     rc = !rc;
35047     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
35048   }
35049   *pResOut = rc;
35050   return SQLITE_OK;
35051 }
35052
35053 /*
35054 ** Lower the locking level on file descriptor id to locktype.  locktype
35055 ** must be either NO_LOCK or SHARED_LOCK.
35056 **
35057 ** If the locking level of the file descriptor is already at or below
35058 ** the requested locking level, this routine is a no-op.
35059 **
35060 ** It is not possible for this routine to fail if the second argument
35061 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
35062 ** might return SQLITE_IOERR;
35063 */
35064 static int winUnlock(sqlite3_file *id, int locktype){
35065   int type;
35066   winFile *pFile = (winFile*)id;
35067   int rc = SQLITE_OK;
35068   assert( pFile!=0 );
35069   assert( locktype<=SHARED_LOCK );
35070   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
35071           pFile->locktype, pFile->sharedLockByte));
35072   type = pFile->locktype;
35073   if( type>=EXCLUSIVE_LOCK ){
35074     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
35075     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
35076       /* This should never happen.  We should always be able to
35077       ** reacquire the read lock */
35078       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
35079                "winUnlock", pFile->zPath);
35080     }
35081   }
35082   if( type>=RESERVED_LOCK ){
35083     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
35084   }
35085   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
35086     unlockReadLock(pFile);
35087   }
35088   if( type>=PENDING_LOCK ){
35089     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
35090   }
35091   pFile->locktype = (u8)locktype;
35092   return rc;
35093 }
35094
35095 /*
35096 ** If *pArg is inititially negative then this is a query.  Set *pArg to
35097 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
35098 **
35099 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
35100 */
35101 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
35102   if( *pArg<0 ){
35103     *pArg = (pFile->ctrlFlags & mask)!=0;
35104   }else if( (*pArg)==0 ){
35105     pFile->ctrlFlags &= ~mask;
35106   }else{
35107     pFile->ctrlFlags |= mask;
35108   }
35109 }
35110
35111 /* Forward declaration */
35112 static int getTempname(int nBuf, char *zBuf);
35113
35114 /*
35115 ** Control and query of the open file handle.
35116 */
35117 static int winFileControl(sqlite3_file *id, int op, void *pArg){
35118   winFile *pFile = (winFile*)id;
35119   switch( op ){
35120     case SQLITE_FCNTL_LOCKSTATE: {
35121       *(int*)pArg = pFile->locktype;
35122       return SQLITE_OK;
35123     }
35124     case SQLITE_LAST_ERRNO: {
35125       *(int*)pArg = (int)pFile->lastErrno;
35126       return SQLITE_OK;
35127     }
35128     case SQLITE_FCNTL_CHUNK_SIZE: {
35129       pFile->szChunk = *(int *)pArg;
35130       return SQLITE_OK;
35131     }
35132     case SQLITE_FCNTL_SIZE_HINT: {
35133       if( pFile->szChunk>0 ){
35134         sqlite3_int64 oldSz;
35135         int rc = winFileSize(id, &oldSz);
35136         if( rc==SQLITE_OK ){
35137           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
35138           if( newSz>oldSz ){
35139             SimulateIOErrorBenign(1);
35140             rc = winTruncate(id, newSz);
35141             SimulateIOErrorBenign(0);
35142           }
35143         }
35144         return rc;
35145       }
35146       return SQLITE_OK;
35147     }
35148     case SQLITE_FCNTL_PERSIST_WAL: {
35149       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
35150       return SQLITE_OK;
35151     }
35152     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
35153       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
35154       return SQLITE_OK;
35155     }
35156     case SQLITE_FCNTL_VFSNAME: {
35157       *(char**)pArg = sqlite3_mprintf("win32");
35158       return SQLITE_OK;
35159     }
35160     case SQLITE_FCNTL_WIN32_AV_RETRY: {
35161       int *a = (int*)pArg;
35162       if( a[0]>0 ){
35163         win32IoerrRetry = a[0];
35164       }else{
35165         a[0] = win32IoerrRetry;
35166       }
35167       if( a[1]>0 ){
35168         win32IoerrRetryDelay = a[1];
35169       }else{
35170         a[1] = win32IoerrRetryDelay;
35171       }
35172       return SQLITE_OK;
35173     }
35174     case SQLITE_FCNTL_TEMPFILENAME: {
35175       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
35176       if( zTFile ){
35177         getTempname(pFile->pVfs->mxPathname, zTFile);
35178         *(char**)pArg = zTFile;
35179       }
35180       return SQLITE_OK;
35181     }
35182   }
35183   return SQLITE_NOTFOUND;
35184 }
35185
35186 /*
35187 ** Return the sector size in bytes of the underlying block device for
35188 ** the specified file. This is almost always 512 bytes, but may be
35189 ** larger for some devices.
35190 **
35191 ** SQLite code assumes this function cannot fail. It also assumes that
35192 ** if two files are created in the same file-system directory (i.e.
35193 ** a database and its journal file) that the sector size will be the
35194 ** same for both.
35195 */
35196 static int winSectorSize(sqlite3_file *id){
35197   (void)id;
35198   return SQLITE_DEFAULT_SECTOR_SIZE;
35199 }
35200
35201 /*
35202 ** Return a vector of device characteristics.
35203 */
35204 static int winDeviceCharacteristics(sqlite3_file *id){
35205   winFile *p = (winFile*)id;
35206   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
35207          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
35208 }
35209
35210 #ifndef SQLITE_OMIT_WAL
35211
35212 /*
35213 ** Windows will only let you create file view mappings
35214 ** on allocation size granularity boundaries.
35215 ** During sqlite3_os_init() we do a GetSystemInfo()
35216 ** to get the granularity size.
35217 */
35218 SYSTEM_INFO winSysInfo;
35219
35220 /*
35221 ** Helper functions to obtain and relinquish the global mutex. The
35222 ** global mutex is used to protect the winLockInfo objects used by
35223 ** this file, all of which may be shared by multiple threads.
35224 **
35225 ** Function winShmMutexHeld() is used to assert() that the global mutex
35226 ** is held when required. This function is only used as part of assert()
35227 ** statements. e.g.
35228 **
35229 **   winShmEnterMutex()
35230 **     assert( winShmMutexHeld() );
35231 **   winShmLeaveMutex()
35232 */
35233 static void winShmEnterMutex(void){
35234   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35235 }
35236 static void winShmLeaveMutex(void){
35237   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35238 }
35239 #ifdef SQLITE_DEBUG
35240 static int winShmMutexHeld(void) {
35241   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
35242 }
35243 #endif
35244
35245 /*
35246 ** Object used to represent a single file opened and mmapped to provide
35247 ** shared memory.  When multiple threads all reference the same
35248 ** log-summary, each thread has its own winFile object, but they all
35249 ** point to a single instance of this object.  In other words, each
35250 ** log-summary is opened only once per process.
35251 **
35252 ** winShmMutexHeld() must be true when creating or destroying
35253 ** this object or while reading or writing the following fields:
35254 **
35255 **      nRef
35256 **      pNext
35257 **
35258 ** The following fields are read-only after the object is created:
35259 **
35260 **      fid
35261 **      zFilename
35262 **
35263 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
35264 ** winShmMutexHeld() is true when reading or writing any other field
35265 ** in this structure.
35266 **
35267 */
35268 struct winShmNode {
35269   sqlite3_mutex *mutex;      /* Mutex to access this object */
35270   char *zFilename;           /* Name of the file */
35271   winFile hFile;             /* File handle from winOpen */
35272
35273   int szRegion;              /* Size of shared-memory regions */
35274   int nRegion;               /* Size of array apRegion */
35275   struct ShmRegion {
35276     HANDLE hMap;             /* File handle from CreateFileMapping */
35277     void *pMap;
35278   } *aRegion;
35279   DWORD lastErrno;           /* The Windows errno from the last I/O error */
35280
35281   int nRef;                  /* Number of winShm objects pointing to this */
35282   winShm *pFirst;            /* All winShm objects pointing to this */
35283   winShmNode *pNext;         /* Next in list of all winShmNode objects */
35284 #ifdef SQLITE_DEBUG
35285   u8 nextShmId;              /* Next available winShm.id value */
35286 #endif
35287 };
35288
35289 /*
35290 ** A global array of all winShmNode objects.
35291 **
35292 ** The winShmMutexHeld() must be true while reading or writing this list.
35293 */
35294 static winShmNode *winShmNodeList = 0;
35295
35296 /*
35297 ** Structure used internally by this VFS to record the state of an
35298 ** open shared memory connection.
35299 **
35300 ** The following fields are initialized when this object is created and
35301 ** are read-only thereafter:
35302 **
35303 **    winShm.pShmNode
35304 **    winShm.id
35305 **
35306 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
35307 ** while accessing any read/write fields.
35308 */
35309 struct winShm {
35310   winShmNode *pShmNode;      /* The underlying winShmNode object */
35311   winShm *pNext;             /* Next winShm with the same winShmNode */
35312   u8 hasMutex;               /* True if holding the winShmNode mutex */
35313   u16 sharedMask;            /* Mask of shared locks held */
35314   u16 exclMask;              /* Mask of exclusive locks held */
35315 #ifdef SQLITE_DEBUG
35316   u8 id;                     /* Id of this connection with its winShmNode */
35317 #endif
35318 };
35319
35320 /*
35321 ** Constants used for locking
35322 */
35323 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
35324 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
35325
35326 /*
35327 ** Apply advisory locks for all n bytes beginning at ofst.
35328 */
35329 #define _SHM_UNLCK  1
35330 #define _SHM_RDLCK  2
35331 #define _SHM_WRLCK  3
35332 static int winShmSystemLock(
35333   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
35334   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
35335   int ofst,             /* Offset to first byte to be locked/unlocked */
35336   int nByte             /* Number of bytes to lock or unlock */
35337 ){
35338   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
35339
35340   /* Access to the winShmNode object is serialized by the caller */
35341   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
35342
35343   /* Release/Acquire the system-level lock */
35344   if( lockType==_SHM_UNLCK ){
35345     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
35346   }else{
35347     /* Initialize the locking parameters */
35348     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
35349     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
35350     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
35351   }
35352
35353   if( rc!= 0 ){
35354     rc = SQLITE_OK;
35355   }else{
35356     pFile->lastErrno =  osGetLastError();
35357     rc = SQLITE_BUSY;
35358   }
35359
35360   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
35361            pFile->hFile.h,
35362            rc==SQLITE_OK ? "ok" : "failed",
35363            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
35364            pFile->lastErrno));
35365
35366   return rc;
35367 }
35368
35369 /* Forward references to VFS methods */
35370 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
35371 static int winDelete(sqlite3_vfs *,const char*,int);
35372
35373 /*
35374 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
35375 **
35376 ** This is not a VFS shared-memory method; it is a utility function called
35377 ** by VFS shared-memory methods.
35378 */
35379 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
35380   winShmNode **pp;
35381   winShmNode *p;
35382   __attribute__((unused)) BOOL bRc;
35383   assert( winShmMutexHeld() );
35384   pp = &winShmNodeList;
35385   while( (p = *pp)!=0 ){
35386     if( p->nRef==0 ){
35387       int i;
35388       if( p->mutex ) sqlite3_mutex_free(p->mutex);
35389       for(i=0; i<p->nRegion; i++){
35390         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
35391         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
35392                  (int)osGetCurrentProcessId(), i,
35393                  bRc ? "ok" : "failed"));
35394         bRc = osCloseHandle(p->aRegion[i].hMap);
35395         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
35396                  (int)osGetCurrentProcessId(), i,
35397                  bRc ? "ok" : "failed"));
35398       }
35399       if( p->hFile.h != INVALID_HANDLE_VALUE ){
35400         SimulateIOErrorBenign(1);
35401         winClose((sqlite3_file *)&p->hFile);
35402         SimulateIOErrorBenign(0);
35403       }
35404       if( deleteFlag ){
35405         SimulateIOErrorBenign(1);
35406         sqlite3BeginBenignMalloc();
35407         winDelete(pVfs, p->zFilename, 0);
35408         sqlite3EndBenignMalloc();
35409         SimulateIOErrorBenign(0);
35410       }
35411       *pp = p->pNext;
35412       sqlite3_free(p->aRegion);
35413       sqlite3_free(p);
35414     }else{
35415       pp = &p->pNext;
35416     }
35417   }
35418 }
35419
35420 /*
35421 ** Open the shared-memory area associated with database file pDbFd.
35422 **
35423 ** When opening a new shared-memory file, if no other instances of that
35424 ** file are currently open, in this process or in other processes, then
35425 ** the file must be truncated to zero length or have its header cleared.
35426 */
35427 static int winOpenSharedMemory(winFile *pDbFd){
35428   struct winShm *p;                  /* The connection to be opened */
35429   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
35430   int rc;                            /* Result code */
35431   struct winShmNode *pNew;           /* Newly allocated winShmNode */
35432   int nName;                         /* Size of zName in bytes */
35433
35434   assert( pDbFd->pShm==0 );    /* Not previously opened */
35435
35436   /* Allocate space for the new sqlite3_shm object.  Also speculatively
35437   ** allocate space for a new winShmNode and filename.
35438   */
35439   p = sqlite3MallocZero( sizeof(*p) );
35440   if( p==0 ) return SQLITE_IOERR_NOMEM;
35441   nName = sqlite3Strlen30(pDbFd->zPath);
35442   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
35443   if( pNew==0 ){
35444     sqlite3_free(p);
35445     return SQLITE_IOERR_NOMEM;
35446   }
35447   pNew->zFilename = (char*)&pNew[1];
35448   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
35449   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
35450
35451   /* Look to see if there is an existing winShmNode that can be used.
35452   ** If no matching winShmNode currently exists, create a new one.
35453   */
35454   winShmEnterMutex();
35455   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
35456     /* TBD need to come up with better match here.  Perhaps
35457     ** use FILE_ID_BOTH_DIR_INFO Structure.
35458     */
35459     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
35460   }
35461   if( pShmNode ){
35462     sqlite3_free(pNew);
35463   }else{
35464     pShmNode = pNew;
35465     pNew = 0;
35466     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
35467     pShmNode->pNext = winShmNodeList;
35468     winShmNodeList = pShmNode;
35469
35470     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
35471     if( pShmNode->mutex==0 ){
35472       rc = SQLITE_IOERR_NOMEM;
35473       goto shm_open_err;
35474     }
35475
35476     rc = winOpen(pDbFd->pVfs,
35477                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
35478                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
35479                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
35480                  0);
35481     if( SQLITE_OK!=rc ){
35482       goto shm_open_err;
35483     }
35484
35485     /* Check to see if another process is holding the dead-man switch.
35486     ** If not, truncate the file to zero length.
35487     */
35488     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
35489       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
35490       if( rc!=SQLITE_OK ){
35491         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
35492                  "winOpenShm", pDbFd->zPath);
35493       }
35494     }
35495     if( rc==SQLITE_OK ){
35496       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35497       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
35498     }
35499     if( rc ) goto shm_open_err;
35500   }
35501
35502   /* Make the new connection a child of the winShmNode */
35503   p->pShmNode = pShmNode;
35504 #ifdef SQLITE_DEBUG
35505   p->id = pShmNode->nextShmId++;
35506 #endif
35507   pShmNode->nRef++;
35508   pDbFd->pShm = p;
35509   winShmLeaveMutex();
35510
35511   /* The reference count on pShmNode has already been incremented under
35512   ** the cover of the winShmEnterMutex() mutex and the pointer from the
35513   ** new (struct winShm) object to the pShmNode has been set. All that is
35514   ** left to do is to link the new object into the linked list starting
35515   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
35516   ** mutex.
35517   */
35518   sqlite3_mutex_enter(pShmNode->mutex);
35519   p->pNext = pShmNode->pFirst;
35520   pShmNode->pFirst = p;
35521   sqlite3_mutex_leave(pShmNode->mutex);
35522   return SQLITE_OK;
35523
35524   /* Jump here on any error */
35525 shm_open_err:
35526   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35527   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
35528   sqlite3_free(p);
35529   sqlite3_free(pNew);
35530   winShmLeaveMutex();
35531   return rc;
35532 }
35533
35534 /*
35535 ** Close a connection to shared-memory.  Delete the underlying
35536 ** storage if deleteFlag is true.
35537 */
35538 static int winShmUnmap(
35539   sqlite3_file *fd,          /* Database holding shared memory */
35540   int deleteFlag             /* Delete after closing if true */
35541 ){
35542   winFile *pDbFd;       /* Database holding shared-memory */
35543   winShm *p;            /* The connection to be closed */
35544   winShmNode *pShmNode; /* The underlying shared-memory file */
35545   winShm **pp;          /* For looping over sibling connections */
35546
35547   pDbFd = (winFile*)fd;
35548   p = pDbFd->pShm;
35549   if( p==0 ) return SQLITE_OK;
35550   pShmNode = p->pShmNode;
35551
35552   /* Remove connection p from the set of connections associated
35553   ** with pShmNode */
35554   sqlite3_mutex_enter(pShmNode->mutex);
35555   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
35556   *pp = p->pNext;
35557
35558   /* Free the connection p */
35559   sqlite3_free(p);
35560   pDbFd->pShm = 0;
35561   sqlite3_mutex_leave(pShmNode->mutex);
35562
35563   /* If pShmNode->nRef has reached 0, then close the underlying
35564   ** shared-memory file, too */
35565   winShmEnterMutex();
35566   assert( pShmNode->nRef>0 );
35567   pShmNode->nRef--;
35568   if( pShmNode->nRef==0 ){
35569     winShmPurge(pDbFd->pVfs, deleteFlag);
35570   }
35571   winShmLeaveMutex();
35572
35573   return SQLITE_OK;
35574 }
35575
35576 /*
35577 ** Change the lock state for a shared-memory segment.
35578 */
35579 static int winShmLock(
35580   sqlite3_file *fd,          /* Database file holding the shared memory */
35581   int ofst,                  /* First lock to acquire or release */
35582   int n,                     /* Number of locks to acquire or release */
35583   int flags                  /* What to do with the lock */
35584 ){
35585   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
35586   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
35587   winShm *pX;                           /* For looping over all siblings */
35588   winShmNode *pShmNode = p->pShmNode;
35589   int rc = SQLITE_OK;                   /* Result code */
35590   u16 mask;                             /* Mask of locks to take or release */
35591
35592   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
35593   assert( n>=1 );
35594   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
35595        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
35596        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
35597        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
35598   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
35599
35600   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
35601   assert( n>1 || mask==(1<<ofst) );
35602   sqlite3_mutex_enter(pShmNode->mutex);
35603   if( flags & SQLITE_SHM_UNLOCK ){
35604     u16 allMask = 0; /* Mask of locks held by siblings */
35605
35606     /* See if any siblings hold this same lock */
35607     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35608       if( pX==p ) continue;
35609       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
35610       allMask |= pX->sharedMask;
35611     }
35612
35613     /* Unlock the system-level locks */
35614     if( (mask & allMask)==0 ){
35615       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
35616     }else{
35617       rc = SQLITE_OK;
35618     }
35619
35620     /* Undo the local locks */
35621     if( rc==SQLITE_OK ){
35622       p->exclMask &= ~mask;
35623       p->sharedMask &= ~mask;
35624     }
35625   }else if( flags & SQLITE_SHM_SHARED ){
35626     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
35627
35628     /* Find out which shared locks are already held by sibling connections.
35629     ** If any sibling already holds an exclusive lock, go ahead and return
35630     ** SQLITE_BUSY.
35631     */
35632     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35633       if( (pX->exclMask & mask)!=0 ){
35634         rc = SQLITE_BUSY;
35635         break;
35636       }
35637       allShared |= pX->sharedMask;
35638     }
35639
35640     /* Get shared locks at the system level, if necessary */
35641     if( rc==SQLITE_OK ){
35642       if( (allShared & mask)==0 ){
35643         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
35644       }else{
35645         rc = SQLITE_OK;
35646       }
35647     }
35648
35649     /* Get the local shared locks */
35650     if( rc==SQLITE_OK ){
35651       p->sharedMask |= mask;
35652     }
35653   }else{
35654     /* Make sure no sibling connections hold locks that will block this
35655     ** lock.  If any do, return SQLITE_BUSY right away.
35656     */
35657     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35658       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
35659         rc = SQLITE_BUSY;
35660         break;
35661       }
35662     }
35663
35664     /* Get the exclusive locks at the system level.  Then if successful
35665     ** also mark the local connection as being locked.
35666     */
35667     if( rc==SQLITE_OK ){
35668       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
35669       if( rc==SQLITE_OK ){
35670         assert( (p->sharedMask & mask)==0 );
35671         p->exclMask |= mask;
35672       }
35673     }
35674   }
35675   sqlite3_mutex_leave(pShmNode->mutex);
35676   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
35677            p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
35678            rc ? "failed" : "ok"));
35679   return rc;
35680 }
35681
35682 /*
35683 ** Implement a memory barrier or memory fence on shared memory.
35684 **
35685 ** All loads and stores begun before the barrier must complete before
35686 ** any load or store begun after the barrier.
35687 */
35688 static void winShmBarrier(
35689   sqlite3_file *fd          /* Database holding the shared memory */
35690 ){
35691   UNUSED_PARAMETER(fd);
35692   /* MemoryBarrier(); // does not work -- do not know why not */
35693   winShmEnterMutex();
35694   winShmLeaveMutex();
35695 }
35696
35697 /*
35698 ** This function is called to obtain a pointer to region iRegion of the
35699 ** shared-memory associated with the database file fd. Shared-memory regions
35700 ** are numbered starting from zero. Each shared-memory region is szRegion
35701 ** bytes in size.
35702 **
35703 ** If an error occurs, an error code is returned and *pp is set to NULL.
35704 **
35705 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
35706 ** region has not been allocated (by any client, including one running in a
35707 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
35708 ** isWrite is non-zero and the requested shared-memory region has not yet
35709 ** been allocated, it is allocated by this function.
35710 **
35711 ** If the shared-memory region has already been allocated or is allocated by
35712 ** this call as described above, then it is mapped into this processes
35713 ** address space (if it is not already), *pp is set to point to the mapped
35714 ** memory and SQLITE_OK returned.
35715 */
35716 static int winShmMap(
35717   sqlite3_file *fd,               /* Handle open on database file */
35718   int iRegion,                    /* Region to retrieve */
35719   int szRegion,                   /* Size of regions */
35720   int isWrite,                    /* True to extend file if necessary */
35721   void volatile **pp              /* OUT: Mapped memory */
35722 ){
35723   winFile *pDbFd = (winFile*)fd;
35724   winShm *p = pDbFd->pShm;
35725   winShmNode *pShmNode;
35726   int rc = SQLITE_OK;
35727
35728   if( !p ){
35729     rc = winOpenSharedMemory(pDbFd);
35730     if( rc!=SQLITE_OK ) return rc;
35731     p = pDbFd->pShm;
35732   }
35733   pShmNode = p->pShmNode;
35734
35735   sqlite3_mutex_enter(pShmNode->mutex);
35736   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
35737
35738   if( pShmNode->nRegion<=iRegion ){
35739     struct ShmRegion *apNew;           /* New aRegion[] array */
35740     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
35741     sqlite3_int64 sz;                  /* Current size of wal-index file */
35742
35743     pShmNode->szRegion = szRegion;
35744
35745     /* The requested region is not mapped into this processes address space.
35746     ** Check to see if it has been allocated (i.e. if the wal-index file is
35747     ** large enough to contain the requested region).
35748     */
35749     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
35750     if( rc!=SQLITE_OK ){
35751       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35752                "winShmMap1", pDbFd->zPath);
35753       goto shmpage_out;
35754     }
35755
35756     if( sz<nByte ){
35757       /* The requested memory region does not exist. If isWrite is set to
35758       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
35759       **
35760       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
35761       ** the requested memory region.
35762       */
35763       if( !isWrite ) goto shmpage_out;
35764       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
35765       if( rc!=SQLITE_OK ){
35766         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35767                  "winShmMap2", pDbFd->zPath);
35768         goto shmpage_out;
35769       }
35770     }
35771
35772     /* Map the requested memory region into this processes address space. */
35773     apNew = (struct ShmRegion *)sqlite3_realloc(
35774         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
35775     );
35776     if( !apNew ){
35777       rc = SQLITE_IOERR_NOMEM;
35778       goto shmpage_out;
35779     }
35780     pShmNode->aRegion = apNew;
35781
35782     while( pShmNode->nRegion<=iRegion ){
35783       HANDLE hMap = NULL;         /* file-mapping handle */
35784       void *pMap = 0;             /* Mapped memory region */
35785
35786 #if SQLITE_OS_WINRT
35787       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
35788           NULL, PAGE_READWRITE, nByte, NULL
35789       );
35790 #elif defined(SQLITE_WIN32_HAS_WIDE)
35791       hMap = osCreateFileMappingW(pShmNode->hFile.h,
35792           NULL, PAGE_READWRITE, 0, nByte, NULL
35793       );
35794 #elif defined(SQLITE_WIN32_HAS_ANSI)
35795       hMap = osCreateFileMappingA(pShmNode->hFile.h,
35796           NULL, PAGE_READWRITE, 0, nByte, NULL
35797       );
35798 #endif
35799       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
35800                (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
35801                hMap ? "ok" : "failed"));
35802       if( hMap ){
35803         int iOffset = pShmNode->nRegion*szRegion;
35804         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35805 #if SQLITE_OS_WINRT
35806         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35807             iOffset - iOffsetShift, szRegion + iOffsetShift
35808         );
35809 #else
35810         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35811             0, iOffset - iOffsetShift, szRegion + iOffsetShift
35812         );
35813 #endif
35814         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
35815                  (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
35816                  szRegion, pMap ? "ok" : "failed"));
35817       }
35818       if( !pMap ){
35819         pShmNode->lastErrno = osGetLastError();
35820         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
35821                  "winShmMap3", pDbFd->zPath);
35822         if( hMap ) osCloseHandle(hMap);
35823         goto shmpage_out;
35824       }
35825
35826       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
35827       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
35828       pShmNode->nRegion++;
35829     }
35830   }
35831
35832 shmpage_out:
35833   if( pShmNode->nRegion>iRegion ){
35834     int iOffset = iRegion*szRegion;
35835     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35836     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
35837     *pp = (void *)&p[iOffsetShift];
35838   }else{
35839     *pp = 0;
35840   }
35841   sqlite3_mutex_leave(pShmNode->mutex);
35842   return rc;
35843 }
35844
35845 #else
35846 # define winShmMap     0
35847 # define winShmLock    0
35848 # define winShmBarrier 0
35849 # define winShmUnmap   0
35850 #endif /* #ifndef SQLITE_OMIT_WAL */
35851
35852 /*
35853 ** Here ends the implementation of all sqlite3_file methods.
35854 **
35855 ********************** End sqlite3_file Methods *******************************
35856 ******************************************************************************/
35857
35858 /*
35859 ** This vector defines all the methods that can operate on an
35860 ** sqlite3_file for win32.
35861 */
35862 static const sqlite3_io_methods winIoMethod = {
35863   2,                              /* iVersion */
35864   winClose,                       /* xClose */
35865   winRead,                        /* xRead */
35866   winWrite,                       /* xWrite */
35867   winTruncate,                    /* xTruncate */
35868   winSync,                        /* xSync */
35869   winFileSize,                    /* xFileSize */
35870   winLock,                        /* xLock */
35871   winUnlock,                      /* xUnlock */
35872   winCheckReservedLock,           /* xCheckReservedLock */
35873   winFileControl,                 /* xFileControl */
35874   winSectorSize,                  /* xSectorSize */
35875   winDeviceCharacteristics,       /* xDeviceCharacteristics */
35876   winShmMap,                      /* xShmMap */
35877   winShmLock,                     /* xShmLock */
35878   winShmBarrier,                  /* xShmBarrier */
35879   winShmUnmap                     /* xShmUnmap */
35880 };
35881
35882 /****************************************************************************
35883 **************************** sqlite3_vfs methods ****************************
35884 **
35885 ** This division contains the implementation of methods on the
35886 ** sqlite3_vfs object.
35887 */
35888
35889 /*
35890 ** Convert a UTF-8 filename into whatever form the underlying
35891 ** operating system wants filenames in.  Space to hold the result
35892 ** is obtained from malloc and must be freed by the calling
35893 ** function.
35894 */
35895 static void *convertUtf8Filename(const char *zFilename){
35896   void *zConverted = 0;
35897   if( isNT() ){
35898     zConverted = utf8ToUnicode(zFilename);
35899   }
35900 #ifdef SQLITE_WIN32_HAS_ANSI
35901   else{
35902     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
35903   }
35904 #endif
35905   /* caller will handle out of memory */
35906   return zConverted;
35907 }
35908
35909 /*
35910 ** Create a temporary file name in zBuf.  zBuf must be big enough to
35911 ** hold at pVfs->mxPathname characters.
35912 */
35913 static int getTempname(int nBuf, char *zBuf){
35914   static char zChars[] =
35915     "abcdefghijklmnopqrstuvwxyz"
35916     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35917     "0123456789";
35918   size_t i, j;
35919   int nTempPath;
35920   char zTempPath[MAX_PATH+2];
35921
35922   /* It's odd to simulate an io-error here, but really this is just
35923   ** using the io-error infrastructure to test that SQLite handles this
35924   ** function failing.
35925   */
35926   SimulateIOError( return SQLITE_IOERR );
35927
35928   memset(zTempPath, 0, MAX_PATH+2);
35929
35930   if( sqlite3_temp_directory ){
35931     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
35932   }
35933 #if !SQLITE_OS_WINRT
35934   else if( isNT() ){
35935     char *zMulti;
35936     WCHAR zWidePath[MAX_PATH];
35937     osGetTempPathW(MAX_PATH-30, zWidePath);
35938     zMulti = unicodeToUtf8(zWidePath);
35939     if( zMulti ){
35940       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
35941       sqlite3_free(zMulti);
35942     }else{
35943       return SQLITE_IOERR_NOMEM;
35944     }
35945   }
35946 #ifdef SQLITE_WIN32_HAS_ANSI
35947   else{
35948     char *zUtf8;
35949     char zMbcsPath[MAX_PATH];
35950     osGetTempPathA(MAX_PATH-30, zMbcsPath);
35951     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
35952     if( zUtf8 ){
35953       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
35954       sqlite3_free(zUtf8);
35955     }else{
35956       return SQLITE_IOERR_NOMEM;
35957     }
35958   }
35959 #endif
35960 #endif
35961
35962   /* Check that the output buffer is large enough for the temporary file
35963   ** name. If it is not, return SQLITE_ERROR.
35964   */
35965   nTempPath = sqlite3Strlen30(zTempPath);
35966
35967   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
35968     return SQLITE_ERROR;
35969   }
35970
35971   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
35972   zTempPath[i] = 0;
35973
35974   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
35975                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
35976                    zTempPath);
35977   j = sqlite3Strlen30(zBuf);
35978   sqlite3_randomness(15, &zBuf[j]);
35979   for(i=0; i<15; i++, j++){
35980     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
35981   }
35982   zBuf[j] = 0;
35983   zBuf[j+1] = 0;
35984
35985   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
35986   return SQLITE_OK;
35987 }
35988
35989 /*
35990 ** Return TRUE if the named file is really a directory.  Return false if
35991 ** it is something other than a directory, or if there is any kind of memory
35992 ** allocation failure.
35993 */
35994 static int winIsDir(const void *zConverted){
35995   DWORD attr;
35996   int rc = 0;
35997   DWORD lastErrno;
35998
35999   if( isNT() ){
36000     int cnt = 0;
36001     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36002     memset(&sAttrData, 0, sizeof(sAttrData));
36003     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
36004                              GetFileExInfoStandard,
36005                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
36006     if( !rc ){
36007       return 0; /* Invalid name? */
36008     }
36009     attr = sAttrData.dwFileAttributes;
36010 #if SQLITE_OS_WINCE==0
36011   }else{
36012     attr = osGetFileAttributesA((char*)zConverted);
36013 #endif
36014   }
36015   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
36016 }
36017
36018 /*
36019 ** Open a file.
36020 */
36021 static int winOpen(
36022   sqlite3_vfs *pVfs,        /* Not used */
36023   const char *zName,        /* Name of the file (UTF-8) */
36024   sqlite3_file *id,         /* Write the SQLite file handle here */
36025   int flags,                /* Open mode flags */
36026   int *pOutFlags            /* Status return flags */
36027 ){
36028   HANDLE h;
36029   DWORD lastErrno;
36030   DWORD dwDesiredAccess;
36031   DWORD dwShareMode;
36032   DWORD dwCreationDisposition;
36033   DWORD dwFlagsAndAttributes = 0;
36034 #if SQLITE_OS_WINCE
36035   int isTemp = 0;
36036 #endif
36037   winFile *pFile = (winFile*)id;
36038   void *zConverted;              /* Filename in OS encoding */
36039   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
36040   int cnt = 0;
36041
36042   /* If argument zPath is a NULL pointer, this function is required to open
36043   ** a temporary file. Use this buffer to store the file name in.
36044   */
36045   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
36046
36047   int rc = SQLITE_OK;            /* Function Return Code */
36048 #if !defined(NDEBUG) || SQLITE_OS_WINCE
36049   int eType = flags&0xFFFFFF00;  /* Type of file to open */
36050 #endif
36051
36052   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
36053   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
36054   int isCreate     = (flags & SQLITE_OPEN_CREATE);
36055 #ifndef NDEBUG
36056   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
36057 #endif
36058   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
36059
36060 #ifndef NDEBUG
36061   int isOpenJournal = (isCreate && (
36062         eType==SQLITE_OPEN_MASTER_JOURNAL
36063      || eType==SQLITE_OPEN_MAIN_JOURNAL
36064      || eType==SQLITE_OPEN_WAL
36065   ));
36066 #endif
36067
36068   /* Check the following statements are true:
36069   **
36070   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
36071   **   (b) if CREATE is set, then READWRITE must also be set, and
36072   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
36073   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
36074   */
36075   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
36076   assert(isCreate==0 || isReadWrite);
36077   assert(isExclusive==0 || isCreate);
36078   assert(isDelete==0 || isCreate);
36079
36080   /* The main DB, main journal, WAL file and master journal are never
36081   ** automatically deleted. Nor are they ever temporary files.  */
36082   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
36083   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
36084   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
36085   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
36086
36087   /* Assert that the upper layer has set one of the "file-type" flags. */
36088   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
36089        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
36090        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
36091        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
36092   );
36093
36094   assert( id!=0 );
36095   UNUSED_PARAMETER(pVfs);
36096
36097 #if SQLITE_OS_WINRT
36098   if( !sqlite3_temp_directory ){
36099     sqlite3_log(SQLITE_ERROR,
36100         "sqlite3_temp_directory variable should be set for WinRT");
36101   }
36102 #endif
36103
36104   pFile->h = INVALID_HANDLE_VALUE;
36105
36106   /* If the second argument to this function is NULL, generate a
36107   ** temporary file name to use
36108   */
36109   if( !zUtf8Name ){
36110     assert(isDelete && !isOpenJournal);
36111     rc = getTempname(MAX_PATH+2, zTmpname);
36112     if( rc!=SQLITE_OK ){
36113       return rc;
36114     }
36115     zUtf8Name = zTmpname;
36116   }
36117
36118   /* Database filenames are double-zero terminated if they are not
36119   ** URIs with parameters.  Hence, they can always be passed into
36120   ** sqlite3_uri_parameter().
36121   */
36122   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
36123         zUtf8Name[strlen(zUtf8Name)+1]==0 );
36124
36125   /* Convert the filename to the system encoding. */
36126   zConverted = convertUtf8Filename(zUtf8Name);
36127   if( zConverted==0 ){
36128     return SQLITE_IOERR_NOMEM;
36129   }
36130
36131   if( winIsDir(zConverted) ){
36132     sqlite3_free(zConverted);
36133     return SQLITE_CANTOPEN_ISDIR;
36134   }
36135
36136   if( isReadWrite ){
36137     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
36138   }else{
36139     dwDesiredAccess = GENERIC_READ;
36140   }
36141
36142   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
36143   ** created. SQLite doesn't use it to indicate "exclusive access"
36144   ** as it is usually understood.
36145   */
36146   if( isExclusive ){
36147     /* Creates a new file, only if it does not already exist. */
36148     /* If the file exists, it fails. */
36149     dwCreationDisposition = CREATE_NEW;
36150   }else if( isCreate ){
36151     /* Open existing file, or create if it doesn't exist */
36152     dwCreationDisposition = OPEN_ALWAYS;
36153   }else{
36154     /* Opens a file, only if it exists. */
36155     dwCreationDisposition = OPEN_EXISTING;
36156   }
36157
36158   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
36159
36160   if( isDelete ){
36161 #if SQLITE_OS_WINCE
36162     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
36163     isTemp = 1;
36164 #else
36165     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
36166                                | FILE_ATTRIBUTE_HIDDEN
36167                                | FILE_FLAG_DELETE_ON_CLOSE;
36168 #endif
36169   }else{
36170     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
36171   }
36172   /* Reports from the internet are that performance is always
36173   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
36174 #if SQLITE_OS_WINCE
36175   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
36176 #endif
36177
36178   if( isNT() ){
36179 #if SQLITE_OS_WINRT
36180     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
36181     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
36182     extendedParameters.dwFileAttributes =
36183             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
36184     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
36185     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
36186     extendedParameters.lpSecurityAttributes = NULL;
36187     extendedParameters.hTemplateFile = NULL;
36188     while( (h = osCreateFile2((LPCWSTR)zConverted,
36189                               dwDesiredAccess,
36190                               dwShareMode,
36191                               dwCreationDisposition,
36192                               &extendedParameters))==INVALID_HANDLE_VALUE &&
36193                               retryIoerr(&cnt, &lastErrno) ){
36194                /* Noop */
36195     }
36196 #else
36197     while( (h = osCreateFileW((LPCWSTR)zConverted,
36198                               dwDesiredAccess,
36199                               dwShareMode, NULL,
36200                               dwCreationDisposition,
36201                               dwFlagsAndAttributes,
36202                               NULL))==INVALID_HANDLE_VALUE &&
36203                               retryIoerr(&cnt, &lastErrno) ){
36204                /* Noop */
36205     }
36206 #endif
36207   }
36208 #ifdef SQLITE_WIN32_HAS_ANSI
36209   else{
36210     while( (h = osCreateFileA((LPCSTR)zConverted,
36211                               dwDesiredAccess,
36212                               dwShareMode, NULL,
36213                               dwCreationDisposition,
36214                               dwFlagsAndAttributes,
36215                               NULL))==INVALID_HANDLE_VALUE &&
36216                               retryIoerr(&cnt, &lastErrno) ){
36217                /* Noop */
36218     }
36219   }
36220 #endif
36221   logIoerr(cnt);
36222
36223   OSTRACE(("OPEN %d %s 0x%lx %s\n",
36224            h, zName, dwDesiredAccess,
36225            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
36226
36227   if( h==INVALID_HANDLE_VALUE ){
36228     pFile->lastErrno = lastErrno;
36229     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
36230     sqlite3_free(zConverted);
36231     if( isReadWrite && !isExclusive ){
36232       return winOpen(pVfs, zName, id,
36233              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
36234     }else{
36235       return SQLITE_CANTOPEN_BKPT;
36236     }
36237   }
36238
36239   if( pOutFlags ){
36240     if( isReadWrite ){
36241       *pOutFlags = SQLITE_OPEN_READWRITE;
36242     }else{
36243       *pOutFlags = SQLITE_OPEN_READONLY;
36244     }
36245   }
36246
36247   memset(pFile, 0, sizeof(*pFile));
36248   pFile->pMethod = &winIoMethod;
36249   pFile->h = h;
36250   pFile->lastErrno = NO_ERROR;
36251   pFile->pVfs = pVfs;
36252 #ifndef SQLITE_OMIT_WAL
36253   pFile->pShm = 0;
36254 #endif
36255   pFile->zPath = zName;
36256   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
36257     pFile->ctrlFlags |= WINFILE_PSOW;
36258   }
36259
36260 #if SQLITE_OS_WINCE
36261   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
36262        && !winceCreateLock(zName, pFile)
36263   ){
36264     osCloseHandle(h);
36265     sqlite3_free(zConverted);
36266     return SQLITE_CANTOPEN_BKPT;
36267   }
36268   if( isTemp ){
36269     pFile->zDeleteOnClose = zConverted;
36270   }else
36271 #endif
36272   {
36273     sqlite3_free(zConverted);
36274   }
36275
36276   OpenCounter(+1);
36277   return rc;
36278 }
36279
36280 /*
36281 ** Delete the named file.
36282 **
36283 ** Note that Windows does not allow a file to be deleted if some other
36284 ** process has it open.  Sometimes a virus scanner or indexing program
36285 ** will open a journal file shortly after it is created in order to do
36286 ** whatever it does.  While this other process is holding the
36287 ** file open, we will be unable to delete it.  To work around this
36288 ** problem, we delay 100 milliseconds and try to delete again.  Up
36289 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
36290 ** up and returning an error.
36291 */
36292 static int winDelete(
36293   sqlite3_vfs *pVfs,          /* Not used on win32 */
36294   const char *zFilename,      /* Name of file to delete */
36295   int syncDir                 /* Not used on win32 */
36296 ){
36297   int cnt = 0;
36298   int rc;
36299   DWORD attr;
36300   DWORD lastErrno;
36301   void *zConverted;
36302   UNUSED_PARAMETER(pVfs);
36303   UNUSED_PARAMETER(syncDir);
36304
36305   SimulateIOError(return SQLITE_IOERR_DELETE);
36306   zConverted = convertUtf8Filename(zFilename);
36307   if( zConverted==0 ){
36308     return SQLITE_IOERR_NOMEM;
36309   }
36310   if( isNT() ){
36311     do {
36312 #if SQLITE_OS_WINRT
36313       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36314       memset(&sAttrData, 0, sizeof(sAttrData));
36315       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
36316                                   &sAttrData) ){
36317         attr = sAttrData.dwFileAttributes;
36318       }else{
36319         lastErrno = osGetLastError();
36320         if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
36321           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36322         }else{
36323           rc = SQLITE_ERROR;
36324         }
36325         break;
36326       }
36327 #else
36328       attr = osGetFileAttributesW(zConverted);
36329 #endif
36330       if ( attr==INVALID_FILE_ATTRIBUTES ){
36331         lastErrno = osGetLastError();
36332         if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
36333           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36334         }else{
36335           rc = SQLITE_ERROR;
36336         }
36337         break;
36338       }
36339       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
36340         rc = SQLITE_ERROR; /* Files only. */
36341         break;
36342       }
36343       if ( osDeleteFileW(zConverted) ){
36344         rc = SQLITE_OK; /* Deleted OK. */
36345         break;
36346       }
36347       if ( !retryIoerr(&cnt, &lastErrno) ){
36348         rc = SQLITE_ERROR; /* No more retries. */
36349         break;
36350       }
36351     } while(1);
36352   }
36353 #ifdef SQLITE_WIN32_HAS_ANSI
36354   else{
36355     do {
36356       attr = osGetFileAttributesA(zConverted);
36357       if ( attr==INVALID_FILE_ATTRIBUTES ){
36358         lastErrno = osGetLastError();
36359         if( lastErrno==ERROR_FILE_NOT_FOUND || lastErrno==ERROR_PATH_NOT_FOUND ){
36360           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36361         }else{
36362           rc = SQLITE_ERROR;
36363         }
36364         break;
36365       }
36366       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
36367         rc = SQLITE_ERROR; /* Files only. */
36368         break;
36369       }
36370       if ( osDeleteFileA(zConverted) ){
36371         rc = SQLITE_OK; /* Deleted OK. */
36372         break;
36373       }
36374       if ( !retryIoerr(&cnt, &lastErrno) ){
36375         rc = SQLITE_ERROR; /* No more retries. */
36376         break;
36377       }
36378     } while(1);
36379   }
36380 #endif
36381   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
36382     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
36383              "winDelete", zFilename);
36384   }else{
36385     logIoerr(cnt);
36386   }
36387   sqlite3_free(zConverted);
36388   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
36389   return rc;
36390 }
36391
36392 /*
36393 ** Check the existance and status of a file.
36394 */
36395 static int winAccess(
36396   sqlite3_vfs *pVfs,         /* Not used on win32 */
36397   const char *zFilename,     /* Name of file to check */
36398   int flags,                 /* Type of test to make on this file */
36399   int *pResOut               /* OUT: Result */
36400 ){
36401   DWORD attr;
36402   int rc = 0;
36403   DWORD lastErrno;
36404   void *zConverted;
36405   UNUSED_PARAMETER(pVfs);
36406
36407   SimulateIOError( return SQLITE_IOERR_ACCESS; );
36408   zConverted = convertUtf8Filename(zFilename);
36409   if( zConverted==0 ){
36410     return SQLITE_IOERR_NOMEM;
36411   }
36412   if( isNT() ){
36413     int cnt = 0;
36414     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36415     memset(&sAttrData, 0, sizeof(sAttrData));
36416     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
36417                              GetFileExInfoStandard,
36418                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
36419     if( rc ){
36420       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
36421       ** as if it does not exist.
36422       */
36423       if(    flags==SQLITE_ACCESS_EXISTS
36424           && sAttrData.nFileSizeHigh==0
36425           && sAttrData.nFileSizeLow==0 ){
36426         attr = INVALID_FILE_ATTRIBUTES;
36427       }else{
36428         attr = sAttrData.dwFileAttributes;
36429       }
36430     }else{
36431       logIoerr(cnt);
36432       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
36433         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
36434         sqlite3_free(zConverted);
36435         return SQLITE_IOERR_ACCESS;
36436       }else{
36437         attr = INVALID_FILE_ATTRIBUTES;
36438       }
36439     }
36440   }
36441 #ifdef SQLITE_WIN32_HAS_ANSI
36442   else{
36443     attr = osGetFileAttributesA((char*)zConverted);
36444   }
36445 #endif
36446   sqlite3_free(zConverted);
36447   switch( flags ){
36448     case SQLITE_ACCESS_READ:
36449     case SQLITE_ACCESS_EXISTS:
36450       rc = attr!=INVALID_FILE_ATTRIBUTES;
36451       break;
36452     case SQLITE_ACCESS_READWRITE:
36453       rc = attr!=INVALID_FILE_ATTRIBUTES &&
36454              (attr & FILE_ATTRIBUTE_READONLY)==0;
36455       break;
36456     default:
36457       assert(!"Invalid flags argument");
36458   }
36459   *pResOut = rc;
36460   return SQLITE_OK;
36461 }
36462
36463
36464 /*
36465 ** Returns non-zero if the specified path name should be used verbatim.  If
36466 ** non-zero is returned from this function, the calling function must simply
36467 ** use the provided path name verbatim -OR- resolve it into a full path name
36468 ** using the GetFullPathName Win32 API function (if available).
36469 */
36470 static BOOL winIsVerbatimPathname(
36471   const char *zPathname
36472 ){
36473   /*
36474   ** If the path name starts with a forward slash or a backslash, it is either
36475   ** a legal UNC name, a volume relative path, or an absolute path name in the
36476   ** "Unix" format on Windows.  There is no easy way to differentiate between
36477   ** the final two cases; therefore, we return the safer return value of TRUE
36478   ** so that callers of this function will simply use it verbatim.
36479   */
36480   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
36481     return TRUE;
36482   }
36483
36484   /*
36485   ** If the path name starts with a letter and a colon it is either a volume
36486   ** relative path or an absolute path.  Callers of this function must not
36487   ** attempt to treat it as a relative path name (i.e. they should simply use
36488   ** it verbatim).
36489   */
36490   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
36491     return TRUE;
36492   }
36493
36494   /*
36495   ** If we get to this point, the path name should almost certainly be a purely
36496   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
36497   */
36498   return FALSE;
36499 }
36500
36501 /*
36502 ** Turn a relative pathname into a full pathname.  Write the full
36503 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
36504 ** bytes in size.
36505 */
36506 static int winFullPathname(
36507   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
36508   const char *zRelative,        /* Possibly relative input path */
36509   int nFull,                    /* Size of output buffer in bytes */
36510   char *zFull                   /* Output buffer */
36511 ){
36512
36513 #if defined(__CYGWIN__)
36514   SimulateIOError( return SQLITE_ERROR );
36515   UNUSED_PARAMETER(nFull);
36516   assert( pVfs->mxPathname>=MAX_PATH );
36517   assert( nFull>=pVfs->mxPathname );
36518   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36519     /*
36520     ** NOTE: We are dealing with a relative path name and the data
36521     **       directory has been set.  Therefore, use it as the basis
36522     **       for converting the relative path name to an absolute
36523     **       one by prepending the data directory and a slash.
36524     */
36525     char zOut[MAX_PATH+1];
36526     memset(zOut, 0, MAX_PATH+1);
36527     cygwin_conv_to_win32_path(zRelative, zOut); /* POSIX to Win32 */
36528     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
36529                      sqlite3_data_directory, zOut);
36530   }else{
36531     /*
36532     ** NOTE: The Cygwin docs state that the maximum length needed
36533     **       for the buffer passed to cygwin_conv_to_full_win32_path
36534     **       is MAX_PATH.
36535     */
36536     cygwin_conv_to_full_win32_path(zRelative, zFull);
36537   }
36538   return SQLITE_OK;
36539 #endif
36540
36541 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
36542   SimulateIOError( return SQLITE_ERROR );
36543   /* WinCE has no concept of a relative pathname, or so I am told. */
36544   /* WinRT has no way to convert a relative path to an absolute one. */
36545   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36546     /*
36547     ** NOTE: We are dealing with a relative path name and the data
36548     **       directory has been set.  Therefore, use it as the basis
36549     **       for converting the relative path name to an absolute
36550     **       one by prepending the data directory and a backslash.
36551     */
36552     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
36553                      sqlite3_data_directory, zRelative);
36554   }else{
36555     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
36556   }
36557   return SQLITE_OK;
36558 #endif
36559
36560 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
36561   DWORD nByte;
36562   void *zConverted;
36563   char *zOut;
36564
36565   /* If this path name begins with "/X:", where "X" is any alphabetic
36566   ** character, discard the initial "/" from the pathname.
36567   */
36568   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
36569     zRelative++;
36570   }
36571
36572   /* It's odd to simulate an io-error here, but really this is just
36573   ** using the io-error infrastructure to test that SQLite handles this
36574   ** function failing. This function could fail if, for example, the
36575   ** current working directory has been unlinked.
36576   */
36577   SimulateIOError( return SQLITE_ERROR );
36578   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36579     /*
36580     ** NOTE: We are dealing with a relative path name and the data
36581     **       directory has been set.  Therefore, use it as the basis
36582     **       for converting the relative path name to an absolute
36583     **       one by prepending the data directory and a backslash.
36584     */
36585     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
36586                      sqlite3_data_directory, zRelative);
36587     return SQLITE_OK;
36588   }
36589   zConverted = convertUtf8Filename(zRelative);
36590   if( zConverted==0 ){
36591     return SQLITE_IOERR_NOMEM;
36592   }
36593   if( isNT() ){
36594     LPWSTR zTemp;
36595     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
36596     if( nByte==0 ){
36597       winLogError(SQLITE_ERROR, osGetLastError(),
36598                   "GetFullPathNameW1", zConverted);
36599       sqlite3_free(zConverted);
36600       return SQLITE_CANTOPEN_FULLPATH;
36601     }
36602     nByte += 3;
36603     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36604     if( zTemp==0 ){
36605       sqlite3_free(zConverted);
36606       return SQLITE_IOERR_NOMEM;
36607     }
36608     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
36609     if( nByte==0 ){
36610       winLogError(SQLITE_ERROR, osGetLastError(),
36611                   "GetFullPathNameW2", zConverted);
36612       sqlite3_free(zConverted);
36613       sqlite3_free(zTemp);
36614       return SQLITE_CANTOPEN_FULLPATH;
36615     }
36616     sqlite3_free(zConverted);
36617     zOut = unicodeToUtf8(zTemp);
36618     sqlite3_free(zTemp);
36619   }
36620 #ifdef SQLITE_WIN32_HAS_ANSI
36621   else{
36622     char *zTemp;
36623     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
36624     if( nByte==0 ){
36625       winLogError(SQLITE_ERROR, osGetLastError(),
36626                   "GetFullPathNameA1", zConverted);
36627       sqlite3_free(zConverted);
36628       return SQLITE_CANTOPEN_FULLPATH;
36629     }
36630     nByte += 3;
36631     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36632     if( zTemp==0 ){
36633       sqlite3_free(zConverted);
36634       return SQLITE_IOERR_NOMEM;
36635     }
36636     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
36637     if( nByte==0 ){
36638       winLogError(SQLITE_ERROR, osGetLastError(),
36639                   "GetFullPathNameA2", zConverted);
36640       sqlite3_free(zConverted);
36641       sqlite3_free(zTemp);
36642       return SQLITE_CANTOPEN_FULLPATH;
36643     }
36644     sqlite3_free(zConverted);
36645     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
36646     sqlite3_free(zTemp);
36647   }
36648 #endif
36649   if( zOut ){
36650     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
36651     sqlite3_free(zOut);
36652     return SQLITE_OK;
36653   }else{
36654     return SQLITE_IOERR_NOMEM;
36655   }
36656 #endif
36657 }
36658
36659 #ifndef SQLITE_OMIT_LOAD_EXTENSION
36660 /*
36661 ** Interfaces for opening a shared library, finding entry points
36662 ** within the shared library, and closing the shared library.
36663 */
36664 /*
36665 ** Interfaces for opening a shared library, finding entry points
36666 ** within the shared library, and closing the shared library.
36667 */
36668 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
36669   HANDLE h;
36670   void *zConverted = convertUtf8Filename(zFilename);
36671   UNUSED_PARAMETER(pVfs);
36672   if( zConverted==0 ){
36673     return 0;
36674   }
36675   if( isNT() ){
36676 #if SQLITE_OS_WINRT
36677     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
36678 #else
36679     h = osLoadLibraryW((LPCWSTR)zConverted);
36680 #endif
36681   }
36682 #ifdef SQLITE_WIN32_HAS_ANSI
36683   else{
36684     h = osLoadLibraryA((char*)zConverted);
36685   }
36686 #endif
36687   sqlite3_free(zConverted);
36688   return (void*)h;
36689 }
36690 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
36691   UNUSED_PARAMETER(pVfs);
36692   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
36693 }
36694 static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
36695   UNUSED_PARAMETER(pVfs);
36696   return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
36697 }
36698 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
36699   UNUSED_PARAMETER(pVfs);
36700   osFreeLibrary((HANDLE)pHandle);
36701 }
36702 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36703   #define winDlOpen  0
36704   #define winDlError 0
36705   #define winDlSym   0
36706   #define winDlClose 0
36707 #endif
36708
36709
36710 /*
36711 ** Write up to nBuf bytes of randomness into zBuf.
36712 */
36713 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36714   int n = 0;
36715   UNUSED_PARAMETER(pVfs);
36716 #if defined(SQLITE_TEST)
36717   n = nBuf;
36718   memset(zBuf, 0, nBuf);
36719 #else
36720   if( sizeof(SYSTEMTIME)<=nBuf-n ){
36721     SYSTEMTIME x;
36722     osGetSystemTime(&x);
36723     memcpy(&zBuf[n], &x, sizeof(x));
36724     n += sizeof(x);
36725   }
36726   if( sizeof(DWORD)<=nBuf-n ){
36727     DWORD pid = osGetCurrentProcessId();
36728     memcpy(&zBuf[n], &pid, sizeof(pid));
36729     n += sizeof(pid);
36730   }
36731 #if SQLITE_OS_WINRT
36732   if( sizeof(ULONGLONG)<=nBuf-n ){
36733     ULONGLONG cnt = osGetTickCount64();
36734     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36735     n += sizeof(cnt);
36736   }
36737 #else
36738   if( sizeof(DWORD)<=nBuf-n ){
36739     DWORD cnt = osGetTickCount();
36740     memcpy(&zBuf[n], &cnt, sizeof(cnt));
36741     n += sizeof(cnt);
36742   }
36743 #endif
36744   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
36745     LARGE_INTEGER i;
36746     osQueryPerformanceCounter(&i);
36747     memcpy(&zBuf[n], &i, sizeof(i));
36748     n += sizeof(i);
36749   }
36750 #endif
36751   return n;
36752 }
36753
36754
36755 /*
36756 ** Sleep for a little while.  Return the amount of time slept.
36757 */
36758 static int winSleep(sqlite3_vfs *pVfs, int microsec){
36759   sqlite3_win32_sleep((microsec+999)/1000);
36760   UNUSED_PARAMETER(pVfs);
36761   return ((microsec+999)/1000)*1000;
36762 }
36763
36764 /*
36765 ** The following variable, if set to a non-zero value, is interpreted as
36766 ** the number of seconds since 1970 and is used to set the result of
36767 ** sqlite3OsCurrentTime() during testing.
36768 */
36769 #ifdef SQLITE_TEST
36770 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
36771 #endif
36772
36773 /*
36774 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
36775 ** the current time and date as a Julian Day number times 86_400_000.  In
36776 ** other words, write into *piNow the number of milliseconds since the Julian
36777 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36778 ** proleptic Gregorian calendar.
36779 **
36780 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
36781 ** cannot be found.
36782 */
36783 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
36784   /* FILETIME structure is a 64-bit value representing the number of
36785      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
36786   */
36787   FILETIME ft;
36788   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
36789 #ifdef SQLITE_TEST
36790   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36791 #endif
36792   /* 2^32 - to avoid use of LL and warnings in gcc */
36793   static const sqlite3_int64 max32BitValue =
36794       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
36795
36796 #if SQLITE_OS_WINCE
36797   SYSTEMTIME time;
36798   osGetSystemTime(&time);
36799   /* if SystemTimeToFileTime() fails, it returns zero. */
36800   if (!osSystemTimeToFileTime(&time,&ft)){
36801     return SQLITE_ERROR;
36802   }
36803 #else
36804   osGetSystemTimeAsFileTime( &ft );
36805 #endif
36806
36807   *piNow = winFiletimeEpoch +
36808             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
36809                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
36810
36811 #ifdef SQLITE_TEST
36812   if( sqlite3_current_time ){
36813     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36814   }
36815 #endif
36816   UNUSED_PARAMETER(pVfs);
36817   return SQLITE_OK;
36818 }
36819
36820 /*
36821 ** Find the current time (in Universal Coordinated Time).  Write the
36822 ** current time and date as a Julian Day number into *prNow and
36823 ** return 0.  Return 1 if the time and date cannot be found.
36824 */
36825 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
36826   int rc;
36827   sqlite3_int64 i;
36828   rc = winCurrentTimeInt64(pVfs, &i);
36829   if( !rc ){
36830     *prNow = i/86400000.0;
36831   }
36832   return rc;
36833 }
36834
36835 /*
36836 ** The idea is that this function works like a combination of
36837 ** GetLastError() and FormatMessage() on Windows (or errno and
36838 ** strerror_r() on Unix). After an error is returned by an OS
36839 ** function, SQLite calls this function with zBuf pointing to
36840 ** a buffer of nBuf bytes. The OS layer should populate the
36841 ** buffer with a nul-terminated UTF-8 encoded error message
36842 ** describing the last IO error to have occurred within the calling
36843 ** thread.
36844 **
36845 ** If the error message is too large for the supplied buffer,
36846 ** it should be truncated. The return value of xGetLastError
36847 ** is zero if the error message fits in the buffer, or non-zero
36848 ** otherwise (if the message was truncated). If non-zero is returned,
36849 ** then it is not necessary to include the nul-terminator character
36850 ** in the output buffer.
36851 **
36852 ** Not supplying an error message will have no adverse effect
36853 ** on SQLite. It is fine to have an implementation that never
36854 ** returns an error message:
36855 **
36856 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36857 **     assert(zBuf[0]=='\0');
36858 **     return 0;
36859 **   }
36860 **
36861 ** However if an error message is supplied, it will be incorporated
36862 ** by sqlite into the error message available to the user using
36863 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
36864 */
36865 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36866   UNUSED_PARAMETER(pVfs);
36867   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
36868 }
36869
36870 /*
36871 ** Initialize and deinitialize the operating system interface.
36872 */
36873 SQLITE_API int sqlite3_os_init(void){
36874   static sqlite3_vfs winVfs = {
36875     3,                   /* iVersion */
36876     sizeof(winFile),     /* szOsFile */
36877     MAX_PATH,            /* mxPathname */
36878     0,                   /* pNext */
36879     "win32",             /* zName */
36880     0,                   /* pAppData */
36881     winOpen,             /* xOpen */
36882     winDelete,           /* xDelete */
36883     winAccess,           /* xAccess */
36884     winFullPathname,     /* xFullPathname */
36885     winDlOpen,           /* xDlOpen */
36886     winDlError,          /* xDlError */
36887     winDlSym,            /* xDlSym */
36888     winDlClose,          /* xDlClose */
36889     winRandomness,       /* xRandomness */
36890     winSleep,            /* xSleep */
36891     winCurrentTime,      /* xCurrentTime */
36892     winGetLastError,     /* xGetLastError */
36893     winCurrentTimeInt64, /* xCurrentTimeInt64 */
36894     winSetSystemCall,    /* xSetSystemCall */
36895     winGetSystemCall,    /* xGetSystemCall */
36896     winNextSystemCall,   /* xNextSystemCall */
36897   };
36898
36899   /* Double-check that the aSyscall[] array has been constructed
36900   ** correctly.  See ticket [bb3a86e890c8e96ab] */
36901   assert( ArraySize(aSyscall)==74 );
36902
36903 #ifndef SQLITE_OMIT_WAL
36904   /* get memory map allocation granularity */
36905   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
36906 #if SQLITE_OS_WINRT
36907   osGetNativeSystemInfo(&winSysInfo);
36908 #else
36909   osGetSystemInfo(&winSysInfo);
36910 #endif
36911   assert(winSysInfo.dwAllocationGranularity > 0);
36912 #endif
36913
36914   sqlite3_vfs_register(&winVfs, 1);
36915   return SQLITE_OK;
36916 }
36917
36918 SQLITE_API int sqlite3_os_end(void){
36919 #if SQLITE_OS_WINRT
36920   if( sleepObj!=NULL ){
36921     osCloseHandle(sleepObj);
36922     sleepObj = NULL;
36923   }
36924 #endif
36925   return SQLITE_OK;
36926 }
36927
36928 #endif /* SQLITE_OS_WIN */
36929
36930 /************** End of os_win.c **********************************************/
36931 /************** Begin file bitvec.c ******************************************/
36932 /*
36933 ** 2008 February 16
36934 **
36935 ** The author disclaims copyright to this source code.  In place of
36936 ** a legal notice, here is a blessing:
36937 **
36938 **    May you do good and not evil.
36939 **    May you find forgiveness for yourself and forgive others.
36940 **    May you share freely, never taking more than you give.
36941 **
36942 *************************************************************************
36943 ** This file implements an object that represents a fixed-length
36944 ** bitmap.  Bits are numbered starting with 1.
36945 **
36946 ** A bitmap is used to record which pages of a database file have been
36947 ** journalled during a transaction, or which pages have the "dont-write"
36948 ** property.  Usually only a few pages are meet either condition.
36949 ** So the bitmap is usually sparse and has low cardinality.
36950 ** But sometimes (for example when during a DROP of a large table) most
36951 ** or all of the pages in a database can get journalled.  In those cases,
36952 ** the bitmap becomes dense with high cardinality.  The algorithm needs
36953 ** to handle both cases well.
36954 **
36955 ** The size of the bitmap is fixed when the object is created.
36956 **
36957 ** All bits are clear when the bitmap is created.  Individual bits
36958 ** may be set or cleared one at a time.
36959 **
36960 ** Test operations are about 100 times more common that set operations.
36961 ** Clear operations are exceedingly rare.  There are usually between
36962 ** 5 and 500 set operations per Bitvec object, though the number of sets can
36963 ** sometimes grow into tens of thousands or larger.  The size of the
36964 ** Bitvec object is the number of pages in the database file at the
36965 ** start of a transaction, and is thus usually less than a few thousand,
36966 ** but can be as large as 2 billion for a really big database.
36967 */
36968
36969 /* Size of the Bitvec structure in bytes. */
36970 #define BITVEC_SZ        512
36971
36972 /* Round the union size down to the nearest pointer boundary, since that's how
36973 ** it will be aligned within the Bitvec struct. */
36974 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
36975
36976 /* Type of the array "element" for the bitmap representation.
36977 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
36978 ** Setting this to the "natural word" size of your CPU may improve
36979 ** performance. */
36980 #define BITVEC_TELEM     u8
36981 /* Size, in bits, of the bitmap element. */
36982 #define BITVEC_SZELEM    8
36983 /* Number of elements in a bitmap array. */
36984 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
36985 /* Number of bits in the bitmap array. */
36986 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
36987
36988 /* Number of u32 values in hash table. */
36989 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
36990 /* Maximum number of entries in hash table before
36991 ** sub-dividing and re-hashing. */
36992 #define BITVEC_MXHASH    (BITVEC_NINT/2)
36993 /* Hashing function for the aHash representation.
36994 ** Empirical testing showed that the *37 multiplier
36995 ** (an arbitrary prime)in the hash function provided
36996 ** no fewer collisions than the no-op *1. */
36997 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
36998
36999 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
37000
37001
37002 /*
37003 ** A bitmap is an instance of the following structure.
37004 **
37005 ** This bitmap records the existance of zero or more bits
37006 ** with values between 1 and iSize, inclusive.
37007 **
37008 ** There are three possible representations of the bitmap.
37009 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
37010 ** bitmap.  The least significant bit is bit 1.
37011 **
37012 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
37013 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
37014 **
37015 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
37016 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
37017 ** handles up to iDivisor separate values of i.  apSub[0] holds
37018 ** values between 1 and iDivisor.  apSub[1] holds values between
37019 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
37020 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
37021 ** to hold deal with values between 1 and iDivisor.
37022 */
37023 struct Bitvec {
37024   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
37025   u32 nSet;       /* Number of bits that are set - only valid for aHash
37026                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
37027                   ** this would be 125. */
37028   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
37029                   /* Should >=0 for apSub element. */
37030                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
37031                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
37032   union {
37033     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
37034     u32 aHash[BITVEC_NINT];      /* Hash table representation */
37035     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
37036   } u;
37037 };
37038
37039 /*
37040 ** Create a new bitmap object able to handle bits between 0 and iSize,
37041 ** inclusive.  Return a pointer to the new object.  Return NULL if
37042 ** malloc fails.
37043 */
37044 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
37045   Bitvec *p;
37046   assert( sizeof(*p)==BITVEC_SZ );
37047   p = sqlite3MallocZero( sizeof(*p) );
37048   if( p ){
37049     p->iSize = iSize;
37050   }
37051   return p;
37052 }
37053
37054 /*
37055 ** Check to see if the i-th bit is set.  Return true or false.
37056 ** If p is NULL (if the bitmap has not been created) or if
37057 ** i is out of range, then return false.
37058 */
37059 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
37060   if( p==0 ) return 0;
37061   if( i>p->iSize || i==0 ) return 0;
37062   i--;
37063   while( p->iDivisor ){
37064     u32 bin = i/p->iDivisor;
37065     i = i%p->iDivisor;
37066     p = p->u.apSub[bin];
37067     if (!p) {
37068       return 0;
37069     }
37070   }
37071   if( p->iSize<=BITVEC_NBIT ){
37072     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
37073   } else{
37074     u32 h = BITVEC_HASH(i++);
37075     while( p->u.aHash[h] ){
37076       if( p->u.aHash[h]==i ) return 1;
37077       h = (h+1) % BITVEC_NINT;
37078     }
37079     return 0;
37080   }
37081 }
37082
37083 /*
37084 ** Set the i-th bit.  Return 0 on success and an error code if
37085 ** anything goes wrong.
37086 **
37087 ** This routine might cause sub-bitmaps to be allocated.  Failing
37088 ** to get the memory needed to hold the sub-bitmap is the only
37089 ** that can go wrong with an insert, assuming p and i are valid.
37090 **
37091 ** The calling function must ensure that p is a valid Bitvec object
37092 ** and that the value for "i" is within range of the Bitvec object.
37093 ** Otherwise the behavior is undefined.
37094 */
37095 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
37096   u32 h;
37097   if( p==0 ) return SQLITE_OK;
37098   assert( i>0 );
37099   assert( i<=p->iSize );
37100   i--;
37101   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
37102     u32 bin = i/p->iDivisor;
37103     i = i%p->iDivisor;
37104     if( p->u.apSub[bin]==0 ){
37105       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
37106       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
37107     }
37108     p = p->u.apSub[bin];
37109   }
37110   if( p->iSize<=BITVEC_NBIT ){
37111     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
37112     return SQLITE_OK;
37113   }
37114   h = BITVEC_HASH(i++);
37115   /* if there wasn't a hash collision, and this doesn't */
37116   /* completely fill the hash, then just add it without */
37117   /* worring about sub-dividing and re-hashing. */
37118   if( !p->u.aHash[h] ){
37119     if (p->nSet<(BITVEC_NINT-1)) {
37120       goto bitvec_set_end;
37121     } else {
37122       goto bitvec_set_rehash;
37123     }
37124   }
37125   /* there was a collision, check to see if it's already */
37126   /* in hash, if not, try to find a spot for it */
37127   do {
37128     if( p->u.aHash[h]==i ) return SQLITE_OK;
37129     h++;
37130     if( h>=BITVEC_NINT ) h = 0;
37131   } while( p->u.aHash[h] );
37132   /* we didn't find it in the hash.  h points to the first */
37133   /* available free spot. check to see if this is going to */
37134   /* make our hash too "full".  */
37135 bitvec_set_rehash:
37136   if( p->nSet>=BITVEC_MXHASH ){
37137     unsigned int j;
37138     int rc;
37139     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
37140     if( aiValues==0 ){
37141       return SQLITE_NOMEM;
37142     }else{
37143       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37144       memset(p->u.apSub, 0, sizeof(p->u.apSub));
37145       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
37146       rc = sqlite3BitvecSet(p, i);
37147       for(j=0; j<BITVEC_NINT; j++){
37148         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
37149       }
37150       sqlite3StackFree(0, aiValues);
37151       return rc;
37152     }
37153   }
37154 bitvec_set_end:
37155   p->nSet++;
37156   p->u.aHash[h] = i;
37157   return SQLITE_OK;
37158 }
37159
37160 /*
37161 ** Clear the i-th bit.
37162 **
37163 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
37164 ** that BitvecClear can use to rebuilt its hash table.
37165 */
37166 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
37167   if( p==0 ) return;
37168   assert( i>0 );
37169   i--;
37170   while( p->iDivisor ){
37171     u32 bin = i/p->iDivisor;
37172     i = i%p->iDivisor;
37173     p = p->u.apSub[bin];
37174     if (!p) {
37175       return;
37176     }
37177   }
37178   if( p->iSize<=BITVEC_NBIT ){
37179     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
37180   }else{
37181     unsigned int j;
37182     u32 *aiValues = pBuf;
37183     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37184     memset(p->u.aHash, 0, sizeof(p->u.aHash));
37185     p->nSet = 0;
37186     for(j=0; j<BITVEC_NINT; j++){
37187       if( aiValues[j] && aiValues[j]!=(i+1) ){
37188         u32 h = BITVEC_HASH(aiValues[j]-1);
37189         p->nSet++;
37190         while( p->u.aHash[h] ){
37191           h++;
37192           if( h>=BITVEC_NINT ) h = 0;
37193         }
37194         p->u.aHash[h] = aiValues[j];
37195       }
37196     }
37197   }
37198 }
37199
37200 /*
37201 ** Destroy a bitmap object.  Reclaim all memory used.
37202 */
37203 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
37204   if( p==0 ) return;
37205   if( p->iDivisor ){
37206     unsigned int i;
37207     for(i=0; i<BITVEC_NPTR; i++){
37208       sqlite3BitvecDestroy(p->u.apSub[i]);
37209     }
37210   }
37211   sqlite3_free(p);
37212 }
37213
37214 /*
37215 ** Return the value of the iSize parameter specified when Bitvec *p
37216 ** was created.
37217 */
37218 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
37219   return p->iSize;
37220 }
37221
37222 #ifndef SQLITE_OMIT_BUILTIN_TEST
37223 /*
37224 ** Let V[] be an array of unsigned characters sufficient to hold
37225 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
37226 ** Then the following macros can be used to set, clear, or test
37227 ** individual bits within V.
37228 */
37229 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
37230 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
37231 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
37232
37233 /*
37234 ** This routine runs an extensive test of the Bitvec code.
37235 **
37236 ** The input is an array of integers that acts as a program
37237 ** to test the Bitvec.  The integers are opcodes followed
37238 ** by 0, 1, or 3 operands, depending on the opcode.  Another
37239 ** opcode follows immediately after the last operand.
37240 **
37241 ** There are 6 opcodes numbered from 0 through 5.  0 is the
37242 ** "halt" opcode and causes the test to end.
37243 **
37244 **    0          Halt and return the number of errors
37245 **    1 N S X    Set N bits beginning with S and incrementing by X
37246 **    2 N S X    Clear N bits beginning with S and incrementing by X
37247 **    3 N        Set N randomly chosen bits
37248 **    4 N        Clear N randomly chosen bits
37249 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
37250 **
37251 ** The opcodes 1 through 4 perform set and clear operations are performed
37252 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
37253 ** Opcode 5 works on the linear array only, not on the Bitvec.
37254 ** Opcode 5 is used to deliberately induce a fault in order to
37255 ** confirm that error detection works.
37256 **
37257 ** At the conclusion of the test the linear array is compared
37258 ** against the Bitvec object.  If there are any differences,
37259 ** an error is returned.  If they are the same, zero is returned.
37260 **
37261 ** If a memory allocation error occurs, return -1.
37262 */
37263 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
37264   Bitvec *pBitvec = 0;
37265   unsigned char *pV = 0;
37266   int rc = -1;
37267   int i, nx, pc, op;
37268   void *pTmpSpace;
37269
37270   /* Allocate the Bitvec to be tested and a linear array of
37271   ** bits to act as the reference */
37272   pBitvec = sqlite3BitvecCreate( sz );
37273   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
37274   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
37275   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
37276
37277   /* NULL pBitvec tests */
37278   sqlite3BitvecSet(0, 1);
37279   sqlite3BitvecClear(0, 1, pTmpSpace);
37280
37281   /* Run the program */
37282   pc = 0;
37283   while( (op = aOp[pc])!=0 ){
37284     switch( op ){
37285       case 1:
37286       case 2:
37287       case 5: {
37288         nx = 4;
37289         i = aOp[pc+2] - 1;
37290         aOp[pc+2] += aOp[pc+3];
37291         break;
37292       }
37293       case 3:
37294       case 4:
37295       default: {
37296         nx = 2;
37297         sqlite3_randomness(sizeof(i), &i);
37298         break;
37299       }
37300     }
37301     if( (--aOp[pc+1]) > 0 ) nx = 0;
37302     pc += nx;
37303     i = (i & 0x7fffffff)%sz;
37304     if( (op & 1)!=0 ){
37305       SETBIT(pV, (i+1));
37306       if( op!=5 ){
37307         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
37308       }
37309     }else{
37310       CLEARBIT(pV, (i+1));
37311       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
37312     }
37313   }
37314
37315   /* Test to make sure the linear array exactly matches the
37316   ** Bitvec object.  Start with the assumption that they do
37317   ** match (rc==0).  Change rc to non-zero if a discrepancy
37318   ** is found.
37319   */
37320   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
37321           + sqlite3BitvecTest(pBitvec, 0)
37322           + (sqlite3BitvecSize(pBitvec) - sz);
37323   for(i=1; i<=sz; i++){
37324     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
37325       rc = i;
37326       break;
37327     }
37328   }
37329
37330   /* Free allocated structure */
37331 bitvec_end:
37332   sqlite3_free(pTmpSpace);
37333   sqlite3_free(pV);
37334   sqlite3BitvecDestroy(pBitvec);
37335   return rc;
37336 }
37337 #endif /* SQLITE_OMIT_BUILTIN_TEST */
37338
37339 /************** End of bitvec.c **********************************************/
37340 /************** Begin file pcache.c ******************************************/
37341 /*
37342 ** 2008 August 05
37343 **
37344 ** The author disclaims copyright to this source code.  In place of
37345 ** a legal notice, here is a blessing:
37346 **
37347 **    May you do good and not evil.
37348 **    May you find forgiveness for yourself and forgive others.
37349 **    May you share freely, never taking more than you give.
37350 **
37351 *************************************************************************
37352 ** This file implements that page cache.
37353 */
37354
37355 /*
37356 ** A complete page cache is an instance of this structure.
37357 */
37358 struct PCache {
37359   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
37360   PgHdr *pSynced;                     /* Last synced page in dirty page list */
37361   int nRef;                           /* Number of referenced pages */
37362   int szCache;                        /* Configured cache size */
37363   int szPage;                         /* Size of every page in this cache */
37364   int szExtra;                        /* Size of extra space for each page */
37365   int bPurgeable;                     /* True if pages are on backing store */
37366   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
37367   void *pStress;                      /* Argument to xStress */
37368   sqlite3_pcache *pCache;             /* Pluggable cache module */
37369   PgHdr *pPage1;                      /* Reference to page 1 */
37370 };
37371
37372 /*
37373 ** Some of the assert() macros in this code are too expensive to run
37374 ** even during normal debugging.  Use them only rarely on long-running
37375 ** tests.  Enable the expensive asserts using the
37376 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
37377 */
37378 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
37379 # define expensive_assert(X)  assert(X)
37380 #else
37381 # define expensive_assert(X)
37382 #endif
37383
37384 /********************************** Linked List Management ********************/
37385
37386 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
37387 /*
37388 ** Check that the pCache->pSynced variable is set correctly. If it
37389 ** is not, either fail an assert or return zero. Otherwise, return
37390 ** non-zero. This is only used in debugging builds, as follows:
37391 **
37392 **   expensive_assert( pcacheCheckSynced(pCache) );
37393 */
37394 static int pcacheCheckSynced(PCache *pCache){
37395   PgHdr *p;
37396   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
37397     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
37398   }
37399   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
37400 }
37401 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
37402
37403 /*
37404 ** Remove page pPage from the list of dirty pages.
37405 */
37406 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
37407   PCache *p = pPage->pCache;
37408
37409   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
37410   assert( pPage->pDirtyPrev || pPage==p->pDirty );
37411
37412   /* Update the PCache1.pSynced variable if necessary. */
37413   if( p->pSynced==pPage ){
37414     PgHdr *pSynced = pPage->pDirtyPrev;
37415     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
37416       pSynced = pSynced->pDirtyPrev;
37417     }
37418     p->pSynced = pSynced;
37419   }
37420
37421   if( pPage->pDirtyNext ){
37422     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
37423   }else{
37424     assert( pPage==p->pDirtyTail );
37425     p->pDirtyTail = pPage->pDirtyPrev;
37426   }
37427   if( pPage->pDirtyPrev ){
37428     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
37429   }else{
37430     assert( pPage==p->pDirty );
37431     p->pDirty = pPage->pDirtyNext;
37432   }
37433   pPage->pDirtyNext = 0;
37434   pPage->pDirtyPrev = 0;
37435
37436   expensive_assert( pcacheCheckSynced(p) );
37437 }
37438
37439 /*
37440 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
37441 ** pPage).
37442 */
37443 static void pcacheAddToDirtyList(PgHdr *pPage){
37444   PCache *p = pPage->pCache;
37445
37446   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
37447
37448   pPage->pDirtyNext = p->pDirty;
37449   if( pPage->pDirtyNext ){
37450     assert( pPage->pDirtyNext->pDirtyPrev==0 );
37451     pPage->pDirtyNext->pDirtyPrev = pPage;
37452   }
37453   p->pDirty = pPage;
37454   if( !p->pDirtyTail ){
37455     p->pDirtyTail = pPage;
37456   }
37457   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
37458     p->pSynced = pPage;
37459   }
37460   expensive_assert( pcacheCheckSynced(p) );
37461 }
37462
37463 /*
37464 ** Wrapper around the pluggable caches xUnpin method. If the cache is
37465 ** being used for an in-memory database, this function is a no-op.
37466 */
37467 static void pcacheUnpin(PgHdr *p){
37468   PCache *pCache = p->pCache;
37469   if( pCache->bPurgeable ){
37470     if( p->pgno==1 ){
37471       pCache->pPage1 = 0;
37472     }
37473     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
37474   }
37475 }
37476
37477 /*************************************************** General Interfaces ******
37478 **
37479 ** Initialize and shutdown the page cache subsystem. Neither of these
37480 ** functions are threadsafe.
37481 */
37482 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
37483   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
37484     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
37485     ** built-in default page cache is used instead of the application defined
37486     ** page cache. */
37487     sqlite3PCacheSetDefault();
37488   }
37489   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
37490 }
37491 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
37492   if( sqlite3GlobalConfig.pcache2.xShutdown ){
37493     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
37494     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
37495   }
37496 }
37497
37498 /*
37499 ** Return the size in bytes of a PCache object.
37500 */
37501 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
37502
37503 /*
37504 ** Create a new PCache object. Storage space to hold the object
37505 ** has already been allocated and is passed in as the p pointer.
37506 ** The caller discovers how much space needs to be allocated by
37507 ** calling sqlite3PcacheSize().
37508 */
37509 SQLITE_PRIVATE void sqlite3PcacheOpen(
37510   int szPage,                  /* Size of every page */
37511   int szExtra,                 /* Extra space associated with each page */
37512   int bPurgeable,              /* True if pages are on backing store */
37513   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
37514   void *pStress,               /* Argument to xStress */
37515   PCache *p                    /* Preallocated space for the PCache */
37516 ){
37517   memset(p, 0, sizeof(PCache));
37518   p->szPage = szPage;
37519   p->szExtra = szExtra;
37520   p->bPurgeable = bPurgeable;
37521   p->xStress = xStress;
37522   p->pStress = pStress;
37523   p->szCache = 100;
37524 }
37525
37526 /*
37527 ** Change the page size for PCache object. The caller must ensure that there
37528 ** are no outstanding page references when this function is called.
37529 */
37530 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
37531   assert( pCache->nRef==0 && pCache->pDirty==0 );
37532   if( pCache->pCache ){
37533     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37534     pCache->pCache = 0;
37535     pCache->pPage1 = 0;
37536   }
37537   pCache->szPage = szPage;
37538 }
37539
37540 /*
37541 ** Compute the number of pages of cache requested.
37542 */
37543 static int numberOfCachePages(PCache *p){
37544   if( p->szCache>=0 ){
37545     return p->szCache;
37546   }else{
37547     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
37548   }
37549 }
37550
37551 /*
37552 ** Try to obtain a page from the cache.
37553 */
37554 SQLITE_PRIVATE int sqlite3PcacheFetch(
37555   PCache *pCache,       /* Obtain the page from this cache */
37556   Pgno pgno,            /* Page number to obtain */
37557   int createFlag,       /* If true, create page if it does not exist already */
37558   PgHdr **ppPage        /* Write the page here */
37559 ){
37560   sqlite3_pcache_page *pPage = 0;
37561   PgHdr *pPgHdr = 0;
37562   int eCreate;
37563
37564   assert( pCache!=0 );
37565   assert( createFlag==1 || createFlag==0 );
37566   assert( pgno>0 );
37567
37568   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
37569   ** allocate it now.
37570   */
37571   if( !pCache->pCache && createFlag ){
37572     sqlite3_pcache *p;
37573     p = sqlite3GlobalConfig.pcache2.xCreate(
37574         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
37575     );
37576     if( !p ){
37577       return SQLITE_NOMEM;
37578     }
37579     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
37580     pCache->pCache = p;
37581   }
37582
37583   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
37584   if( pCache->pCache ){
37585     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
37586   }
37587
37588   if( !pPage && eCreate==1 ){
37589     PgHdr *pPg;
37590
37591     /* Find a dirty page to write-out and recycle. First try to find a
37592     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
37593     ** cleared), but if that is not possible settle for any other
37594     ** unreferenced dirty page.
37595     */
37596     expensive_assert( pcacheCheckSynced(pCache) );
37597     for(pPg=pCache->pSynced;
37598         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
37599         pPg=pPg->pDirtyPrev
37600     );
37601     pCache->pSynced = pPg;
37602     if( !pPg ){
37603       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
37604     }
37605     if( pPg ){
37606       int rc;
37607 #ifdef SQLITE_LOG_CACHE_SPILL
37608       sqlite3_log(SQLITE_FULL,
37609                   "spill page %d making room for %d - cache used: %d/%d",
37610                   pPg->pgno, pgno,
37611                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
37612                   numberOfCachePages(pCache));
37613 #endif
37614       rc = pCache->xStress(pCache->pStress, pPg);
37615       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
37616         return rc;
37617       }
37618     }
37619
37620     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
37621   }
37622
37623   if( pPage ){
37624     pPgHdr = (PgHdr *)pPage->pExtra;
37625
37626     if( !pPgHdr->pPage ){
37627       memset(pPgHdr, 0, sizeof(PgHdr));
37628       pPgHdr->pPage = pPage;
37629       pPgHdr->pData = pPage->pBuf;
37630       pPgHdr->pExtra = (void *)&pPgHdr[1];
37631       memset(pPgHdr->pExtra, 0, pCache->szExtra);
37632       pPgHdr->pCache = pCache;
37633       pPgHdr->pgno = pgno;
37634     }
37635     assert( pPgHdr->pCache==pCache );
37636     assert( pPgHdr->pgno==pgno );
37637     assert( pPgHdr->pData==pPage->pBuf );
37638     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
37639
37640     if( 0==pPgHdr->nRef ){
37641       pCache->nRef++;
37642     }
37643     pPgHdr->nRef++;
37644     if( pgno==1 ){
37645       pCache->pPage1 = pPgHdr;
37646     }
37647   }
37648   *ppPage = pPgHdr;
37649   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
37650 }
37651
37652 /*
37653 ** Decrement the reference count on a page. If the page is clean and the
37654 ** reference count drops to 0, then it is made elible for recycling.
37655 */
37656 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
37657   assert( p->nRef>0 );
37658   p->nRef--;
37659   if( p->nRef==0 ){
37660     PCache *pCache = p->pCache;
37661     pCache->nRef--;
37662     if( (p->flags&PGHDR_DIRTY)==0 ){
37663       pcacheUnpin(p);
37664     }else{
37665       /* Move the page to the head of the dirty list. */
37666       pcacheRemoveFromDirtyList(p);
37667       pcacheAddToDirtyList(p);
37668     }
37669   }
37670 }
37671
37672 /*
37673 ** Increase the reference count of a supplied page by 1.
37674 */
37675 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
37676   assert(p->nRef>0);
37677   p->nRef++;
37678 }
37679
37680 /*
37681 ** Drop a page from the cache. There must be exactly one reference to the
37682 ** page. This function deletes that reference, so after it returns the
37683 ** page pointed to by p is invalid.
37684 */
37685 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
37686   PCache *pCache;
37687   assert( p->nRef==1 );
37688   if( p->flags&PGHDR_DIRTY ){
37689     pcacheRemoveFromDirtyList(p);
37690   }
37691   pCache = p->pCache;
37692   pCache->nRef--;
37693   if( p->pgno==1 ){
37694     pCache->pPage1 = 0;
37695   }
37696   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
37697 }
37698
37699 /*
37700 ** Make sure the page is marked as dirty. If it isn't dirty already,
37701 ** make it so.
37702 */
37703 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
37704   p->flags &= ~PGHDR_DONT_WRITE;
37705   assert( p->nRef>0 );
37706   if( 0==(p->flags & PGHDR_DIRTY) ){
37707     p->flags |= PGHDR_DIRTY;
37708     pcacheAddToDirtyList( p);
37709   }
37710 }
37711
37712 /*
37713 ** Make sure the page is marked as clean. If it isn't clean already,
37714 ** make it so.
37715 */
37716 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
37717   if( (p->flags & PGHDR_DIRTY) ){
37718     pcacheRemoveFromDirtyList(p);
37719     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
37720     if( p->nRef==0 ){
37721       pcacheUnpin(p);
37722     }
37723   }
37724 }
37725
37726 /*
37727 ** Make every page in the cache clean.
37728 */
37729 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
37730   PgHdr *p;
37731   while( (p = pCache->pDirty)!=0 ){
37732     sqlite3PcacheMakeClean(p);
37733   }
37734 }
37735
37736 /*
37737 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
37738 */
37739 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
37740   PgHdr *p;
37741   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37742     p->flags &= ~PGHDR_NEED_SYNC;
37743   }
37744   pCache->pSynced = pCache->pDirtyTail;
37745 }
37746
37747 /*
37748 ** Change the page number of page p to newPgno.
37749 */
37750 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
37751   PCache *pCache = p->pCache;
37752   assert( p->nRef>0 );
37753   assert( newPgno>0 );
37754   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
37755   p->pgno = newPgno;
37756   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
37757     pcacheRemoveFromDirtyList(p);
37758     pcacheAddToDirtyList(p);
37759   }
37760 }
37761
37762 /*
37763 ** Drop every cache entry whose page number is greater than "pgno". The
37764 ** caller must ensure that there are no outstanding references to any pages
37765 ** other than page 1 with a page number greater than pgno.
37766 **
37767 ** If there is a reference to page 1 and the pgno parameter passed to this
37768 ** function is 0, then the data area associated with page 1 is zeroed, but
37769 ** the page object is not dropped.
37770 */
37771 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
37772   if( pCache->pCache ){
37773     PgHdr *p;
37774     PgHdr *pNext;
37775     for(p=pCache->pDirty; p; p=pNext){
37776       pNext = p->pDirtyNext;
37777       /* This routine never gets call with a positive pgno except right
37778       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
37779       ** it must be that pgno==0.
37780       */
37781       assert( p->pgno>0 );
37782       if( ALWAYS(p->pgno>pgno) ){
37783         assert( p->flags&PGHDR_DIRTY );
37784         sqlite3PcacheMakeClean(p);
37785       }
37786     }
37787     if( pgno==0 && pCache->pPage1 ){
37788       memset(pCache->pPage1->pData, 0, pCache->szPage);
37789       pgno = 1;
37790     }
37791     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
37792   }
37793 }
37794
37795 /*
37796 ** Close a cache.
37797 */
37798 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
37799   if( pCache->pCache ){
37800     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37801   }
37802 }
37803
37804 /*
37805 ** Discard the contents of the cache.
37806 */
37807 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
37808   sqlite3PcacheTruncate(pCache, 0);
37809 }
37810
37811 /*
37812 ** Merge two lists of pages connected by pDirty and in pgno order.
37813 ** Do not both fixing the pDirtyPrev pointers.
37814 */
37815 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
37816   PgHdr result, *pTail;
37817   pTail = &result;
37818   while( pA && pB ){
37819     if( pA->pgno<pB->pgno ){
37820       pTail->pDirty = pA;
37821       pTail = pA;
37822       pA = pA->pDirty;
37823     }else{
37824       pTail->pDirty = pB;
37825       pTail = pB;
37826       pB = pB->pDirty;
37827     }
37828   }
37829   if( pA ){
37830     pTail->pDirty = pA;
37831   }else if( pB ){
37832     pTail->pDirty = pB;
37833   }else{
37834     pTail->pDirty = 0;
37835   }
37836   return result.pDirty;
37837 }
37838
37839 /*
37840 ** Sort the list of pages in accending order by pgno.  Pages are
37841 ** connected by pDirty pointers.  The pDirtyPrev pointers are
37842 ** corrupted by this sort.
37843 **
37844 ** Since there cannot be more than 2^31 distinct pages in a database,
37845 ** there cannot be more than 31 buckets required by the merge sorter.
37846 ** One extra bucket is added to catch overflow in case something
37847 ** ever changes to make the previous sentence incorrect.
37848 */
37849 #define N_SORT_BUCKET  32
37850 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
37851   PgHdr *a[N_SORT_BUCKET], *p;
37852   int i;
37853   memset(a, 0, sizeof(a));
37854   while( pIn ){
37855     p = pIn;
37856     pIn = p->pDirty;
37857     p->pDirty = 0;
37858     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
37859       if( a[i]==0 ){
37860         a[i] = p;
37861         break;
37862       }else{
37863         p = pcacheMergeDirtyList(a[i], p);
37864         a[i] = 0;
37865       }
37866     }
37867     if( NEVER(i==N_SORT_BUCKET-1) ){
37868       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
37869       ** the input list.  But that is impossible.
37870       */
37871       a[i] = pcacheMergeDirtyList(a[i], p);
37872     }
37873   }
37874   p = a[0];
37875   for(i=1; i<N_SORT_BUCKET; i++){
37876     p = pcacheMergeDirtyList(p, a[i]);
37877   }
37878   return p;
37879 }
37880
37881 /*
37882 ** Return a list of all dirty pages in the cache, sorted by page number.
37883 */
37884 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
37885   PgHdr *p;
37886   for(p=pCache->pDirty; p; p=p->pDirtyNext){
37887     p->pDirty = p->pDirtyNext;
37888   }
37889   return pcacheSortDirtyList(pCache->pDirty);
37890 }
37891
37892 /*
37893 ** Return the total number of referenced pages held by the cache.
37894 */
37895 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
37896   return pCache->nRef;
37897 }
37898
37899 /*
37900 ** Return the number of references to the page supplied as an argument.
37901 */
37902 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
37903   return p->nRef;
37904 }
37905
37906 /*
37907 ** Return the total number of pages in the cache.
37908 */
37909 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
37910   int nPage = 0;
37911   if( pCache->pCache ){
37912     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
37913   }
37914   return nPage;
37915 }
37916
37917 #ifdef SQLITE_TEST
37918 /*
37919 ** Get the suggested cache-size value.
37920 */
37921 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
37922   return numberOfCachePages(pCache);
37923 }
37924 #endif
37925
37926 /*
37927 ** Set the suggested cache-size value.
37928 */
37929 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
37930   pCache->szCache = mxPage;
37931   if( pCache->pCache ){
37932     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
37933                                            numberOfCachePages(pCache));
37934   }
37935 }
37936
37937 /*
37938 ** Free up as much memory as possible from the page cache.
37939 */
37940 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
37941   if( pCache->pCache ){
37942     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
37943   }
37944 }
37945
37946 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
37947 /*
37948 ** For all dirty pages currently in the cache, invoke the specified
37949 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
37950 ** defined.
37951 */
37952 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
37953   PgHdr *pDirty;
37954   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
37955     xIter(pDirty);
37956   }
37957 }
37958 #endif
37959
37960 /************** End of pcache.c **********************************************/
37961 /************** Begin file pcache1.c *****************************************/
37962 /*
37963 ** 2008 November 05
37964 **
37965 ** The author disclaims copyright to this source code.  In place of
37966 ** a legal notice, here is a blessing:
37967 **
37968 **    May you do good and not evil.
37969 **    May you find forgiveness for yourself and forgive others.
37970 **    May you share freely, never taking more than you give.
37971 **
37972 *************************************************************************
37973 **
37974 ** This file implements the default page cache implementation (the
37975 ** sqlite3_pcache interface). It also contains part of the implementation
37976 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
37977 ** If the default page cache implementation is overriden, then neither of
37978 ** these two features are available.
37979 */
37980
37981
37982 typedef struct PCache1 PCache1;
37983 typedef struct PgHdr1 PgHdr1;
37984 typedef struct PgFreeslot PgFreeslot;
37985 typedef struct PGroup PGroup;
37986
37987 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
37988 ** of one or more PCaches that are able to recycle each others unpinned
37989 ** pages when they are under memory pressure.  A PGroup is an instance of
37990 ** the following object.
37991 **
37992 ** This page cache implementation works in one of two modes:
37993 **
37994 **   (1)  Every PCache is the sole member of its own PGroup.  There is
37995 **        one PGroup per PCache.
37996 **
37997 **   (2)  There is a single global PGroup that all PCaches are a member
37998 **        of.
37999 **
38000 ** Mode 1 uses more memory (since PCache instances are not able to rob
38001 ** unused pages from other PCaches) but it also operates without a mutex,
38002 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
38003 ** threadsafe, but recycles pages more efficiently.
38004 **
38005 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
38006 ** PGroup which is the pcache1.grp global variable and its mutex is
38007 ** SQLITE_MUTEX_STATIC_LRU.
38008 */
38009 struct PGroup {
38010   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
38011   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
38012   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
38013   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
38014   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
38015   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
38016 };
38017
38018 /* Each page cache is an instance of the following object.  Every
38019 ** open database file (including each in-memory database and each
38020 ** temporary or transient database) has a single page cache which
38021 ** is an instance of this object.
38022 **
38023 ** Pointers to structures of this type are cast and returned as
38024 ** opaque sqlite3_pcache* handles.
38025 */
38026 struct PCache1 {
38027   /* Cache configuration parameters. Page size (szPage) and the purgeable
38028   ** flag (bPurgeable) are set when the cache is created. nMax may be
38029   ** modified at any time by a call to the pcache1Cachesize() method.
38030   ** The PGroup mutex must be held when accessing nMax.
38031   */
38032   PGroup *pGroup;                     /* PGroup this cache belongs to */
38033   int szPage;                         /* Size of allocated pages in bytes */
38034   int szExtra;                        /* Size of extra space in bytes */
38035   int bPurgeable;                     /* True if cache is purgeable */
38036   unsigned int nMin;                  /* Minimum number of pages reserved */
38037   unsigned int nMax;                  /* Configured "cache_size" value */
38038   unsigned int n90pct;                /* nMax*9/10 */
38039   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
38040
38041   /* Hash table of all pages. The following variables may only be accessed
38042   ** when the accessor is holding the PGroup mutex.
38043   */
38044   unsigned int nRecyclable;           /* Number of pages in the LRU list */
38045   unsigned int nPage;                 /* Total number of pages in apHash */
38046   unsigned int nHash;                 /* Number of slots in apHash[] */
38047   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
38048 };
38049
38050 /*
38051 ** Each cache entry is represented by an instance of the following
38052 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
38053 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
38054 ** in memory.
38055 */
38056 struct PgHdr1 {
38057   sqlite3_pcache_page page;
38058   unsigned int iKey;             /* Key value (page number) */
38059   PgHdr1 *pNext;                 /* Next in hash table chain */
38060   PCache1 *pCache;               /* Cache that currently owns this page */
38061   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
38062   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
38063 };
38064
38065 /*
38066 ** Free slots in the allocator used to divide up the buffer provided using
38067 ** the SQLITE_CONFIG_PAGECACHE mechanism.
38068 */
38069 struct PgFreeslot {
38070   PgFreeslot *pNext;  /* Next free slot */
38071 };
38072
38073 /*
38074 ** Global data used by this cache.
38075 */
38076 static SQLITE_WSD struct PCacheGlobal {
38077   PGroup grp;                    /* The global PGroup for mode (2) */
38078
38079   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
38080   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
38081   ** fixed at sqlite3_initialize() time and do not require mutex protection.
38082   ** The nFreeSlot and pFree values do require mutex protection.
38083   */
38084   int isInit;                    /* True if initialized */
38085   int szSlot;                    /* Size of each free slot */
38086   int nSlot;                     /* The number of pcache slots */
38087   int nReserve;                  /* Try to keep nFreeSlot above this */
38088   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
38089   /* Above requires no mutex.  Use mutex below for variable that follow. */
38090   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
38091   PgFreeslot *pFree;             /* Free page blocks */
38092   int nFreeSlot;                 /* Number of unused pcache slots */
38093   /* The following value requires a mutex to change.  We skip the mutex on
38094   ** reading because (1) most platforms read a 32-bit integer atomically and
38095   ** (2) even if an incorrect value is read, no great harm is done since this
38096   ** is really just an optimization. */
38097   int bUnderPressure;            /* True if low on PAGECACHE memory */
38098 } pcache1_g;
38099
38100 /*
38101 ** All code in this file should access the global structure above via the
38102 ** alias "pcache1". This ensures that the WSD emulation is used when
38103 ** compiling for systems that do not support real WSD.
38104 */
38105 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
38106
38107 /*
38108 ** Macros to enter and leave the PCache LRU mutex.
38109 */
38110 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
38111 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
38112
38113 /******************************************************************************/
38114 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
38115
38116 /*
38117 ** This function is called during initialization if a static buffer is
38118 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
38119 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
38120 ** enough to contain 'n' buffers of 'sz' bytes each.
38121 **
38122 ** This routine is called from sqlite3_initialize() and so it is guaranteed
38123 ** to be serialized already.  There is no need for further mutexing.
38124 */
38125 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
38126   if( pcache1.isInit ){
38127     PgFreeslot *p;
38128     sz = ROUNDDOWN8(sz);
38129     pcache1.szSlot = sz;
38130     pcache1.nSlot = pcache1.nFreeSlot = n;
38131     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
38132     pcache1.pStart = pBuf;
38133     pcache1.pFree = 0;
38134     pcache1.bUnderPressure = 0;
38135     while( n-- ){
38136       p = (PgFreeslot*)pBuf;
38137       p->pNext = pcache1.pFree;
38138       pcache1.pFree = p;
38139       pBuf = (void*)&((char*)pBuf)[sz];
38140     }
38141     pcache1.pEnd = pBuf;
38142   }
38143 }
38144
38145 /*
38146 ** Malloc function used within this file to allocate space from the buffer
38147 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
38148 ** such buffer exists or there is no space left in it, this function falls
38149 ** back to sqlite3Malloc().
38150 **
38151 ** Multiple threads can run this routine at the same time.  Global variables
38152 ** in pcache1 need to be protected via mutex.
38153 */
38154 static void *pcache1Alloc(int nByte){
38155   void *p = 0;
38156   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
38157   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
38158   if( nByte<=pcache1.szSlot ){
38159     sqlite3_mutex_enter(pcache1.mutex);
38160     p = (PgHdr1 *)pcache1.pFree;
38161     if( p ){
38162       pcache1.pFree = pcache1.pFree->pNext;
38163       pcache1.nFreeSlot--;
38164       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38165       assert( pcache1.nFreeSlot>=0 );
38166       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
38167     }
38168     sqlite3_mutex_leave(pcache1.mutex);
38169   }
38170   if( p==0 ){
38171     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
38172     ** it from sqlite3Malloc instead.
38173     */
38174     p = sqlite3Malloc(nByte);
38175 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
38176     if( p ){
38177       int sz = sqlite3MallocSize(p);
38178       sqlite3_mutex_enter(pcache1.mutex);
38179       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
38180       sqlite3_mutex_leave(pcache1.mutex);
38181     }
38182 #endif
38183     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
38184   }
38185   return p;
38186 }
38187
38188 /*
38189 ** Free an allocated buffer obtained from pcache1Alloc().
38190 */
38191 static int pcache1Free(void *p){
38192   int nFreed = 0;
38193   if( p==0 ) return 0;
38194   if( p>=pcache1.pStart && p<pcache1.pEnd ){
38195     PgFreeslot *pSlot;
38196     sqlite3_mutex_enter(pcache1.mutex);
38197     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
38198     pSlot = (PgFreeslot*)p;
38199     pSlot->pNext = pcache1.pFree;
38200     pcache1.pFree = pSlot;
38201     pcache1.nFreeSlot++;
38202     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38203     assert( pcache1.nFreeSlot<=pcache1.nSlot );
38204     sqlite3_mutex_leave(pcache1.mutex);
38205   }else{
38206     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
38207     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
38208     nFreed = sqlite3MallocSize(p);
38209 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
38210     sqlite3_mutex_enter(pcache1.mutex);
38211     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
38212     sqlite3_mutex_leave(pcache1.mutex);
38213 #endif
38214     sqlite3_free(p);
38215   }
38216   return nFreed;
38217 }
38218
38219 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
38220 /*
38221 ** Return the size of a pcache allocation
38222 */
38223 static int pcache1MemSize(void *p){
38224   if( p>=pcache1.pStart && p<pcache1.pEnd ){
38225     return pcache1.szSlot;
38226   }else{
38227     int iSize;
38228     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
38229     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
38230     iSize = sqlite3MallocSize(p);
38231     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
38232     return iSize;
38233   }
38234 }
38235 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
38236
38237 /*
38238 ** Allocate a new page object initially associated with cache pCache.
38239 */
38240 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
38241   PgHdr1 *p = 0;
38242   void *pPg;
38243
38244   /* The group mutex must be released before pcache1Alloc() is called. This
38245   ** is because it may call sqlite3_release_memory(), which assumes that
38246   ** this mutex is not held. */
38247   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38248   pcache1LeaveMutex(pCache->pGroup);
38249 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38250   pPg = pcache1Alloc(pCache->szPage);
38251   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
38252   if( !pPg || !p ){
38253     pcache1Free(pPg);
38254     sqlite3_free(p);
38255     pPg = 0;
38256   }
38257 #else
38258   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
38259   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
38260 #endif
38261   pcache1EnterMutex(pCache->pGroup);
38262
38263   if( pPg ){
38264     p->page.pBuf = pPg;
38265     p->page.pExtra = &p[1];
38266     if( pCache->bPurgeable ){
38267       pCache->pGroup->nCurrentPage++;
38268     }
38269     return p;
38270   }
38271   return 0;
38272 }
38273
38274 /*
38275 ** Free a page object allocated by pcache1AllocPage().
38276 **
38277 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
38278 ** that the current implementation happens to never call this routine
38279 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
38280 */
38281 static void pcache1FreePage(PgHdr1 *p){
38282   if( ALWAYS(p) ){
38283     PCache1 *pCache = p->pCache;
38284     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
38285     pcache1Free(p->page.pBuf);
38286 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38287     sqlite3_free(p);
38288 #endif
38289     if( pCache->bPurgeable ){
38290       pCache->pGroup->nCurrentPage--;
38291     }
38292   }
38293 }
38294
38295 /*
38296 ** Malloc function used by SQLite to obtain space from the buffer configured
38297 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
38298 ** exists, this function falls back to sqlite3Malloc().
38299 */
38300 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
38301   return pcache1Alloc(sz);
38302 }
38303
38304 /*
38305 ** Free an allocated buffer obtained from sqlite3PageMalloc().
38306 */
38307 SQLITE_PRIVATE void sqlite3PageFree(void *p){
38308   pcache1Free(p);
38309 }
38310
38311
38312 /*
38313 ** Return true if it desirable to avoid allocating a new page cache
38314 ** entry.
38315 **
38316 ** If memory was allocated specifically to the page cache using
38317 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
38318 ** it is desirable to avoid allocating a new page cache entry because
38319 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
38320 ** for all page cache needs and we should not need to spill the
38321 ** allocation onto the heap.
38322 **
38323 ** Or, the heap is used for all page cache memory but the heap is
38324 ** under memory pressure, then again it is desirable to avoid
38325 ** allocating a new page cache entry in order to avoid stressing
38326 ** the heap even further.
38327 */
38328 static int pcache1UnderMemoryPressure(PCache1 *pCache){
38329   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
38330     return pcache1.bUnderPressure;
38331   }else{
38332     return sqlite3HeapNearlyFull();
38333   }
38334 }
38335
38336 /******************************************************************************/
38337 /******** General Implementation Functions ************************************/
38338
38339 /*
38340 ** This function is used to resize the hash table used by the cache passed
38341 ** as the first argument.
38342 **
38343 ** The PCache mutex must be held when this function is called.
38344 */
38345 static int pcache1ResizeHash(PCache1 *p){
38346   PgHdr1 **apNew;
38347   unsigned int nNew;
38348   unsigned int i;
38349
38350   assert( sqlite3_mutex_held(p->pGroup->mutex) );
38351
38352   nNew = p->nHash*2;
38353   if( nNew<256 ){
38354     nNew = 256;
38355   }
38356
38357   pcache1LeaveMutex(p->pGroup);
38358   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
38359   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
38360   if( p->nHash ){ sqlite3EndBenignMalloc(); }
38361   pcache1EnterMutex(p->pGroup);
38362   if( apNew ){
38363     for(i=0; i<p->nHash; i++){
38364       PgHdr1 *pPage;
38365       PgHdr1 *pNext = p->apHash[i];
38366       while( (pPage = pNext)!=0 ){
38367         unsigned int h = pPage->iKey % nNew;
38368         pNext = pPage->pNext;
38369         pPage->pNext = apNew[h];
38370         apNew[h] = pPage;
38371       }
38372     }
38373     sqlite3_free(p->apHash);
38374     p->apHash = apNew;
38375     p->nHash = nNew;
38376   }
38377
38378   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
38379 }
38380
38381 /*
38382 ** This function is used internally to remove the page pPage from the
38383 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
38384 ** LRU list, then this function is a no-op.
38385 **
38386 ** The PGroup mutex must be held when this function is called.
38387 **
38388 ** If pPage is NULL then this routine is a no-op.
38389 */
38390 static void pcache1PinPage(PgHdr1 *pPage){
38391   PCache1 *pCache;
38392   PGroup *pGroup;
38393
38394   if( pPage==0 ) return;
38395   pCache = pPage->pCache;
38396   pGroup = pCache->pGroup;
38397   assert( sqlite3_mutex_held(pGroup->mutex) );
38398   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
38399     if( pPage->pLruPrev ){
38400       pPage->pLruPrev->pLruNext = pPage->pLruNext;
38401     }
38402     if( pPage->pLruNext ){
38403       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
38404     }
38405     if( pGroup->pLruHead==pPage ){
38406       pGroup->pLruHead = pPage->pLruNext;
38407     }
38408     if( pGroup->pLruTail==pPage ){
38409       pGroup->pLruTail = pPage->pLruPrev;
38410     }
38411     pPage->pLruNext = 0;
38412     pPage->pLruPrev = 0;
38413     pPage->pCache->nRecyclable--;
38414   }
38415 }
38416
38417
38418 /*
38419 ** Remove the page supplied as an argument from the hash table
38420 ** (PCache1.apHash structure) that it is currently stored in.
38421 **
38422 ** The PGroup mutex must be held when this function is called.
38423 */
38424 static void pcache1RemoveFromHash(PgHdr1 *pPage){
38425   unsigned int h;
38426   PCache1 *pCache = pPage->pCache;
38427   PgHdr1 **pp;
38428
38429   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38430   h = pPage->iKey % pCache->nHash;
38431   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
38432   *pp = (*pp)->pNext;
38433
38434   pCache->nPage--;
38435 }
38436
38437 /*
38438 ** If there are currently more than nMaxPage pages allocated, try
38439 ** to recycle pages to reduce the number allocated to nMaxPage.
38440 */
38441 static void pcache1EnforceMaxPage(PGroup *pGroup){
38442   assert( sqlite3_mutex_held(pGroup->mutex) );
38443   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
38444     PgHdr1 *p = pGroup->pLruTail;
38445     assert( p->pCache->pGroup==pGroup );
38446     pcache1PinPage(p);
38447     pcache1RemoveFromHash(p);
38448     pcache1FreePage(p);
38449   }
38450 }
38451
38452 /*
38453 ** Discard all pages from cache pCache with a page number (key value)
38454 ** greater than or equal to iLimit. Any pinned pages that meet this
38455 ** criteria are unpinned before they are discarded.
38456 **
38457 ** The PCache mutex must be held when this function is called.
38458 */
38459 static void pcache1TruncateUnsafe(
38460   PCache1 *pCache,             /* The cache to truncate */
38461   unsigned int iLimit          /* Drop pages with this pgno or larger */
38462 ){
38463   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
38464   unsigned int h;
38465   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38466   for(h=0; h<pCache->nHash; h++){
38467     PgHdr1 **pp = &pCache->apHash[h];
38468     PgHdr1 *pPage;
38469     while( (pPage = *pp)!=0 ){
38470       if( pPage->iKey>=iLimit ){
38471         pCache->nPage--;
38472         *pp = pPage->pNext;
38473         pcache1PinPage(pPage);
38474         pcache1FreePage(pPage);
38475       }else{
38476         pp = &pPage->pNext;
38477         TESTONLY( nPage++; )
38478       }
38479     }
38480   }
38481   assert( pCache->nPage==nPage );
38482 }
38483
38484 /******************************************************************************/
38485 /******** sqlite3_pcache Methods **********************************************/
38486
38487 /*
38488 ** Implementation of the sqlite3_pcache.xInit method.
38489 */
38490 static int pcache1Init(void *NotUsed){
38491   UNUSED_PARAMETER(NotUsed);
38492   assert( pcache1.isInit==0 );
38493   memset(&pcache1, 0, sizeof(pcache1));
38494   if( sqlite3GlobalConfig.bCoreMutex ){
38495     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
38496     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
38497   }
38498   pcache1.grp.mxPinned = 10;
38499   pcache1.isInit = 1;
38500   return SQLITE_OK;
38501 }
38502
38503 /*
38504 ** Implementation of the sqlite3_pcache.xShutdown method.
38505 ** Note that the static mutex allocated in xInit does
38506 ** not need to be freed.
38507 */
38508 static void pcache1Shutdown(void *NotUsed){
38509   UNUSED_PARAMETER(NotUsed);
38510   assert( pcache1.isInit!=0 );
38511   memset(&pcache1, 0, sizeof(pcache1));
38512 }
38513
38514 /*
38515 ** Implementation of the sqlite3_pcache.xCreate method.
38516 **
38517 ** Allocate a new cache.
38518 */
38519 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
38520   PCache1 *pCache;      /* The newly created page cache */
38521   PGroup *pGroup;       /* The group the new page cache will belong to */
38522   int sz;               /* Bytes of memory required to allocate the new cache */
38523
38524   /*
38525   ** The seperateCache variable is true if each PCache has its own private
38526   ** PGroup.  In other words, separateCache is true for mode (1) where no
38527   ** mutexing is required.
38528   **
38529   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
38530   **
38531   **   *  Always use a unified cache in single-threaded applications
38532   **
38533   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
38534   **      use separate caches (mode-1)
38535   */
38536 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
38537   const int separateCache = 0;
38538 #else
38539   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
38540 #endif
38541
38542   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
38543   assert( szExtra < 300 );
38544
38545   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
38546   pCache = (PCache1 *)sqlite3MallocZero(sz);
38547   if( pCache ){
38548     if( separateCache ){
38549       pGroup = (PGroup*)&pCache[1];
38550       pGroup->mxPinned = 10;
38551     }else{
38552       pGroup = &pcache1.grp;
38553     }
38554     pCache->pGroup = pGroup;
38555     pCache->szPage = szPage;
38556     pCache->szExtra = szExtra;
38557     pCache->bPurgeable = (bPurgeable ? 1 : 0);
38558     if( bPurgeable ){
38559       pCache->nMin = 10;
38560       pcache1EnterMutex(pGroup);
38561       pGroup->nMinPage += pCache->nMin;
38562       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38563       pcache1LeaveMutex(pGroup);
38564     }
38565   }
38566   return (sqlite3_pcache *)pCache;
38567 }
38568
38569 /*
38570 ** Implementation of the sqlite3_pcache.xCachesize method.
38571 **
38572 ** Configure the cache_size limit for a cache.
38573 */
38574 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
38575   PCache1 *pCache = (PCache1 *)p;
38576   if( pCache->bPurgeable ){
38577     PGroup *pGroup = pCache->pGroup;
38578     pcache1EnterMutex(pGroup);
38579     pGroup->nMaxPage += (nMax - pCache->nMax);
38580     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38581     pCache->nMax = nMax;
38582     pCache->n90pct = pCache->nMax*9/10;
38583     pcache1EnforceMaxPage(pGroup);
38584     pcache1LeaveMutex(pGroup);
38585   }
38586 }
38587
38588 /*
38589 ** Implementation of the sqlite3_pcache.xShrink method.
38590 **
38591 ** Free up as much memory as possible.
38592 */
38593 static void pcache1Shrink(sqlite3_pcache *p){
38594   PCache1 *pCache = (PCache1*)p;
38595   if( pCache->bPurgeable ){
38596     PGroup *pGroup = pCache->pGroup;
38597     int savedMaxPage;
38598     pcache1EnterMutex(pGroup);
38599     savedMaxPage = pGroup->nMaxPage;
38600     pGroup->nMaxPage = 0;
38601     pcache1EnforceMaxPage(pGroup);
38602     pGroup->nMaxPage = savedMaxPage;
38603     pcache1LeaveMutex(pGroup);
38604   }
38605 }
38606
38607 /*
38608 ** Implementation of the sqlite3_pcache.xPagecount method.
38609 */
38610 static int pcache1Pagecount(sqlite3_pcache *p){
38611   int n;
38612   PCache1 *pCache = (PCache1*)p;
38613   pcache1EnterMutex(pCache->pGroup);
38614   n = pCache->nPage;
38615   pcache1LeaveMutex(pCache->pGroup);
38616   return n;
38617 }
38618
38619 /*
38620 ** Implementation of the sqlite3_pcache.xFetch method.
38621 **
38622 ** Fetch a page by key value.
38623 **
38624 ** Whether or not a new page may be allocated by this function depends on
38625 ** the value of the createFlag argument.  0 means do not allocate a new
38626 ** page.  1 means allocate a new page if space is easily available.  2
38627 ** means to try really hard to allocate a new page.
38628 **
38629 ** For a non-purgeable cache (a cache used as the storage for an in-memory
38630 ** database) there is really no difference between createFlag 1 and 2.  So
38631 ** the calling function (pcache.c) will never have a createFlag of 1 on
38632 ** a non-purgeable cache.
38633 **
38634 ** There are three different approaches to obtaining space for a page,
38635 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
38636 **
38637 **   1. Regardless of the value of createFlag, the cache is searched for a
38638 **      copy of the requested page. If one is found, it is returned.
38639 **
38640 **   2. If createFlag==0 and the page is not already in the cache, NULL is
38641 **      returned.
38642 **
38643 **   3. If createFlag is 1, and the page is not already in the cache, then
38644 **      return NULL (do not allocate a new page) if any of the following
38645 **      conditions are true:
38646 **
38647 **       (a) the number of pages pinned by the cache is greater than
38648 **           PCache1.nMax, or
38649 **
38650 **       (b) the number of pages pinned by the cache is greater than
38651 **           the sum of nMax for all purgeable caches, less the sum of
38652 **           nMin for all other purgeable caches, or
38653 **
38654 **   4. If none of the first three conditions apply and the cache is marked
38655 **      as purgeable, and if one of the following is true:
38656 **
38657 **       (a) The number of pages allocated for the cache is already
38658 **           PCache1.nMax, or
38659 **
38660 **       (b) The number of pages allocated for all purgeable caches is
38661 **           already equal to or greater than the sum of nMax for all
38662 **           purgeable caches,
38663 **
38664 **       (c) The system is under memory pressure and wants to avoid
38665 **           unnecessary pages cache entry allocations
38666 **
38667 **      then attempt to recycle a page from the LRU list. If it is the right
38668 **      size, return the recycled buffer. Otherwise, free the buffer and
38669 **      proceed to step 5.
38670 **
38671 **   5. Otherwise, allocate and return a new page buffer.
38672 */
38673 static sqlite3_pcache_page *pcache1Fetch(
38674   sqlite3_pcache *p,
38675   unsigned int iKey,
38676   int createFlag
38677 ){
38678   unsigned int nPinned;
38679   PCache1 *pCache = (PCache1 *)p;
38680   PGroup *pGroup;
38681   PgHdr1 *pPage = 0;
38682
38683   assert( pCache->bPurgeable || createFlag!=1 );
38684   assert( pCache->bPurgeable || pCache->nMin==0 );
38685   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
38686   assert( pCache->nMin==0 || pCache->bPurgeable );
38687   pcache1EnterMutex(pGroup = pCache->pGroup);
38688
38689   /* Step 1: Search the hash table for an existing entry. */
38690   if( pCache->nHash>0 ){
38691     unsigned int h = iKey % pCache->nHash;
38692     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
38693   }
38694
38695   /* Step 2: Abort if no existing page is found and createFlag is 0 */
38696   if( pPage || createFlag==0 ){
38697     pcache1PinPage(pPage);
38698     goto fetch_out;
38699   }
38700
38701   /* The pGroup local variable will normally be initialized by the
38702   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
38703   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
38704   ** local variable here.  Delaying the initialization of pGroup is an
38705   ** optimization:  The common case is to exit the module before reaching
38706   ** this point.
38707   */
38708 #ifdef SQLITE_MUTEX_OMIT
38709   pGroup = pCache->pGroup;
38710 #endif
38711
38712   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
38713   assert( pCache->nPage >= pCache->nRecyclable );
38714   nPinned = pCache->nPage - pCache->nRecyclable;
38715   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
38716   assert( pCache->n90pct == pCache->nMax*9/10 );
38717   if( createFlag==1 && (
38718         nPinned>=pGroup->mxPinned
38719      || nPinned>=pCache->n90pct
38720      || pcache1UnderMemoryPressure(pCache)
38721   )){
38722     goto fetch_out;
38723   }
38724
38725   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
38726     goto fetch_out;
38727   }
38728
38729   /* Step 4. Try to recycle a page. */
38730   if( pCache->bPurgeable && pGroup->pLruTail && (
38731          (pCache->nPage+1>=pCache->nMax)
38732       || pGroup->nCurrentPage>=pGroup->nMaxPage
38733       || pcache1UnderMemoryPressure(pCache)
38734   )){
38735     PCache1 *pOther;
38736     pPage = pGroup->pLruTail;
38737     pcache1RemoveFromHash(pPage);
38738     pcache1PinPage(pPage);
38739     pOther = pPage->pCache;
38740
38741     /* We want to verify that szPage and szExtra are the same for pOther
38742     ** and pCache.  Assert that we can verify this by comparing sums. */
38743     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
38744     assert( pCache->szExtra<512 );
38745     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
38746     assert( pOther->szExtra<512 );
38747
38748     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
38749       pcache1FreePage(pPage);
38750       pPage = 0;
38751     }else{
38752       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
38753     }
38754   }
38755
38756   /* Step 5. If a usable page buffer has still not been found,
38757   ** attempt to allocate a new one.
38758   */
38759   if( !pPage ){
38760     if( createFlag==1 ) sqlite3BeginBenignMalloc();
38761     pPage = pcache1AllocPage(pCache);
38762     if( createFlag==1 ) sqlite3EndBenignMalloc();
38763   }
38764
38765   if( pPage ){
38766     unsigned int h = iKey % pCache->nHash;
38767     pCache->nPage++;
38768     pPage->iKey = iKey;
38769     pPage->pNext = pCache->apHash[h];
38770     pPage->pCache = pCache;
38771     pPage->pLruPrev = 0;
38772     pPage->pLruNext = 0;
38773     *(void **)pPage->page.pExtra = 0;
38774     pCache->apHash[h] = pPage;
38775   }
38776
38777 fetch_out:
38778   if( pPage && iKey>pCache->iMaxKey ){
38779     pCache->iMaxKey = iKey;
38780   }
38781   pcache1LeaveMutex(pGroup);
38782   return &pPage->page;
38783 }
38784
38785
38786 /*
38787 ** Implementation of the sqlite3_pcache.xUnpin method.
38788 **
38789 ** Mark a page as unpinned (eligible for asynchronous recycling).
38790 */
38791 static void pcache1Unpin(
38792   sqlite3_pcache *p,
38793   sqlite3_pcache_page *pPg,
38794   int reuseUnlikely
38795 ){
38796   PCache1 *pCache = (PCache1 *)p;
38797   PgHdr1 *pPage = (PgHdr1 *)pPg;
38798   PGroup *pGroup = pCache->pGroup;
38799
38800   assert( pPage->pCache==pCache );
38801   pcache1EnterMutex(pGroup);
38802
38803   /* It is an error to call this function if the page is already
38804   ** part of the PGroup LRU list.
38805   */
38806   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
38807   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
38808
38809   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
38810     pcache1RemoveFromHash(pPage);
38811     pcache1FreePage(pPage);
38812   }else{
38813     /* Add the page to the PGroup LRU list. */
38814     if( pGroup->pLruHead ){
38815       pGroup->pLruHead->pLruPrev = pPage;
38816       pPage->pLruNext = pGroup->pLruHead;
38817       pGroup->pLruHead = pPage;
38818     }else{
38819       pGroup->pLruTail = pPage;
38820       pGroup->pLruHead = pPage;
38821     }
38822     pCache->nRecyclable++;
38823   }
38824
38825   pcache1LeaveMutex(pCache->pGroup);
38826 }
38827
38828 /*
38829 ** Implementation of the sqlite3_pcache.xRekey method.
38830 */
38831 static void pcache1Rekey(
38832   sqlite3_pcache *p,
38833   sqlite3_pcache_page *pPg,
38834   unsigned int iOld,
38835   unsigned int iNew
38836 ){
38837   PCache1 *pCache = (PCache1 *)p;
38838   PgHdr1 *pPage = (PgHdr1 *)pPg;
38839   PgHdr1 **pp;
38840   unsigned int h;
38841   assert( pPage->iKey==iOld );
38842   assert( pPage->pCache==pCache );
38843
38844   pcache1EnterMutex(pCache->pGroup);
38845
38846   h = iOld%pCache->nHash;
38847   pp = &pCache->apHash[h];
38848   while( (*pp)!=pPage ){
38849     pp = &(*pp)->pNext;
38850   }
38851   *pp = pPage->pNext;
38852
38853   h = iNew%pCache->nHash;
38854   pPage->iKey = iNew;
38855   pPage->pNext = pCache->apHash[h];
38856   pCache->apHash[h] = pPage;
38857   if( iNew>pCache->iMaxKey ){
38858     pCache->iMaxKey = iNew;
38859   }
38860
38861   pcache1LeaveMutex(pCache->pGroup);
38862 }
38863
38864 /*
38865 ** Implementation of the sqlite3_pcache.xTruncate method.
38866 **
38867 ** Discard all unpinned pages in the cache with a page number equal to
38868 ** or greater than parameter iLimit. Any pinned pages with a page number
38869 ** equal to or greater than iLimit are implicitly unpinned.
38870 */
38871 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
38872   PCache1 *pCache = (PCache1 *)p;
38873   pcache1EnterMutex(pCache->pGroup);
38874   if( iLimit<=pCache->iMaxKey ){
38875     pcache1TruncateUnsafe(pCache, iLimit);
38876     pCache->iMaxKey = iLimit-1;
38877   }
38878   pcache1LeaveMutex(pCache->pGroup);
38879 }
38880
38881 /*
38882 ** Implementation of the sqlite3_pcache.xDestroy method.
38883 **
38884 ** Destroy a cache allocated using pcache1Create().
38885 */
38886 static void pcache1Destroy(sqlite3_pcache *p){
38887   PCache1 *pCache = (PCache1 *)p;
38888   PGroup *pGroup = pCache->pGroup;
38889   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
38890   pcache1EnterMutex(pGroup);
38891   pcache1TruncateUnsafe(pCache, 0);
38892   assert( pGroup->nMaxPage >= pCache->nMax );
38893   pGroup->nMaxPage -= pCache->nMax;
38894   assert( pGroup->nMinPage >= pCache->nMin );
38895   pGroup->nMinPage -= pCache->nMin;
38896   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38897   pcache1EnforceMaxPage(pGroup);
38898   pcache1LeaveMutex(pGroup);
38899   sqlite3_free(pCache->apHash);
38900   sqlite3_free(pCache);
38901 }
38902
38903 /*
38904 ** This function is called during initialization (sqlite3_initialize()) to
38905 ** install the default pluggable cache module, assuming the user has not
38906 ** already provided an alternative.
38907 */
38908 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
38909   static const sqlite3_pcache_methods2 defaultMethods = {
38910     1,                       /* iVersion */
38911     0,                       /* pArg */
38912     pcache1Init,             /* xInit */
38913     pcache1Shutdown,         /* xShutdown */
38914     pcache1Create,           /* xCreate */
38915     pcache1Cachesize,        /* xCachesize */
38916     pcache1Pagecount,        /* xPagecount */
38917     pcache1Fetch,            /* xFetch */
38918     pcache1Unpin,            /* xUnpin */
38919     pcache1Rekey,            /* xRekey */
38920     pcache1Truncate,         /* xTruncate */
38921     pcache1Destroy,          /* xDestroy */
38922     pcache1Shrink            /* xShrink */
38923   };
38924   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
38925 }
38926
38927 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
38928 /*
38929 ** This function is called to free superfluous dynamically allocated memory
38930 ** held by the pager system. Memory in use by any SQLite pager allocated
38931 ** by the current thread may be sqlite3_free()ed.
38932 **
38933 ** nReq is the number of bytes of memory required. Once this much has
38934 ** been released, the function returns. The return value is the total number
38935 ** of bytes of memory released.
38936 */
38937 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
38938   int nFree = 0;
38939   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
38940   assert( sqlite3_mutex_notheld(pcache1.mutex) );
38941   if( pcache1.pStart==0 ){
38942     PgHdr1 *p;
38943     pcache1EnterMutex(&pcache1.grp);
38944     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
38945       nFree += pcache1MemSize(p->page.pBuf);
38946 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38947       nFree += sqlite3MemSize(p);
38948 #endif
38949       pcache1PinPage(p);
38950       pcache1RemoveFromHash(p);
38951       pcache1FreePage(p);
38952     }
38953     pcache1LeaveMutex(&pcache1.grp);
38954   }
38955   return nFree;
38956 }
38957 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
38958
38959 #ifdef SQLITE_TEST
38960 /*
38961 ** This function is used by test procedures to inspect the internal state
38962 ** of the global cache.
38963 */
38964 SQLITE_PRIVATE void sqlite3PcacheStats(
38965   int *pnCurrent,      /* OUT: Total number of pages cached */
38966   int *pnMax,          /* OUT: Global maximum cache size */
38967   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
38968   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
38969 ){
38970   PgHdr1 *p;
38971   int nRecyclable = 0;
38972   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
38973     nRecyclable++;
38974   }
38975   *pnCurrent = pcache1.grp.nCurrentPage;
38976   *pnMax = (int)pcache1.grp.nMaxPage;
38977   *pnMin = (int)pcache1.grp.nMinPage;
38978   *pnRecyclable = nRecyclable;
38979 }
38980 #endif
38981
38982 /************** End of pcache1.c *********************************************/
38983 /************** Begin file rowset.c ******************************************/
38984 /*
38985 ** 2008 December 3
38986 **
38987 ** The author disclaims copyright to this source code.  In place of
38988 ** a legal notice, here is a blessing:
38989 **
38990 **    May you do good and not evil.
38991 **    May you find forgiveness for yourself and forgive others.
38992 **    May you share freely, never taking more than you give.
38993 **
38994 *************************************************************************
38995 **
38996 ** This module implements an object we call a "RowSet".
38997 **
38998 ** The RowSet object is a collection of rowids.  Rowids
38999 ** are inserted into the RowSet in an arbitrary order.  Inserts
39000 ** can be intermixed with tests to see if a given rowid has been
39001 ** previously inserted into the RowSet.
39002 **
39003 ** After all inserts are finished, it is possible to extract the
39004 ** elements of the RowSet in sorted order.  Once this extraction
39005 ** process has started, no new elements may be inserted.
39006 **
39007 ** Hence, the primitive operations for a RowSet are:
39008 **
39009 **    CREATE
39010 **    INSERT
39011 **    TEST
39012 **    SMALLEST
39013 **    DESTROY
39014 **
39015 ** The CREATE and DESTROY primitives are the constructor and destructor,
39016 ** obviously.  The INSERT primitive adds a new element to the RowSet.
39017 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
39018 ** extracts the least value from the RowSet.
39019 **
39020 ** The INSERT primitive might allocate additional memory.  Memory is
39021 ** allocated in chunks so most INSERTs do no allocation.  There is an
39022 ** upper bound on the size of allocated memory.  No memory is freed
39023 ** until DESTROY.
39024 **
39025 ** The TEST primitive includes a "batch" number.  The TEST primitive
39026 ** will only see elements that were inserted before the last change
39027 ** in the batch number.  In other words, if an INSERT occurs between
39028 ** two TESTs where the TESTs have the same batch nubmer, then the
39029 ** value added by the INSERT will not be visible to the second TEST.
39030 ** The initial batch number is zero, so if the very first TEST contains
39031 ** a non-zero batch number, it will see all prior INSERTs.
39032 **
39033 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
39034 ** that is attempted.
39035 **
39036 ** The cost of an INSERT is roughly constant.  (Sometime new memory
39037 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
39038 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
39039 ** The cost of a TEST using the same batch number is O(logN).  The cost
39040 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
39041 ** primitives are constant time.  The cost of DESTROY is O(N).
39042 **
39043 ** There is an added cost of O(N) when switching between TEST and
39044 ** SMALLEST primitives.
39045 */
39046
39047
39048 /*
39049 ** Target size for allocation chunks.
39050 */
39051 #define ROWSET_ALLOCATION_SIZE 1024
39052
39053 /*
39054 ** The number of rowset entries per allocation chunk.
39055 */
39056 #define ROWSET_ENTRY_PER_CHUNK  \
39057                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
39058
39059 /*
39060 ** Each entry in a RowSet is an instance of the following object.
39061 **
39062 ** This same object is reused to store a linked list of trees of RowSetEntry
39063 ** objects.  In that alternative use, pRight points to the next entry
39064 ** in the list, pLeft points to the tree, and v is unused.  The
39065 ** RowSet.pForest value points to the head of this forest list.
39066 */
39067 struct RowSetEntry {
39068   i64 v;                        /* ROWID value for this entry */
39069   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
39070   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
39071 };
39072
39073 /*
39074 ** RowSetEntry objects are allocated in large chunks (instances of the
39075 ** following structure) to reduce memory allocation overhead.  The
39076 ** chunks are kept on a linked list so that they can be deallocated
39077 ** when the RowSet is destroyed.
39078 */
39079 struct RowSetChunk {
39080   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
39081   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
39082 };
39083
39084 /*
39085 ** A RowSet in an instance of the following structure.
39086 **
39087 ** A typedef of this structure if found in sqliteInt.h.
39088 */
39089 struct RowSet {
39090   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
39091   sqlite3 *db;                   /* The database connection */
39092   struct RowSetEntry *pEntry;    /* List of entries using pRight */
39093   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
39094   struct RowSetEntry *pFresh;    /* Source of new entry objects */
39095   struct RowSetEntry *pForest;   /* List of binary trees of entries */
39096   u16 nFresh;                    /* Number of objects on pFresh */
39097   u8 rsFlags;                    /* Various flags */
39098   u8 iBatch;                     /* Current insert batch */
39099 };
39100
39101 /*
39102 ** Allowed values for RowSet.rsFlags
39103 */
39104 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
39105 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
39106
39107 /*
39108 ** Turn bulk memory into a RowSet object.  N bytes of memory
39109 ** are available at pSpace.  The db pointer is used as a memory context
39110 ** for any subsequent allocations that need to occur.
39111 ** Return a pointer to the new RowSet object.
39112 **
39113 ** It must be the case that N is sufficient to make a Rowset.  If not
39114 ** an assertion fault occurs.
39115 **
39116 ** If N is larger than the minimum, use the surplus as an initial
39117 ** allocation of entries available to be filled.
39118 */
39119 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
39120   RowSet *p;
39121   assert( N >= ROUND8(sizeof(*p)) );
39122   p = pSpace;
39123   p->pChunk = 0;
39124   p->db = db;
39125   p->pEntry = 0;
39126   p->pLast = 0;
39127   p->pForest = 0;
39128   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
39129   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
39130   p->rsFlags = ROWSET_SORTED;
39131   p->iBatch = 0;
39132   return p;
39133 }
39134
39135 /*
39136 ** Deallocate all chunks from a RowSet.  This frees all memory that
39137 ** the RowSet has allocated over its lifetime.  This routine is
39138 ** the destructor for the RowSet.
39139 */
39140 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
39141   struct RowSetChunk *pChunk, *pNextChunk;
39142   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
39143     pNextChunk = pChunk->pNextChunk;
39144     sqlite3DbFree(p->db, pChunk);
39145   }
39146   p->pChunk = 0;
39147   p->nFresh = 0;
39148   p->pEntry = 0;
39149   p->pLast = 0;
39150   p->pForest = 0;
39151   p->rsFlags = ROWSET_SORTED;
39152 }
39153
39154 /*
39155 ** Allocate a new RowSetEntry object that is associated with the
39156 ** given RowSet.  Return a pointer to the new and completely uninitialized
39157 ** objected.
39158 **
39159 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
39160 ** routine returns NULL.
39161 */
39162 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
39163   assert( p!=0 );
39164   if( p->nFresh==0 ){
39165     struct RowSetChunk *pNew;
39166     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
39167     if( pNew==0 ){
39168       return 0;
39169     }
39170     pNew->pNextChunk = p->pChunk;
39171     p->pChunk = pNew;
39172     p->pFresh = pNew->aEntry;
39173     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
39174   }
39175   p->nFresh--;
39176   return p->pFresh++;
39177 }
39178
39179 /*
39180 ** Insert a new value into a RowSet.
39181 **
39182 ** The mallocFailed flag of the database connection is set if a
39183 ** memory allocation fails.
39184 */
39185 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
39186   struct RowSetEntry *pEntry;  /* The new entry */
39187   struct RowSetEntry *pLast;   /* The last prior entry */
39188
39189   /* This routine is never called after sqlite3RowSetNext() */
39190   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
39191
39192   pEntry = rowSetEntryAlloc(p);
39193   if( pEntry==0 ) return;
39194   pEntry->v = rowid;
39195   pEntry->pRight = 0;
39196   pLast = p->pLast;
39197   if( pLast ){
39198     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
39199       p->rsFlags &= ~ROWSET_SORTED;
39200     }
39201     pLast->pRight = pEntry;
39202   }else{
39203     p->pEntry = pEntry;
39204   }
39205   p->pLast = pEntry;
39206 }
39207
39208 /*
39209 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
39210 **
39211 ** The input lists are connected via pRight pointers and are
39212 ** assumed to each already be in sorted order.
39213 */
39214 static struct RowSetEntry *rowSetEntryMerge(
39215   struct RowSetEntry *pA,    /* First sorted list to be merged */
39216   struct RowSetEntry *pB     /* Second sorted list to be merged */
39217 ){
39218   struct RowSetEntry head;
39219   struct RowSetEntry *pTail;
39220
39221   pTail = &head;
39222   while( pA && pB ){
39223     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39224     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
39225     if( pA->v<pB->v ){
39226       pTail->pRight = pA;
39227       pA = pA->pRight;
39228       pTail = pTail->pRight;
39229     }else if( pB->v<pA->v ){
39230       pTail->pRight = pB;
39231       pB = pB->pRight;
39232       pTail = pTail->pRight;
39233     }else{
39234       pA = pA->pRight;
39235     }
39236   }
39237   if( pA ){
39238     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39239     pTail->pRight = pA;
39240   }else{
39241     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
39242     pTail->pRight = pB;
39243   }
39244   return head.pRight;
39245 }
39246
39247 /*
39248 ** Sort all elements on the list of RowSetEntry objects into order of
39249 ** increasing v.
39250 */
39251 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
39252   unsigned int i;
39253   struct RowSetEntry *pNext, *aBucket[40];
39254
39255   memset(aBucket, 0, sizeof(aBucket));
39256   while( pIn ){
39257     pNext = pIn->pRight;
39258     pIn->pRight = 0;
39259     for(i=0; aBucket[i]; i++){
39260       pIn = rowSetEntryMerge(aBucket[i], pIn);
39261       aBucket[i] = 0;
39262     }
39263     aBucket[i] = pIn;
39264     pIn = pNext;
39265   }
39266   pIn = 0;
39267   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
39268     pIn = rowSetEntryMerge(pIn, aBucket[i]);
39269   }
39270   return pIn;
39271 }
39272
39273
39274 /*
39275 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
39276 ** Convert this tree into a linked list connected by the pRight pointers
39277 ** and return pointers to the first and last elements of the new list.
39278 */
39279 static void rowSetTreeToList(
39280   struct RowSetEntry *pIn,         /* Root of the input tree */
39281   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
39282   struct RowSetEntry **ppLast      /* Write tail of the output list here */
39283 ){
39284   assert( pIn!=0 );
39285   if( pIn->pLeft ){
39286     struct RowSetEntry *p;
39287     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
39288     p->pRight = pIn;
39289   }else{
39290     *ppFirst = pIn;
39291   }
39292   if( pIn->pRight ){
39293     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
39294   }else{
39295     *ppLast = pIn;
39296   }
39297   assert( (*ppLast)->pRight==0 );
39298 }
39299
39300
39301 /*
39302 ** Convert a sorted list of elements (connected by pRight) into a binary
39303 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
39304 ** node taken from the head of *ppList.  A depth of 2 means a tree with
39305 ** three nodes.  And so forth.
39306 **
39307 ** Use as many entries from the input list as required and update the
39308 ** *ppList to point to the unused elements of the list.  If the input
39309 ** list contains too few elements, then construct an incomplete tree
39310 ** and leave *ppList set to NULL.
39311 **
39312 ** Return a pointer to the root of the constructed binary tree.
39313 */
39314 static struct RowSetEntry *rowSetNDeepTree(
39315   struct RowSetEntry **ppList,
39316   int iDepth
39317 ){
39318   struct RowSetEntry *p;         /* Root of the new tree */
39319   struct RowSetEntry *pLeft;     /* Left subtree */
39320   if( *ppList==0 ){
39321     return 0;
39322   }
39323   if( iDepth==1 ){
39324     p = *ppList;
39325     *ppList = p->pRight;
39326     p->pLeft = p->pRight = 0;
39327     return p;
39328   }
39329   pLeft = rowSetNDeepTree(ppList, iDepth-1);
39330   p = *ppList;
39331   if( p==0 ){
39332     return pLeft;
39333   }
39334   p->pLeft = pLeft;
39335   *ppList = p->pRight;
39336   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
39337   return p;
39338 }
39339
39340 /*
39341 ** Convert a sorted list of elements into a binary tree. Make the tree
39342 ** as deep as it needs to be in order to contain the entire list.
39343 */
39344 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
39345   int iDepth;           /* Depth of the tree so far */
39346   struct RowSetEntry *p;       /* Current tree root */
39347   struct RowSetEntry *pLeft;   /* Left subtree */
39348
39349   assert( pList!=0 );
39350   p = pList;
39351   pList = p->pRight;
39352   p->pLeft = p->pRight = 0;
39353   for(iDepth=1; pList; iDepth++){
39354     pLeft = p;
39355     p = pList;
39356     pList = p->pRight;
39357     p->pLeft = pLeft;
39358     p->pRight = rowSetNDeepTree(&pList, iDepth);
39359   }
39360   return p;
39361 }
39362
39363 /*
39364 ** Take all the entries on p->pEntry and on the trees in p->pForest and
39365 ** sort them all together into one big ordered list on p->pEntry.
39366 **
39367 ** This routine should only be called once in the life of a RowSet.
39368 */
39369 static void rowSetToList(RowSet *p){
39370
39371   /* This routine is called only once */
39372   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
39373
39374   if( (p->rsFlags & ROWSET_SORTED)==0 ){
39375     p->pEntry = rowSetEntrySort(p->pEntry);
39376   }
39377
39378   /* While this module could theoretically support it, sqlite3RowSetNext()
39379   ** is never called after sqlite3RowSetText() for the same RowSet.  So
39380   ** there is never a forest to deal with.  Should this change, simply
39381   ** remove the assert() and the #if 0. */
39382   assert( p->pForest==0 );
39383 #if 0
39384   while( p->pForest ){
39385     struct RowSetEntry *pTree = p->pForest->pLeft;
39386     if( pTree ){
39387       struct RowSetEntry *pHead, *pTail;
39388       rowSetTreeToList(pTree, &pHead, &pTail);
39389       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
39390     }
39391     p->pForest = p->pForest->pRight;
39392   }
39393 #endif
39394   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
39395 }
39396
39397 /*
39398 ** Extract the smallest element from the RowSet.
39399 ** Write the element into *pRowid.  Return 1 on success.  Return
39400 ** 0 if the RowSet is already empty.
39401 **
39402 ** After this routine has been called, the sqlite3RowSetInsert()
39403 ** routine may not be called again.
39404 */
39405 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
39406   assert( p!=0 );
39407
39408   /* Merge the forest into a single sorted list on first call */
39409   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
39410
39411   /* Return the next entry on the list */
39412   if( p->pEntry ){
39413     *pRowid = p->pEntry->v;
39414     p->pEntry = p->pEntry->pRight;
39415     if( p->pEntry==0 ){
39416       sqlite3RowSetClear(p);
39417     }
39418     return 1;
39419   }else{
39420     return 0;
39421   }
39422 }
39423
39424 /*
39425 ** Check to see if element iRowid was inserted into the rowset as
39426 ** part of any insert batch prior to iBatch.  Return 1 or 0.
39427 **
39428 ** If this is the first test of a new batch and if there exist entires
39429 ** on pRowSet->pEntry, then sort those entires into the forest at
39430 ** pRowSet->pForest so that they can be tested.
39431 */
39432 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
39433   struct RowSetEntry *p, *pTree;
39434
39435   /* This routine is never called after sqlite3RowSetNext() */
39436   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
39437
39438   /* Sort entries into the forest on the first test of a new batch
39439   */
39440   if( iBatch!=pRowSet->iBatch ){
39441     p = pRowSet->pEntry;
39442     if( p ){
39443       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
39444       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
39445         p = rowSetEntrySort(p);
39446       }
39447       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39448         ppPrevTree = &pTree->pRight;
39449         if( pTree->pLeft==0 ){
39450           pTree->pLeft = rowSetListToTree(p);
39451           break;
39452         }else{
39453           struct RowSetEntry *pAux, *pTail;
39454           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
39455           pTree->pLeft = 0;
39456           p = rowSetEntryMerge(pAux, p);
39457         }
39458       }
39459       if( pTree==0 ){
39460         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
39461         if( pTree ){
39462           pTree->v = 0;
39463           pTree->pRight = 0;
39464           pTree->pLeft = rowSetListToTree(p);
39465         }
39466       }
39467       pRowSet->pEntry = 0;
39468       pRowSet->pLast = 0;
39469       pRowSet->rsFlags |= ROWSET_SORTED;
39470     }
39471     pRowSet->iBatch = iBatch;
39472   }
39473
39474   /* Test to see if the iRowid value appears anywhere in the forest.
39475   ** Return 1 if it does and 0 if not.
39476   */
39477   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39478     p = pTree->pLeft;
39479     while( p ){
39480       if( p->v<iRowid ){
39481         p = p->pRight;
39482       }else if( p->v>iRowid ){
39483         p = p->pLeft;
39484       }else{
39485         return 1;
39486       }
39487     }
39488   }
39489   return 0;
39490 }
39491
39492 /************** End of rowset.c **********************************************/
39493 /************** Begin file pager.c *******************************************/
39494 /*
39495 ** 2001 September 15
39496 **
39497 ** The author disclaims copyright to this source code.  In place of
39498 ** a legal notice, here is a blessing:
39499 **
39500 **    May you do good and not evil.
39501 **    May you find forgiveness for yourself and forgive others.
39502 **    May you share freely, never taking more than you give.
39503 **
39504 *************************************************************************
39505 ** This is the implementation of the page cache subsystem or "pager".
39506 **
39507 ** The pager is used to access a database disk file.  It implements
39508 ** atomic commit and rollback through the use of a journal file that
39509 ** is separate from the database file.  The pager also implements file
39510 ** locking to prevent two processes from writing the same database
39511 ** file simultaneously, or one process from reading the database while
39512 ** another is writing.
39513 */
39514 #ifndef SQLITE_OMIT_DISKIO
39515 /************** Include wal.h in the middle of pager.c ***********************/
39516 /************** Begin file wal.h *********************************************/
39517 /*
39518 ** 2010 February 1
39519 **
39520 ** The author disclaims copyright to this source code.  In place of
39521 ** a legal notice, here is a blessing:
39522 **
39523 **    May you do good and not evil.
39524 **    May you find forgiveness for yourself and forgive others.
39525 **    May you share freely, never taking more than you give.
39526 **
39527 *************************************************************************
39528 ** This header file defines the interface to the write-ahead logging
39529 ** system. Refer to the comments below and the header comment attached to
39530 ** the implementation of each function in log.c for further details.
39531 */
39532
39533 #ifndef _WAL_H_
39534 #define _WAL_H_
39535
39536
39537 /* Additional values that can be added to the sync_flags argument of
39538 ** sqlite3WalFrames():
39539 */
39540 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
39541 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
39542
39543 #ifdef SQLITE_OMIT_WAL
39544 # define sqlite3WalOpen(x,y,z)                   0
39545 # define sqlite3WalLimit(x,y)
39546 # define sqlite3WalClose(w,x,y,z)                0
39547 # define sqlite3WalBeginReadTransaction(y,z)     0
39548 # define sqlite3WalEndReadTransaction(z)
39549 # define sqlite3WalRead(v,w,x,y,z)               0
39550 # define sqlite3WalDbsize(y)                     0
39551 # define sqlite3WalBeginWriteTransaction(y)      0
39552 # define sqlite3WalEndWriteTransaction(x)        0
39553 # define sqlite3WalUndo(x,y,z)                   0
39554 # define sqlite3WalSavepoint(y,z)
39555 # define sqlite3WalSavepointUndo(y,z)            0
39556 # define sqlite3WalFrames(u,v,w,x,y,z)           0
39557 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
39558 # define sqlite3WalCallback(z)                   0
39559 # define sqlite3WalExclusiveMode(y,z)            0
39560 # define sqlite3WalHeapMemory(z)                 0
39561 # define sqlite3WalFramesize(z)                  0
39562 #else
39563
39564 #define WAL_SAVEPOINT_NDATA 4
39565
39566 /* Connection to a write-ahead log (WAL) file.
39567 ** There is one object of this type for each pager.
39568 */
39569 typedef struct Wal Wal;
39570
39571 /* Open and close a connection to a write-ahead log. */
39572 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
39573 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
39574
39575 /* Set the limiting size of a WAL file. */
39576 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
39577
39578 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
39579 ** snapshot is like a read-transaction.  It is the state of the database
39580 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
39581 ** preserves the current state even if the other threads or processes
39582 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
39583 ** transaction and releases the lock.
39584 */
39585 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
39586 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
39587
39588 /* Read a page from the write-ahead log, if it is present. */
39589 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
39590
39591 /* If the WAL is not empty, return the size of the database. */
39592 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
39593
39594 /* Obtain or release the WRITER lock. */
39595 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
39596 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
39597
39598 /* Undo any frames written (but not committed) to the log */
39599 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
39600
39601 /* Return an integer that records the current (uncommitted) write
39602 ** position in the WAL */
39603 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
39604
39605 /* Move the write position of the WAL back to iFrame.  Called in
39606 ** response to a ROLLBACK TO command. */
39607 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
39608
39609 /* Write a frame or frames to the log. */
39610 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
39611
39612 /* Copy pages from the log to the database file */
39613 SQLITE_PRIVATE int sqlite3WalCheckpoint(
39614   Wal *pWal,                      /* Write-ahead log connection */
39615   int eMode,                      /* One of PASSIVE, FULL and RESTART */
39616   int (*xBusy)(void*),            /* Function to call when busy */
39617   void *pBusyArg,                 /* Context argument for xBusyHandler */
39618   int sync_flags,                 /* Flags to sync db file with (or 0) */
39619   int nBuf,                       /* Size of buffer nBuf */
39620   u8 *zBuf,                       /* Temporary buffer to use */
39621   int *pnLog,                     /* OUT: Number of frames in WAL */
39622   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
39623 );
39624
39625 /* Return the value to pass to a sqlite3_wal_hook callback, the
39626 ** number of frames in the WAL at the point of the last commit since
39627 ** sqlite3WalCallback() was called.  If no commits have occurred since
39628 ** the last call, then return 0.
39629 */
39630 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
39631
39632 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
39633 ** by the pager layer on the database file.
39634 */
39635 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
39636
39637 /* Return true if the argument is non-NULL and the WAL module is using
39638 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
39639 ** WAL module is using shared-memory, return false.
39640 */
39641 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
39642
39643 #ifdef SQLITE_ENABLE_ZIPVFS
39644 /* If the WAL file is not empty, return the number of bytes of content
39645 ** stored in each frame (i.e. the db page-size when the WAL was created).
39646 */
39647 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
39648 #endif
39649
39650 #endif /* ifndef SQLITE_OMIT_WAL */
39651 #endif /* _WAL_H_ */
39652
39653 /************** End of wal.h *************************************************/
39654 /************** Continuing where we left off in pager.c **********************/
39655
39656
39657 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
39658 **
39659 ** This comment block describes invariants that hold when using a rollback
39660 ** journal.  These invariants do not apply for journal_mode=WAL,
39661 ** journal_mode=MEMORY, or journal_mode=OFF.
39662 **
39663 ** Within this comment block, a page is deemed to have been synced
39664 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
39665 ** Otherwise, the page is not synced until the xSync method of the VFS
39666 ** is called successfully on the file containing the page.
39667 **
39668 ** Definition:  A page of the database file is said to be "overwriteable" if
39669 ** one or more of the following are true about the page:
39670 **
39671 **     (a)  The original content of the page as it was at the beginning of
39672 **          the transaction has been written into the rollback journal and
39673 **          synced.
39674 **
39675 **     (b)  The page was a freelist leaf page at the start of the transaction.
39676 **
39677 **     (c)  The page number is greater than the largest page that existed in
39678 **          the database file at the start of the transaction.
39679 **
39680 ** (1) A page of the database file is never overwritten unless one of the
39681 **     following are true:
39682 **
39683 **     (a) The page and all other pages on the same sector are overwriteable.
39684 **
39685 **     (b) The atomic page write optimization is enabled, and the entire
39686 **         transaction other than the update of the transaction sequence
39687 **         number consists of a single page change.
39688 **
39689 ** (2) The content of a page written into the rollback journal exactly matches
39690 **     both the content in the database when the rollback journal was written
39691 **     and the content in the database at the beginning of the current
39692 **     transaction.
39693 **
39694 ** (3) Writes to the database file are an integer multiple of the page size
39695 **     in length and are aligned on a page boundary.
39696 **
39697 ** (4) Reads from the database file are either aligned on a page boundary and
39698 **     an integer multiple of the page size in length or are taken from the
39699 **     first 100 bytes of the database file.
39700 **
39701 ** (5) All writes to the database file are synced prior to the rollback journal
39702 **     being deleted, truncated, or zeroed.
39703 **
39704 ** (6) If a master journal file is used, then all writes to the database file
39705 **     are synced prior to the master journal being deleted.
39706 **
39707 ** Definition: Two databases (or the same database at two points it time)
39708 ** are said to be "logically equivalent" if they give the same answer to
39709 ** all queries.  Note in particular the content of freelist leaf
39710 ** pages can be changed arbitarily without effecting the logical equivalence
39711 ** of the database.
39712 **
39713 ** (7) At any time, if any subset, including the empty set and the total set,
39714 **     of the unsynced changes to a rollback journal are removed and the
39715 **     journal is rolled back, the resulting database file will be logical
39716 **     equivalent to the database file at the beginning of the transaction.
39717 **
39718 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
39719 **     is called to restore the database file to the same size it was at
39720 **     the beginning of the transaction.  (In some VFSes, the xTruncate
39721 **     method is a no-op, but that does not change the fact the SQLite will
39722 **     invoke it.)
39723 **
39724 ** (9) Whenever the database file is modified, at least one bit in the range
39725 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
39726 **     the EXCLUSIVE lock, thus signaling other connections on the same
39727 **     database to flush their caches.
39728 **
39729 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
39730 **      than one billion transactions.
39731 **
39732 ** (11) A database file is well-formed at the beginning and at the conclusion
39733 **      of every transaction.
39734 **
39735 ** (12) An EXCLUSIVE lock is held on the database file when writing to
39736 **      the database file.
39737 **
39738 ** (13) A SHARED lock is held on the database file while reading any
39739 **      content out of the database file.
39740 **
39741 ******************************************************************************/
39742
39743 /*
39744 ** Macros for troubleshooting.  Normally turned off
39745 */
39746 #if 0
39747 int sqlite3PagerTrace=1;  /* True to enable tracing */
39748 #define sqlite3DebugPrintf printf
39749 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
39750 #else
39751 #define PAGERTRACE(X)
39752 #endif
39753
39754 /*
39755 ** The following two macros are used within the PAGERTRACE() macros above
39756 ** to print out file-descriptors.
39757 **
39758 ** PAGERID() takes a pointer to a Pager struct as its argument. The
39759 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
39760 ** struct as its argument.
39761 */
39762 #define PAGERID(p) ((int)(p->fd))
39763 #define FILEHANDLEID(fd) ((int)fd)
39764
39765 /*
39766 ** The Pager.eState variable stores the current 'state' of a pager. A
39767 ** pager may be in any one of the seven states shown in the following
39768 ** state diagram.
39769 **
39770 **                            OPEN <------+------+
39771 **                              |         |      |
39772 **                              V         |      |
39773 **               +---------> READER-------+      |
39774 **               |              |                |
39775 **               |              V                |
39776 **               |<-------WRITER_LOCKED------> ERROR
39777 **               |              |                ^
39778 **               |              V                |
39779 **               |<------WRITER_CACHEMOD-------->|
39780 **               |              |                |
39781 **               |              V                |
39782 **               |<-------WRITER_DBMOD---------->|
39783 **               |              |                |
39784 **               |              V                |
39785 **               +<------WRITER_FINISHED-------->+
39786 **
39787 **
39788 ** List of state transitions and the C [function] that performs each:
39789 **
39790 **   OPEN              -> READER              [sqlite3PagerSharedLock]
39791 **   READER            -> OPEN                [pager_unlock]
39792 **
39793 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
39794 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
39795 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
39796 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
39797 **   WRITER_***        -> READER              [pager_end_transaction]
39798 **
39799 **   WRITER_***        -> ERROR               [pager_error]
39800 **   ERROR             -> OPEN                [pager_unlock]
39801 **
39802 **
39803 **  OPEN:
39804 **
39805 **    The pager starts up in this state. Nothing is guaranteed in this
39806 **    state - the file may or may not be locked and the database size is
39807 **    unknown. The database may not be read or written.
39808 **
39809 **    * No read or write transaction is active.
39810 **    * Any lock, or no lock at all, may be held on the database file.
39811 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
39812 **
39813 **  READER:
39814 **
39815 **    In this state all the requirements for reading the database in
39816 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
39817 **    was) in exclusive-locking mode, a user-level read transaction is
39818 **    open. The database size is known in this state.
39819 **
39820 **    A connection running with locking_mode=normal enters this state when
39821 **    it opens a read-transaction on the database and returns to state
39822 **    OPEN after the read-transaction is completed. However a connection
39823 **    running in locking_mode=exclusive (including temp databases) remains in
39824 **    this state even after the read-transaction is closed. The only way
39825 **    a locking_mode=exclusive connection can transition from READER to OPEN
39826 **    is via the ERROR state (see below).
39827 **
39828 **    * A read transaction may be active (but a write-transaction cannot).
39829 **    * A SHARED or greater lock is held on the database file.
39830 **    * The dbSize variable may be trusted (even if a user-level read
39831 **      transaction is not active). The dbOrigSize and dbFileSize variables
39832 **      may not be trusted at this point.
39833 **    * If the database is a WAL database, then the WAL connection is open.
39834 **    * Even if a read-transaction is not open, it is guaranteed that
39835 **      there is no hot-journal in the file-system.
39836 **
39837 **  WRITER_LOCKED:
39838 **
39839 **    The pager moves to this state from READER when a write-transaction
39840 **    is first opened on the database. In WRITER_LOCKED state, all locks
39841 **    required to start a write-transaction are held, but no actual
39842 **    modifications to the cache or database have taken place.
39843 **
39844 **    In rollback mode, a RESERVED or (if the transaction was opened with
39845 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
39846 **    moving to this state, but the journal file is not written to or opened
39847 **    to in this state. If the transaction is committed or rolled back while
39848 **    in WRITER_LOCKED state, all that is required is to unlock the database
39849 **    file.
39850 **
39851 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
39852 **    If the connection is running with locking_mode=exclusive, an attempt
39853 **    is made to obtain an EXCLUSIVE lock on the database file.
39854 **
39855 **    * A write transaction is active.
39856 **    * If the connection is open in rollback-mode, a RESERVED or greater
39857 **      lock is held on the database file.
39858 **    * If the connection is open in WAL-mode, a WAL write transaction
39859 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
39860 **      called).
39861 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
39862 **    * The contents of the pager cache have not been modified.
39863 **    * The journal file may or may not be open.
39864 **    * Nothing (not even the first header) has been written to the journal.
39865 **
39866 **  WRITER_CACHEMOD:
39867 **
39868 **    A pager moves from WRITER_LOCKED state to this state when a page is
39869 **    first modified by the upper layer. In rollback mode the journal file
39870 **    is opened (if it is not already open) and a header written to the
39871 **    start of it. The database file on disk has not been modified.
39872 **
39873 **    * A write transaction is active.
39874 **    * A RESERVED or greater lock is held on the database file.
39875 **    * The journal file is open and the first header has been written
39876 **      to it, but the header has not been synced to disk.
39877 **    * The contents of the page cache have been modified.
39878 **
39879 **  WRITER_DBMOD:
39880 **
39881 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
39882 **    when it modifies the contents of the database file. WAL connections
39883 **    never enter this state (since they do not modify the database file,
39884 **    just the log file).
39885 **
39886 **    * A write transaction is active.
39887 **    * An EXCLUSIVE or greater lock is held on the database file.
39888 **    * The journal file is open and the first header has been written
39889 **      and synced to disk.
39890 **    * The contents of the page cache have been modified (and possibly
39891 **      written to disk).
39892 **
39893 **  WRITER_FINISHED:
39894 **
39895 **    It is not possible for a WAL connection to enter this state.
39896 **
39897 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
39898 **    state after the entire transaction has been successfully written into the
39899 **    database file. In this state the transaction may be committed simply
39900 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
39901 **    not possible to modify the database further. At this point, the upper
39902 **    layer must either commit or rollback the transaction.
39903 **
39904 **    * A write transaction is active.
39905 **    * An EXCLUSIVE or greater lock is held on the database file.
39906 **    * All writing and syncing of journal and database data has finished.
39907 **      If no error occured, all that remains is to finalize the journal to
39908 **      commit the transaction. If an error did occur, the caller will need
39909 **      to rollback the transaction.
39910 **
39911 **  ERROR:
39912 **
39913 **    The ERROR state is entered when an IO or disk-full error (including
39914 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
39915 **    difficult to be sure that the in-memory pager state (cache contents,
39916 **    db size etc.) are consistent with the contents of the file-system.
39917 **
39918 **    Temporary pager files may enter the ERROR state, but in-memory pagers
39919 **    cannot.
39920 **
39921 **    For example, if an IO error occurs while performing a rollback,
39922 **    the contents of the page-cache may be left in an inconsistent state.
39923 **    At this point it would be dangerous to change back to READER state
39924 **    (as usually happens after a rollback). Any subsequent readers might
39925 **    report database corruption (due to the inconsistent cache), and if
39926 **    they upgrade to writers, they may inadvertently corrupt the database
39927 **    file. To avoid this hazard, the pager switches into the ERROR state
39928 **    instead of READER following such an error.
39929 **
39930 **    Once it has entered the ERROR state, any attempt to use the pager
39931 **    to read or write data returns an error. Eventually, once all
39932 **    outstanding transactions have been abandoned, the pager is able to
39933 **    transition back to OPEN state, discarding the contents of the
39934 **    page-cache and any other in-memory state at the same time. Everything
39935 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
39936 **    when a read-transaction is next opened on the pager (transitioning
39937 **    the pager into READER state). At that point the system has recovered
39938 **    from the error.
39939 **
39940 **    Specifically, the pager jumps into the ERROR state if:
39941 **
39942 **      1. An error occurs while attempting a rollback. This happens in
39943 **         function sqlite3PagerRollback().
39944 **
39945 **      2. An error occurs while attempting to finalize a journal file
39946 **         following a commit in function sqlite3PagerCommitPhaseTwo().
39947 **
39948 **      3. An error occurs while attempting to write to the journal or
39949 **         database file in function pagerStress() in order to free up
39950 **         memory.
39951 **
39952 **    In other cases, the error is returned to the b-tree layer. The b-tree
39953 **    layer then attempts a rollback operation. If the error condition
39954 **    persists, the pager enters the ERROR state via condition (1) above.
39955 **
39956 **    Condition (3) is necessary because it can be triggered by a read-only
39957 **    statement executed within a transaction. In this case, if the error
39958 **    code were simply returned to the user, the b-tree layer would not
39959 **    automatically attempt a rollback, as it assumes that an error in a
39960 **    read-only statement cannot leave the pager in an internally inconsistent
39961 **    state.
39962 **
39963 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
39964 **    * There are one or more outstanding references to pages (after the
39965 **      last reference is dropped the pager should move back to OPEN state).
39966 **    * The pager is not an in-memory pager.
39967 **
39968 **
39969 ** Notes:
39970 **
39971 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
39972 **     connection is open in WAL mode. A WAL connection is always in one
39973 **     of the first four states.
39974 **
39975 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
39976 **     state. There are two exceptions: immediately after exclusive-mode has
39977 **     been turned on (and before any read or write transactions are
39978 **     executed), and when the pager is leaving the "error state".
39979 **
39980 **   * See also: assert_pager_state().
39981 */
39982 #define PAGER_OPEN                  0
39983 #define PAGER_READER                1
39984 #define PAGER_WRITER_LOCKED         2
39985 #define PAGER_WRITER_CACHEMOD       3
39986 #define PAGER_WRITER_DBMOD          4
39987 #define PAGER_WRITER_FINISHED       5
39988 #define PAGER_ERROR                 6
39989
39990 /*
39991 ** The Pager.eLock variable is almost always set to one of the
39992 ** following locking-states, according to the lock currently held on
39993 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39994 ** This variable is kept up to date as locks are taken and released by
39995 ** the pagerLockDb() and pagerUnlockDb() wrappers.
39996 **
39997 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
39998 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
39999 ** the operation was successful. In these circumstances pagerLockDb() and
40000 ** pagerUnlockDb() take a conservative approach - eLock is always updated
40001 ** when unlocking the file, and only updated when locking the file if the
40002 ** VFS call is successful. This way, the Pager.eLock variable may be set
40003 ** to a less exclusive (lower) value than the lock that is actually held
40004 ** at the system level, but it is never set to a more exclusive value.
40005 **
40006 ** This is usually safe. If an xUnlock fails or appears to fail, there may
40007 ** be a few redundant xLock() calls or a lock may be held for longer than
40008 ** required, but nothing really goes wrong.
40009 **
40010 ** The exception is when the database file is unlocked as the pager moves
40011 ** from ERROR to OPEN state. At this point there may be a hot-journal file
40012 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
40013 ** transition, by the same pager or any other). If the call to xUnlock()
40014 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
40015 ** can confuse the call to xCheckReservedLock() call made later as part
40016 ** of hot-journal detection.
40017 **
40018 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
40019 ** lock held by this process or any others". So xCheckReservedLock may
40020 ** return true because the caller itself is holding an EXCLUSIVE lock (but
40021 ** doesn't know it because of a previous error in xUnlock). If this happens
40022 ** a hot-journal may be mistaken for a journal being created by an active
40023 ** transaction in another process, causing SQLite to read from the database
40024 ** without rolling it back.
40025 **
40026 ** To work around this, if a call to xUnlock() fails when unlocking the
40027 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
40028 ** is only changed back to a real locking state after a successful call
40029 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
40030 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
40031 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
40032 ** lock on the database file before attempting to roll it back. See function
40033 ** PagerSharedLock() for more detail.
40034 **
40035 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
40036 ** PAGER_OPEN state.
40037 */
40038 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
40039
40040 /*
40041 ** A macro used for invoking the codec if there is one
40042 */
40043 #ifdef SQLITE_HAS_CODEC
40044 # define CODEC1(P,D,N,X,E) \
40045     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
40046 # define CODEC2(P,D,N,X,E,O) \
40047     if( P->xCodec==0 ){ O=(char*)D; }else \
40048     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
40049 #else
40050 # define CODEC1(P,D,N,X,E)   /* NO-OP */
40051 # define CODEC2(P,D,N,X,E,O) O=(char*)D
40052 #endif
40053
40054 /*
40055 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
40056 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
40057 ** This could conceivably cause corruption following a power failure on
40058 ** such a system. This is currently an undocumented limit.
40059 */
40060 #define MAX_SECTOR_SIZE 0x10000
40061
40062 /*
40063 ** An instance of the following structure is allocated for each active
40064 ** savepoint and statement transaction in the system. All such structures
40065 ** are stored in the Pager.aSavepoint[] array, which is allocated and
40066 ** resized using sqlite3Realloc().
40067 **
40068 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
40069 ** set to 0. If a journal-header is written into the main journal while
40070 ** the savepoint is active, then iHdrOffset is set to the byte offset
40071 ** immediately following the last journal record written into the main
40072 ** journal before the journal-header. This is required during savepoint
40073 ** rollback (see pagerPlaybackSavepoint()).
40074 */
40075 typedef struct PagerSavepoint PagerSavepoint;
40076 struct PagerSavepoint {
40077   i64 iOffset;                 /* Starting offset in main journal */
40078   i64 iHdrOffset;              /* See above */
40079   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
40080   Pgno nOrig;                  /* Original number of pages in file */
40081   Pgno iSubRec;                /* Index of first record in sub-journal */
40082 #ifndef SQLITE_OMIT_WAL
40083   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
40084 #endif
40085 };
40086
40087 /*
40088 ** A open page cache is an instance of struct Pager. A description of
40089 ** some of the more important member variables follows:
40090 **
40091 ** eState
40092 **
40093 **   The current 'state' of the pager object. See the comment and state
40094 **   diagram above for a description of the pager state.
40095 **
40096 ** eLock
40097 **
40098 **   For a real on-disk database, the current lock held on the database file -
40099 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
40100 **
40101 **   For a temporary or in-memory database (neither of which require any
40102 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
40103 **   databases always have Pager.exclusiveMode==1, this tricks the pager
40104 **   logic into thinking that it already has all the locks it will ever
40105 **   need (and no reason to release them).
40106 **
40107 **   In some (obscure) circumstances, this variable may also be set to
40108 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
40109 **   details.
40110 **
40111 ** changeCountDone
40112 **
40113 **   This boolean variable is used to make sure that the change-counter
40114 **   (the 4-byte header field at byte offset 24 of the database file) is
40115 **   not updated more often than necessary.
40116 **
40117 **   It is set to true when the change-counter field is updated, which
40118 **   can only happen if an exclusive lock is held on the database file.
40119 **   It is cleared (set to false) whenever an exclusive lock is
40120 **   relinquished on the database file. Each time a transaction is committed,
40121 **   The changeCountDone flag is inspected. If it is true, the work of
40122 **   updating the change-counter is omitted for the current transaction.
40123 **
40124 **   This mechanism means that when running in exclusive mode, a connection
40125 **   need only update the change-counter once, for the first transaction
40126 **   committed.
40127 **
40128 ** setMaster
40129 **
40130 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
40131 **   (or may not) specify a master-journal name to be written into the
40132 **   journal file before it is synced to disk.
40133 **
40134 **   Whether or not a journal file contains a master-journal pointer affects
40135 **   the way in which the journal file is finalized after the transaction is
40136 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
40137 **   If a journal file does not contain a master-journal pointer, it is
40138 **   finalized by overwriting the first journal header with zeroes. If
40139 **   it does contain a master-journal pointer the journal file is finalized
40140 **   by truncating it to zero bytes, just as if the connection were
40141 **   running in "journal_mode=truncate" mode.
40142 **
40143 **   Journal files that contain master journal pointers cannot be finalized
40144 **   simply by overwriting the first journal-header with zeroes, as the
40145 **   master journal pointer could interfere with hot-journal rollback of any
40146 **   subsequently interrupted transaction that reuses the journal file.
40147 **
40148 **   The flag is cleared as soon as the journal file is finalized (either
40149 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
40150 **   journal file from being successfully finalized, the setMaster flag
40151 **   is cleared anyway (and the pager will move to ERROR state).
40152 **
40153 ** doNotSpill, doNotSyncSpill
40154 **
40155 **   These two boolean variables control the behaviour of cache-spills
40156 **   (calls made by the pcache module to the pagerStress() routine to
40157 **   write cached data to the file-system in order to free up memory).
40158 **
40159 **   When doNotSpill is non-zero, writing to the database from pagerStress()
40160 **   is disabled altogether. This is done in a very obscure case that
40161 **   comes up during savepoint rollback that requires the pcache module
40162 **   to allocate a new page to prevent the journal file from being written
40163 **   while it is being traversed by code in pager_playback().
40164 **
40165 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
40166 **   is permitted, but syncing the journal file is not. This flag is set
40167 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
40168 **   the database page-size in order to prevent a journal sync from happening
40169 **   in between the journalling of two pages on the same sector.
40170 **
40171 ** subjInMemory
40172 **
40173 **   This is a boolean variable. If true, then any required sub-journal
40174 **   is opened as an in-memory journal file. If false, then in-memory
40175 **   sub-journals are only used for in-memory pager files.
40176 **
40177 **   This variable is updated by the upper layer each time a new
40178 **   write-transaction is opened.
40179 **
40180 ** dbSize, dbOrigSize, dbFileSize
40181 **
40182 **   Variable dbSize is set to the number of pages in the database file.
40183 **   It is valid in PAGER_READER and higher states (all states except for
40184 **   OPEN and ERROR).
40185 **
40186 **   dbSize is set based on the size of the database file, which may be
40187 **   larger than the size of the database (the value stored at offset
40188 **   28 of the database header by the btree). If the size of the file
40189 **   is not an integer multiple of the page-size, the value stored in
40190 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
40191 **   Except, any file that is greater than 0 bytes in size is considered
40192 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
40193 **   to dbSize==1).
40194 **
40195 **   During a write-transaction, if pages with page-numbers greater than
40196 **   dbSize are modified in the cache, dbSize is updated accordingly.
40197 **   Similarly, if the database is truncated using PagerTruncateImage(),
40198 **   dbSize is updated.
40199 **
40200 **   Variables dbOrigSize and dbFileSize are valid in states
40201 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
40202 **   variable at the start of the transaction. It is used during rollback,
40203 **   and to determine whether or not pages need to be journalled before
40204 **   being modified.
40205 **
40206 **   Throughout a write-transaction, dbFileSize contains the size of
40207 **   the file on disk in pages. It is set to a copy of dbSize when the
40208 **   write-transaction is first opened, and updated when VFS calls are made
40209 **   to write or truncate the database file on disk.
40210 **
40211 **   The only reason the dbFileSize variable is required is to suppress
40212 **   unnecessary calls to xTruncate() after committing a transaction. If,
40213 **   when a transaction is committed, the dbFileSize variable indicates
40214 **   that the database file is larger than the database image (Pager.dbSize),
40215 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
40216 **   to measure the database file on disk, and then truncates it if required.
40217 **   dbFileSize is not used when rolling back a transaction. In this case
40218 **   pager_truncate() is called unconditionally (which means there may be
40219 **   a call to xFilesize() that is not strictly required). In either case,
40220 **   pager_truncate() may cause the file to become smaller or larger.
40221 **
40222 ** dbHintSize
40223 **
40224 **   The dbHintSize variable is used to limit the number of calls made to
40225 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
40226 **
40227 **   dbHintSize is set to a copy of the dbSize variable when a
40228 **   write-transaction is opened (at the same time as dbFileSize and
40229 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
40230 **   dbHintSize is increased to the number of pages that correspond to the
40231 **   size-hint passed to the method call. See pager_write_pagelist() for
40232 **   details.
40233 **
40234 ** errCode
40235 **
40236 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
40237 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
40238 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
40239 **   sub-codes.
40240 */
40241 struct Pager {
40242   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
40243   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
40244   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
40245   u8 useJournal;              /* Use a rollback journal on this file */
40246   u8 noSync;                  /* Do not sync the journal if true */
40247   u8 fullSync;                /* Do extra syncs of the journal for robustness */
40248   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
40249   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
40250   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
40251   u8 tempFile;                /* zFilename is a temporary file */
40252   u8 readOnly;                /* True for a read-only database */
40253   u8 memDb;                   /* True to inhibit all file I/O */
40254
40255   /**************************************************************************
40256   ** The following block contains those class members that change during
40257   ** routine opertion.  Class members not in this block are either fixed
40258   ** when the pager is first created or else only change when there is a
40259   ** significant mode change (such as changing the page_size, locking_mode,
40260   ** or the journal_mode).  From another view, these class members describe
40261   ** the "state" of the pager, while other class members describe the
40262   ** "configuration" of the pager.
40263   */
40264   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
40265   u8 eLock;                   /* Current lock held on database file */
40266   u8 changeCountDone;         /* Set after incrementing the change-counter */
40267   u8 setMaster;               /* True if a m-j name has been written to jrnl */
40268   u8 doNotSpill;              /* Do not spill the cache when non-zero */
40269   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
40270   u8 subjInMemory;            /* True to use in-memory sub-journals */
40271   Pgno dbSize;                /* Number of pages in the database */
40272   Pgno dbOrigSize;            /* dbSize before the current transaction */
40273   Pgno dbFileSize;            /* Number of pages in the database file */
40274   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
40275   int errCode;                /* One of several kinds of errors */
40276   int nRec;                   /* Pages journalled since last j-header written */
40277   u32 cksumInit;              /* Quasi-random value added to every checksum */
40278   u32 nSubRec;                /* Number of records written to sub-journal */
40279   Bitvec *pInJournal;         /* One bit for each page in the database file */
40280   sqlite3_file *fd;           /* File descriptor for database */
40281   sqlite3_file *jfd;          /* File descriptor for main journal */
40282   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
40283   i64 journalOff;             /* Current write offset in the journal file */
40284   i64 journalHdr;             /* Byte offset to previous journal header */
40285   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
40286   PagerSavepoint *aSavepoint; /* Array of active savepoints */
40287   int nSavepoint;             /* Number of elements in aSavepoint[] */
40288   char dbFileVers[16];        /* Changes whenever database file changes */
40289   /*
40290   ** End of the routinely-changing class members
40291   ***************************************************************************/
40292
40293   u16 nExtra;                 /* Add this many bytes to each in-memory page */
40294   i16 nReserve;               /* Number of unused bytes at end of each page */
40295   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
40296   u32 sectorSize;             /* Assumed sector size during rollback */
40297   int pageSize;               /* Number of bytes in a page */
40298   Pgno mxPgno;                /* Maximum allowed size of the database */
40299   i64 journalSizeLimit;       /* Size limit for persistent journal files */
40300   char *zFilename;            /* Name of the database file */
40301   char *zJournal;             /* Name of the journal file */
40302   int (*xBusyHandler)(void*); /* Function to call when busy */
40303   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
40304   int aStat[3];               /* Total cache hits, misses and writes */
40305 #ifdef SQLITE_TEST
40306   int nRead;                  /* Database pages read */
40307 #endif
40308   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
40309 #ifdef SQLITE_HAS_CODEC
40310   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
40311   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
40312   void (*xCodecFree)(void*);             /* Destructor for the codec */
40313   void *pCodec;               /* First argument to xCodec... methods */
40314 #endif
40315   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
40316   PCache *pPCache;            /* Pointer to page cache object */
40317 #ifndef SQLITE_OMIT_WAL
40318   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
40319   char *zWal;                 /* File name for write-ahead log */
40320 #endif
40321 };
40322
40323 /*
40324 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
40325 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
40326 ** or CACHE_WRITE to sqlite3_db_status().
40327 */
40328 #define PAGER_STAT_HIT   0
40329 #define PAGER_STAT_MISS  1
40330 #define PAGER_STAT_WRITE 2
40331
40332 /*
40333 ** The following global variables hold counters used for
40334 ** testing purposes only.  These variables do not exist in
40335 ** a non-testing build.  These variables are not thread-safe.
40336 */
40337 #ifdef SQLITE_TEST
40338 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
40339 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
40340 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
40341 # define PAGER_INCR(v)  v++
40342 #else
40343 # define PAGER_INCR(v)
40344 #endif
40345
40346
40347
40348 /*
40349 ** Journal files begin with the following magic string.  The data
40350 ** was obtained from /dev/random.  It is used only as a sanity check.
40351 **
40352 ** Since version 2.8.0, the journal format contains additional sanity
40353 ** checking information.  If the power fails while the journal is being
40354 ** written, semi-random garbage data might appear in the journal
40355 ** file after power is restored.  If an attempt is then made
40356 ** to roll the journal back, the database could be corrupted.  The additional
40357 ** sanity checking data is an attempt to discover the garbage in the
40358 ** journal and ignore it.
40359 **
40360 ** The sanity checking information for the new journal format consists
40361 ** of a 32-bit checksum on each page of data.  The checksum covers both
40362 ** the page number and the pPager->pageSize bytes of data for the page.
40363 ** This cksum is initialized to a 32-bit random value that appears in the
40364 ** journal file right after the header.  The random initializer is important,
40365 ** because garbage data that appears at the end of a journal is likely
40366 ** data that was once in other files that have now been deleted.  If the
40367 ** garbage data came from an obsolete journal file, the checksums might
40368 ** be correct.  But by initializing the checksum to random value which
40369 ** is different for every journal, we minimize that risk.
40370 */
40371 static const unsigned char aJournalMagic[] = {
40372   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
40373 };
40374
40375 /*
40376 ** The size of the of each page record in the journal is given by
40377 ** the following macro.
40378 */
40379 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
40380
40381 /*
40382 ** The journal header size for this pager. This is usually the same
40383 ** size as a single disk sector. See also setSectorSize().
40384 */
40385 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
40386
40387 /*
40388 ** The macro MEMDB is true if we are dealing with an in-memory database.
40389 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
40390 ** the value of MEMDB will be a constant and the compiler will optimize
40391 ** out code that would never execute.
40392 */
40393 #ifdef SQLITE_OMIT_MEMORYDB
40394 # define MEMDB 0
40395 #else
40396 # define MEMDB pPager->memDb
40397 #endif
40398
40399 /*
40400 ** The maximum legal page number is (2^31 - 1).
40401 */
40402 #define PAGER_MAX_PGNO 2147483647
40403
40404 /*
40405 ** The argument to this macro is a file descriptor (type sqlite3_file*).
40406 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
40407 **
40408 ** This is so that expressions can be written as:
40409 **
40410 **   if( isOpen(pPager->jfd) ){ ...
40411 **
40412 ** instead of
40413 **
40414 **   if( pPager->jfd->pMethods ){ ...
40415 */
40416 #define isOpen(pFd) ((pFd)->pMethods)
40417
40418 /*
40419 ** Return true if this pager uses a write-ahead log instead of the usual
40420 ** rollback journal. Otherwise false.
40421 */
40422 #ifndef SQLITE_OMIT_WAL
40423 static int pagerUseWal(Pager *pPager){
40424   return (pPager->pWal!=0);
40425 }
40426 #else
40427 # define pagerUseWal(x) 0
40428 # define pagerRollbackWal(x) 0
40429 # define pagerWalFrames(v,w,x,y) 0
40430 # define pagerOpenWalIfPresent(z) SQLITE_OK
40431 # define pagerBeginReadTransaction(z) SQLITE_OK
40432 #endif
40433
40434 #ifndef NDEBUG
40435 /*
40436 ** Usage:
40437 **
40438 **   assert( assert_pager_state(pPager) );
40439 **
40440 ** This function runs many asserts to try to find inconsistencies in
40441 ** the internal state of the Pager object.
40442 */
40443 static int assert_pager_state(Pager *p){
40444   Pager *pPager = p;
40445
40446   /* State must be valid. */
40447   assert( p->eState==PAGER_OPEN
40448        || p->eState==PAGER_READER
40449        || p->eState==PAGER_WRITER_LOCKED
40450        || p->eState==PAGER_WRITER_CACHEMOD
40451        || p->eState==PAGER_WRITER_DBMOD
40452        || p->eState==PAGER_WRITER_FINISHED
40453        || p->eState==PAGER_ERROR
40454   );
40455
40456   /* Regardless of the current state, a temp-file connection always behaves
40457   ** as if it has an exclusive lock on the database file. It never updates
40458   ** the change-counter field, so the changeCountDone flag is always set.
40459   */
40460   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
40461   assert( p->tempFile==0 || pPager->changeCountDone );
40462
40463   /* If the useJournal flag is clear, the journal-mode must be "OFF".
40464   ** And if the journal-mode is "OFF", the journal file must not be open.
40465   */
40466   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
40467   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
40468
40469   /* Check that MEMDB implies noSync. And an in-memory journal. Since
40470   ** this means an in-memory pager performs no IO at all, it cannot encounter
40471   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
40472   ** a journal file. (although the in-memory journal implementation may
40473   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
40474   ** is therefore not possible for an in-memory pager to enter the ERROR
40475   ** state.
40476   */
40477   if( MEMDB ){
40478     assert( p->noSync );
40479     assert( p->journalMode==PAGER_JOURNALMODE_OFF
40480          || p->journalMode==PAGER_JOURNALMODE_MEMORY
40481     );
40482     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
40483     assert( pagerUseWal(p)==0 );
40484   }
40485
40486   /* If changeCountDone is set, a RESERVED lock or greater must be held
40487   ** on the file.
40488   */
40489   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
40490   assert( p->eLock!=PENDING_LOCK );
40491
40492   switch( p->eState ){
40493     case PAGER_OPEN:
40494       assert( !MEMDB );
40495       assert( pPager->errCode==SQLITE_OK );
40496       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
40497       break;
40498
40499     case PAGER_READER:
40500       assert( pPager->errCode==SQLITE_OK );
40501       assert( p->eLock!=UNKNOWN_LOCK );
40502       assert( p->eLock>=SHARED_LOCK );
40503       break;
40504
40505     case PAGER_WRITER_LOCKED:
40506       assert( p->eLock!=UNKNOWN_LOCK );
40507       assert( pPager->errCode==SQLITE_OK );
40508       if( !pagerUseWal(pPager) ){
40509         assert( p->eLock>=RESERVED_LOCK );
40510       }
40511       assert( pPager->dbSize==pPager->dbOrigSize );
40512       assert( pPager->dbOrigSize==pPager->dbFileSize );
40513       assert( pPager->dbOrigSize==pPager->dbHintSize );
40514       assert( pPager->setMaster==0 );
40515       break;
40516
40517     case PAGER_WRITER_CACHEMOD:
40518       assert( p->eLock!=UNKNOWN_LOCK );
40519       assert( pPager->errCode==SQLITE_OK );
40520       if( !pagerUseWal(pPager) ){
40521         /* It is possible that if journal_mode=wal here that neither the
40522         ** journal file nor the WAL file are open. This happens during
40523         ** a rollback transaction that switches from journal_mode=off
40524         ** to journal_mode=wal.
40525         */
40526         assert( p->eLock>=RESERVED_LOCK );
40527         assert( isOpen(p->jfd)
40528              || p->journalMode==PAGER_JOURNALMODE_OFF
40529              || p->journalMode==PAGER_JOURNALMODE_WAL
40530         );
40531       }
40532       assert( pPager->dbOrigSize==pPager->dbFileSize );
40533       assert( pPager->dbOrigSize==pPager->dbHintSize );
40534       break;
40535
40536     case PAGER_WRITER_DBMOD:
40537       assert( p->eLock==EXCLUSIVE_LOCK );
40538       assert( pPager->errCode==SQLITE_OK );
40539       assert( !pagerUseWal(pPager) );
40540       assert( p->eLock>=EXCLUSIVE_LOCK );
40541       assert( isOpen(p->jfd)
40542            || p->journalMode==PAGER_JOURNALMODE_OFF
40543            || p->journalMode==PAGER_JOURNALMODE_WAL
40544       );
40545       assert( pPager->dbOrigSize<=pPager->dbHintSize );
40546       break;
40547
40548     case PAGER_WRITER_FINISHED:
40549       assert( p->eLock==EXCLUSIVE_LOCK );
40550       assert( pPager->errCode==SQLITE_OK );
40551       assert( !pagerUseWal(pPager) );
40552       assert( isOpen(p->jfd)
40553            || p->journalMode==PAGER_JOURNALMODE_OFF
40554            || p->journalMode==PAGER_JOURNALMODE_WAL
40555       );
40556       break;
40557
40558     case PAGER_ERROR:
40559       /* There must be at least one outstanding reference to the pager if
40560       ** in ERROR state. Otherwise the pager should have already dropped
40561       ** back to OPEN state.
40562       */
40563       assert( pPager->errCode!=SQLITE_OK );
40564       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
40565       break;
40566   }
40567
40568   return 1;
40569 }
40570 #endif /* ifndef NDEBUG */
40571
40572 #ifdef SQLITE_DEBUG
40573 /*
40574 ** Return a pointer to a human readable string in a static buffer
40575 ** containing the state of the Pager object passed as an argument. This
40576 ** is intended to be used within debuggers. For example, as an alternative
40577 ** to "print *pPager" in gdb:
40578 **
40579 ** (gdb) printf "%s", print_pager_state(pPager)
40580 */
40581 static char *print_pager_state(Pager *p){
40582   static char zRet[1024];
40583
40584   sqlite3_snprintf(1024, zRet,
40585       "Filename:      %s\n"
40586       "State:         %s errCode=%d\n"
40587       "Lock:          %s\n"
40588       "Locking mode:  locking_mode=%s\n"
40589       "Journal mode:  journal_mode=%s\n"
40590       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
40591       "Journal:       journalOff=%lld journalHdr=%lld\n"
40592       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
40593       , p->zFilename
40594       , p->eState==PAGER_OPEN            ? "OPEN" :
40595         p->eState==PAGER_READER          ? "READER" :
40596         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
40597         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
40598         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
40599         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
40600         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
40601       , (int)p->errCode
40602       , p->eLock==NO_LOCK         ? "NO_LOCK" :
40603         p->eLock==RESERVED_LOCK   ? "RESERVED" :
40604         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
40605         p->eLock==SHARED_LOCK     ? "SHARED" :
40606         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
40607       , p->exclusiveMode ? "exclusive" : "normal"
40608       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
40609         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
40610         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
40611         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
40612         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
40613         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
40614       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
40615       , p->journalOff, p->journalHdr
40616       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
40617   );
40618
40619   return zRet;
40620 }
40621 #endif
40622
40623 /*
40624 ** Return true if it is necessary to write page *pPg into the sub-journal.
40625 ** A page needs to be written into the sub-journal if there exists one
40626 ** or more open savepoints for which:
40627 **
40628 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
40629 **   * The bit corresponding to the page-number is not set in
40630 **     PagerSavepoint.pInSavepoint.
40631 */
40632 static int subjRequiresPage(PgHdr *pPg){
40633   Pgno pgno = pPg->pgno;
40634   Pager *pPager = pPg->pPager;
40635   int i;
40636   for(i=0; i<pPager->nSavepoint; i++){
40637     PagerSavepoint *p = &pPager->aSavepoint[i];
40638     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
40639       return 1;
40640     }
40641   }
40642   return 0;
40643 }
40644
40645 /*
40646 ** Return true if the page is already in the journal file.
40647 */
40648 static int pageInJournal(PgHdr *pPg){
40649   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
40650 }
40651
40652 /*
40653 ** Read a 32-bit integer from the given file descriptor.  Store the integer
40654 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
40655 ** error code is something goes wrong.
40656 **
40657 ** All values are stored on disk as big-endian.
40658 */
40659 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
40660   unsigned char ac[4];
40661   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
40662   if( rc==SQLITE_OK ){
40663     *pRes = sqlite3Get4byte(ac);
40664   }
40665   return rc;
40666 }
40667
40668 /*
40669 ** Write a 32-bit integer into a string buffer in big-endian byte order.
40670 */
40671 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
40672
40673
40674 /*
40675 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
40676 ** on success or an error code is something goes wrong.
40677 */
40678 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
40679   char ac[4];
40680   put32bits(ac, val);
40681   return sqlite3OsWrite(fd, ac, 4, offset);
40682 }
40683
40684 /*
40685 ** Unlock the database file to level eLock, which must be either NO_LOCK
40686 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
40687 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
40688 **
40689 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40690 ** called, do not modify it. See the comment above the #define of
40691 ** UNKNOWN_LOCK for an explanation of this.
40692 */
40693 static int pagerUnlockDb(Pager *pPager, int eLock){
40694   int rc = SQLITE_OK;
40695
40696   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
40697   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
40698   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
40699   if( isOpen(pPager->fd) ){
40700     assert( pPager->eLock>=eLock );
40701     rc = sqlite3OsUnlock(pPager->fd, eLock);
40702     if( pPager->eLock!=UNKNOWN_LOCK ){
40703       pPager->eLock = (u8)eLock;
40704     }
40705     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
40706   }
40707   return rc;
40708 }
40709
40710 /*
40711 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
40712 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
40713 ** Pager.eLock variable to the new locking state.
40714 **
40715 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40716 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
40717 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
40718 ** of this.
40719 */
40720 static int pagerLockDb(Pager *pPager, int eLock){
40721   int rc = SQLITE_OK;
40722
40723   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
40724   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
40725     rc = sqlite3OsLock(pPager->fd, eLock);
40726     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
40727       pPager->eLock = (u8)eLock;
40728       IOTRACE(("LOCK %p %d\n", pPager, eLock))
40729     }
40730   }
40731   return rc;
40732 }
40733
40734 /*
40735 ** This function determines whether or not the atomic-write optimization
40736 ** can be used with this pager. The optimization can be used if:
40737 **
40738 **  (a) the value returned by OsDeviceCharacteristics() indicates that
40739 **      a database page may be written atomically, and
40740 **  (b) the value returned by OsSectorSize() is less than or equal
40741 **      to the page size.
40742 **
40743 ** The optimization is also always enabled for temporary files. It is
40744 ** an error to call this function if pPager is opened on an in-memory
40745 ** database.
40746 **
40747 ** If the optimization cannot be used, 0 is returned. If it can be used,
40748 ** then the value returned is the size of the journal file when it
40749 ** contains rollback data for exactly one page.
40750 */
40751 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40752 static int jrnlBufferSize(Pager *pPager){
40753   assert( !MEMDB );
40754   if( !pPager->tempFile ){
40755     int dc;                           /* Device characteristics */
40756     int nSector;                      /* Sector size */
40757     int szPage;                       /* Page size */
40758
40759     assert( isOpen(pPager->fd) );
40760     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
40761     nSector = pPager->sectorSize;
40762     szPage = pPager->pageSize;
40763
40764     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40765     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40766     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
40767       return 0;
40768     }
40769   }
40770
40771   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
40772 }
40773 #endif
40774
40775 /*
40776 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
40777 ** on the cache using a hash function.  This is used for testing
40778 ** and debugging only.
40779 */
40780 #ifdef SQLITE_CHECK_PAGES
40781 /*
40782 ** Return a 32-bit hash of the page data for pPage.
40783 */
40784 static u32 pager_datahash(int nByte, unsigned char *pData){
40785   u32 hash = 0;
40786   int i;
40787   for(i=0; i<nByte; i++){
40788     hash = (hash*1039) + pData[i];
40789   }
40790   return hash;
40791 }
40792 static u32 pager_pagehash(PgHdr *pPage){
40793   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
40794 }
40795 static void pager_set_pagehash(PgHdr *pPage){
40796   pPage->pageHash = pager_pagehash(pPage);
40797 }
40798
40799 /*
40800 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
40801 ** is defined, and NDEBUG is not defined, an assert() statement checks
40802 ** that the page is either dirty or still matches the calculated page-hash.
40803 */
40804 #define CHECK_PAGE(x) checkPage(x)
40805 static void checkPage(PgHdr *pPg){
40806   Pager *pPager = pPg->pPager;
40807   assert( pPager->eState!=PAGER_ERROR );
40808   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
40809 }
40810
40811 #else
40812 #define pager_datahash(X,Y)  0
40813 #define pager_pagehash(X)  0
40814 #define pager_set_pagehash(X)
40815 #define CHECK_PAGE(x)
40816 #endif  /* SQLITE_CHECK_PAGES */
40817
40818 /*
40819 ** When this is called the journal file for pager pPager must be open.
40820 ** This function attempts to read a master journal file name from the
40821 ** end of the file and, if successful, copies it into memory supplied
40822 ** by the caller. See comments above writeMasterJournal() for the format
40823 ** used to store a master journal file name at the end of a journal file.
40824 **
40825 ** zMaster must point to a buffer of at least nMaster bytes allocated by
40826 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
40827 ** enough space to write the master journal name). If the master journal
40828 ** name in the journal is longer than nMaster bytes (including a
40829 ** nul-terminator), then this is handled as if no master journal name
40830 ** were present in the journal.
40831 **
40832 ** If a master journal file name is present at the end of the journal
40833 ** file, then it is copied into the buffer pointed to by zMaster. A
40834 ** nul-terminator byte is appended to the buffer following the master
40835 ** journal file name.
40836 **
40837 ** If it is determined that no master journal file name is present
40838 ** zMaster[0] is set to 0 and SQLITE_OK returned.
40839 **
40840 ** If an error occurs while reading from the journal file, an SQLite
40841 ** error code is returned.
40842 */
40843 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
40844   int rc;                    /* Return code */
40845   u32 len;                   /* Length in bytes of master journal name */
40846   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
40847   u32 cksum;                 /* MJ checksum value read from journal */
40848   u32 u;                     /* Unsigned loop counter */
40849   unsigned char aMagic[8];   /* A buffer to hold the magic header */
40850   zMaster[0] = '\0';
40851
40852   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
40853    || szJ<16
40854    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
40855    || len>=nMaster
40856    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
40857    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
40858    || memcmp(aMagic, aJournalMagic, 8)
40859    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
40860   ){
40861     return rc;
40862   }
40863
40864   /* See if the checksum matches the master journal name */
40865   for(u=0; u<len; u++){
40866     cksum -= zMaster[u];
40867   }
40868   if( cksum ){
40869     /* If the checksum doesn't add up, then one or more of the disk sectors
40870     ** containing the master journal filename is corrupted. This means
40871     ** definitely roll back, so just return SQLITE_OK and report a (nul)
40872     ** master-journal filename.
40873     */
40874     len = 0;
40875   }
40876   zMaster[len] = '\0';
40877
40878   return SQLITE_OK;
40879 }
40880
40881 /*
40882 ** Return the offset of the sector boundary at or immediately
40883 ** following the value in pPager->journalOff, assuming a sector
40884 ** size of pPager->sectorSize bytes.
40885 **
40886 ** i.e for a sector size of 512:
40887 **
40888 **   Pager.journalOff          Return value
40889 **   ---------------------------------------
40890 **   0                         0
40891 **   512                       512
40892 **   100                       512
40893 **   2000                      2048
40894 **
40895 */
40896 static i64 journalHdrOffset(Pager *pPager){
40897   i64 offset = 0;
40898   i64 c = pPager->journalOff;
40899   if( c ){
40900     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
40901   }
40902   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
40903   assert( offset>=c );
40904   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
40905   return offset;
40906 }
40907
40908 /*
40909 ** The journal file must be open when this function is called.
40910 **
40911 ** This function is a no-op if the journal file has not been written to
40912 ** within the current transaction (i.e. if Pager.journalOff==0).
40913 **
40914 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
40915 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
40916 ** zero the 28-byte header at the start of the journal file. In either case,
40917 ** if the pager is not in no-sync mode, sync the journal file immediately
40918 ** after writing or truncating it.
40919 **
40920 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
40921 ** following the truncation or zeroing described above the size of the
40922 ** journal file in bytes is larger than this value, then truncate the
40923 ** journal file to Pager.journalSizeLimit bytes. The journal file does
40924 ** not need to be synced following this operation.
40925 **
40926 ** If an IO error occurs, abandon processing and return the IO error code.
40927 ** Otherwise, return SQLITE_OK.
40928 */
40929 static int zeroJournalHdr(Pager *pPager, int doTruncate){
40930   int rc = SQLITE_OK;                               /* Return code */
40931   assert( isOpen(pPager->jfd) );
40932   if( pPager->journalOff ){
40933     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
40934
40935     IOTRACE(("JZEROHDR %p\n", pPager))
40936     if( doTruncate || iLimit==0 ){
40937       rc = sqlite3OsTruncate(pPager->jfd, 0);
40938     }else{
40939       static const char zeroHdr[28] = {0};
40940       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
40941     }
40942     if( rc==SQLITE_OK && !pPager->noSync ){
40943       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
40944     }
40945
40946     /* At this point the transaction is committed but the write lock
40947     ** is still held on the file. If there is a size limit configured for
40948     ** the persistent journal and the journal file currently consumes more
40949     ** space than that limit allows for, truncate it now. There is no need
40950     ** to sync the file following this operation.
40951     */
40952     if( rc==SQLITE_OK && iLimit>0 ){
40953       i64 sz;
40954       rc = sqlite3OsFileSize(pPager->jfd, &sz);
40955       if( rc==SQLITE_OK && sz>iLimit ){
40956         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
40957       }
40958     }
40959   }
40960   return rc;
40961 }
40962
40963 /*
40964 ** The journal file must be open when this routine is called. A journal
40965 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
40966 ** current location.
40967 **
40968 ** The format for the journal header is as follows:
40969 ** - 8 bytes: Magic identifying journal format.
40970 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
40971 ** - 4 bytes: Random number used for page hash.
40972 ** - 4 bytes: Initial database page count.
40973 ** - 4 bytes: Sector size used by the process that wrote this journal.
40974 ** - 4 bytes: Database page size.
40975 **
40976 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
40977 */
40978 static int writeJournalHdr(Pager *pPager){
40979   int rc = SQLITE_OK;                 /* Return code */
40980   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
40981   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
40982   u32 nWrite;                         /* Bytes of header sector written */
40983   int ii;                             /* Loop counter */
40984
40985   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
40986
40987   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
40988     nHeader = JOURNAL_HDR_SZ(pPager);
40989   }
40990
40991   /* If there are active savepoints and any of them were created
40992   ** since the most recent journal header was written, update the
40993   ** PagerSavepoint.iHdrOffset fields now.
40994   */
40995   for(ii=0; ii<pPager->nSavepoint; ii++){
40996     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
40997       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
40998     }
40999   }
41000
41001   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
41002
41003   /*
41004   ** Write the nRec Field - the number of page records that follow this
41005   ** journal header. Normally, zero is written to this value at this time.
41006   ** After the records are added to the journal (and the journal synced,
41007   ** if in full-sync mode), the zero is overwritten with the true number
41008   ** of records (see syncJournal()).
41009   **
41010   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
41011   ** reading the journal this value tells SQLite to assume that the
41012   ** rest of the journal file contains valid page records. This assumption
41013   ** is dangerous, as if a failure occurred whilst writing to the journal
41014   ** file it may contain some garbage data. There are two scenarios
41015   ** where this risk can be ignored:
41016   **
41017   **   * When the pager is in no-sync mode. Corruption can follow a
41018   **     power failure in this case anyway.
41019   **
41020   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
41021   **     that garbage data is never appended to the journal file.
41022   */
41023   assert( isOpen(pPager->fd) || pPager->noSync );
41024   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
41025    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
41026   ){
41027     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
41028     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
41029   }else{
41030     memset(zHeader, 0, sizeof(aJournalMagic)+4);
41031   }
41032
41033   /* The random check-hash initialiser */
41034   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
41035   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
41036   /* The initial database size */
41037   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
41038   /* The assumed sector size for this process */
41039   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
41040
41041   /* The page size */
41042   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
41043
41044   /* Initializing the tail of the buffer is not necessary.  Everything
41045   ** works find if the following memset() is omitted.  But initializing
41046   ** the memory prevents valgrind from complaining, so we are willing to
41047   ** take the performance hit.
41048   */
41049   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
41050          nHeader-(sizeof(aJournalMagic)+20));
41051
41052   /* In theory, it is only necessary to write the 28 bytes that the
41053   ** journal header consumes to the journal file here. Then increment the
41054   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
41055   ** record is written to the following sector (leaving a gap in the file
41056   ** that will be implicitly filled in by the OS).
41057   **
41058   ** However it has been discovered that on some systems this pattern can
41059   ** be significantly slower than contiguously writing data to the file,
41060   ** even if that means explicitly writing data to the block of
41061   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
41062   ** is done.
41063   **
41064   ** The loop is required here in case the sector-size is larger than the
41065   ** database page size. Since the zHeader buffer is only Pager.pageSize
41066   ** bytes in size, more than one call to sqlite3OsWrite() may be required
41067   ** to populate the entire journal header sector.
41068   */
41069   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
41070     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
41071     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
41072     assert( pPager->journalHdr <= pPager->journalOff );
41073     pPager->journalOff += nHeader;
41074   }
41075
41076   return rc;
41077 }
41078
41079 /*
41080 ** The journal file must be open when this is called. A journal header file
41081 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
41082 ** file. The current location in the journal file is given by
41083 ** pPager->journalOff. See comments above function writeJournalHdr() for
41084 ** a description of the journal header format.
41085 **
41086 ** If the header is read successfully, *pNRec is set to the number of
41087 ** page records following this header and *pDbSize is set to the size of the
41088 ** database before the transaction began, in pages. Also, pPager->cksumInit
41089 ** is set to the value read from the journal header. SQLITE_OK is returned
41090 ** in this case.
41091 **
41092 ** If the journal header file appears to be corrupted, SQLITE_DONE is
41093 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
41094 ** cannot be read from the journal file an error code is returned.
41095 */
41096 static int readJournalHdr(
41097   Pager *pPager,               /* Pager object */
41098   int isHot,
41099   i64 journalSize,             /* Size of the open journal file in bytes */
41100   u32 *pNRec,                  /* OUT: Value read from the nRec field */
41101   u32 *pDbSize                 /* OUT: Value of original database size field */
41102 ){
41103   int rc;                      /* Return code */
41104   unsigned char aMagic[8];     /* A buffer to hold the magic header */
41105   i64 iHdrOff;                 /* Offset of journal header being read */
41106
41107   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
41108
41109   /* Advance Pager.journalOff to the start of the next sector. If the
41110   ** journal file is too small for there to be a header stored at this
41111   ** point, return SQLITE_DONE.
41112   */
41113   pPager->journalOff = journalHdrOffset(pPager);
41114   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
41115     return SQLITE_DONE;
41116   }
41117   iHdrOff = pPager->journalOff;
41118
41119   /* Read in the first 8 bytes of the journal header. If they do not match
41120   ** the  magic string found at the start of each journal header, return
41121   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
41122   ** proceed.
41123   */
41124   if( isHot || iHdrOff!=pPager->journalHdr ){
41125     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
41126     if( rc ){
41127       return rc;
41128     }
41129     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
41130       return SQLITE_DONE;
41131     }
41132   }
41133
41134   /* Read the first three 32-bit fields of the journal header: The nRec
41135   ** field, the checksum-initializer and the database size at the start
41136   ** of the transaction. Return an error code if anything goes wrong.
41137   */
41138   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
41139    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
41140    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
41141   ){
41142     return rc;
41143   }
41144
41145   if( pPager->journalOff==0 ){
41146     u32 iPageSize;               /* Page-size field of journal header */
41147     u32 iSectorSize;             /* Sector-size field of journal header */
41148
41149     /* Read the page-size and sector-size journal header fields. */
41150     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
41151      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
41152     ){
41153       return rc;
41154     }
41155
41156     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
41157     ** journal header to zero. In this case, assume that the Pager.pageSize
41158     ** variable is already set to the correct page size.
41159     */
41160     if( iPageSize==0 ){
41161       iPageSize = pPager->pageSize;
41162     }
41163
41164     /* Check that the values read from the page-size and sector-size fields
41165     ** are within range. To be 'in range', both values need to be a power
41166     ** of two greater than or equal to 512 or 32, and not greater than their
41167     ** respective compile time maximum limits.
41168     */
41169     if( iPageSize<512                  || iSectorSize<32
41170      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
41171      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
41172     ){
41173       /* If the either the page-size or sector-size in the journal-header is
41174       ** invalid, then the process that wrote the journal-header must have
41175       ** crashed before the header was synced. In this case stop reading
41176       ** the journal file here.
41177       */
41178       return SQLITE_DONE;
41179     }
41180
41181     /* Update the page-size to match the value read from the journal.
41182     ** Use a testcase() macro to make sure that malloc failure within
41183     ** PagerSetPagesize() is tested.
41184     */
41185     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
41186     testcase( rc!=SQLITE_OK );
41187
41188     /* Update the assumed sector-size to match the value used by
41189     ** the process that created this journal. If this journal was
41190     ** created by a process other than this one, then this routine
41191     ** is being called from within pager_playback(). The local value
41192     ** of Pager.sectorSize is restored at the end of that routine.
41193     */
41194     pPager->sectorSize = iSectorSize;
41195   }
41196
41197   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
41198   return rc;
41199 }
41200
41201
41202 /*
41203 ** Write the supplied master journal name into the journal file for pager
41204 ** pPager at the current location. The master journal name must be the last
41205 ** thing written to a journal file. If the pager is in full-sync mode, the
41206 ** journal file descriptor is advanced to the next sector boundary before
41207 ** anything is written. The format is:
41208 **
41209 **   + 4 bytes: PAGER_MJ_PGNO.
41210 **   + N bytes: Master journal filename in utf-8.
41211 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
41212 **   + 4 bytes: Master journal name checksum.
41213 **   + 8 bytes: aJournalMagic[].
41214 **
41215 ** The master journal page checksum is the sum of the bytes in the master
41216 ** journal name, where each byte is interpreted as a signed 8-bit integer.
41217 **
41218 ** If zMaster is a NULL pointer (occurs for a single database transaction),
41219 ** this call is a no-op.
41220 */
41221 static int writeMasterJournal(Pager *pPager, const char *zMaster){
41222   int rc;                          /* Return code */
41223   int nMaster;                     /* Length of string zMaster */
41224   i64 iHdrOff;                     /* Offset of header in journal file */
41225   i64 jrnlSize;                    /* Size of journal file on disk */
41226   u32 cksum = 0;                   /* Checksum of string zMaster */
41227
41228   assert( pPager->setMaster==0 );
41229   assert( !pagerUseWal(pPager) );
41230
41231   if( !zMaster
41232    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
41233    || pPager->journalMode==PAGER_JOURNALMODE_OFF
41234   ){
41235     return SQLITE_OK;
41236   }
41237   pPager->setMaster = 1;
41238   assert( isOpen(pPager->jfd) );
41239   assert( pPager->journalHdr <= pPager->journalOff );
41240
41241   /* Calculate the length in bytes and the checksum of zMaster */
41242   for(nMaster=0; zMaster[nMaster]; nMaster++){
41243     cksum += zMaster[nMaster];
41244   }
41245
41246   /* If in full-sync mode, advance to the next disk sector before writing
41247   ** the master journal name. This is in case the previous page written to
41248   ** the journal has already been synced.
41249   */
41250   if( pPager->fullSync ){
41251     pPager->journalOff = journalHdrOffset(pPager);
41252   }
41253   iHdrOff = pPager->journalOff;
41254
41255   /* Write the master journal data to the end of the journal file. If
41256   ** an error occurs, return the error code to the caller.
41257   */
41258   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
41259    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
41260    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
41261    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
41262    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
41263   ){
41264     return rc;
41265   }
41266   pPager->journalOff += (nMaster+20);
41267
41268   /* If the pager is in peristent-journal mode, then the physical
41269   ** journal-file may extend past the end of the master-journal name
41270   ** and 8 bytes of magic data just written to the file. This is
41271   ** dangerous because the code to rollback a hot-journal file
41272   ** will not be able to find the master-journal name to determine
41273   ** whether or not the journal is hot.
41274   **
41275   ** Easiest thing to do in this scenario is to truncate the journal
41276   ** file to the required size.
41277   */
41278   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
41279    && jrnlSize>pPager->journalOff
41280   ){
41281     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
41282   }
41283   return rc;
41284 }
41285
41286 /*
41287 ** Find a page in the hash table given its page number. Return
41288 ** a pointer to the page or NULL if the requested page is not
41289 ** already in memory.
41290 */
41291 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
41292   PgHdr *p;                         /* Return value */
41293
41294   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
41295   ** fail, since no attempt to allocate dynamic memory will be made.
41296   */
41297   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
41298   return p;
41299 }
41300
41301 /*
41302 ** Discard the entire contents of the in-memory page-cache.
41303 */
41304 static void pager_reset(Pager *pPager){
41305   sqlite3BackupRestart(pPager->pBackup);
41306   sqlite3PcacheClear(pPager->pPCache);
41307 }
41308
41309 /*
41310 ** Free all structures in the Pager.aSavepoint[] array and set both
41311 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
41312 ** if it is open and the pager is not in exclusive mode.
41313 */
41314 static void releaseAllSavepoints(Pager *pPager){
41315   int ii;               /* Iterator for looping through Pager.aSavepoint */
41316   for(ii=0; ii<pPager->nSavepoint; ii++){
41317     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
41318   }
41319   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
41320     sqlite3OsClose(pPager->sjfd);
41321   }
41322   sqlite3_free(pPager->aSavepoint);
41323   pPager->aSavepoint = 0;
41324   pPager->nSavepoint = 0;
41325   pPager->nSubRec = 0;
41326 }
41327
41328 /*
41329 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
41330 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
41331 ** or SQLITE_NOMEM if a malloc failure occurs.
41332 */
41333 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
41334   int ii;                   /* Loop counter */
41335   int rc = SQLITE_OK;       /* Result code */
41336
41337   for(ii=0; ii<pPager->nSavepoint; ii++){
41338     PagerSavepoint *p = &pPager->aSavepoint[ii];
41339     if( pgno<=p->nOrig ){
41340       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
41341       testcase( rc==SQLITE_NOMEM );
41342       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41343     }
41344   }
41345   return rc;
41346 }
41347
41348 /*
41349 ** This function is a no-op if the pager is in exclusive mode and not
41350 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
41351 ** state.
41352 **
41353 ** If the pager is not in exclusive-access mode, the database file is
41354 ** completely unlocked. If the file is unlocked and the file-system does
41355 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
41356 ** closed (if it is open).
41357 **
41358 ** If the pager is in ERROR state when this function is called, the
41359 ** contents of the pager cache are discarded before switching back to
41360 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
41361 ** or not, any journal file left in the file-system will be treated
41362 ** as a hot-journal and rolled back the next time a read-transaction
41363 ** is opened (by this or by any other connection).
41364 */
41365 static void pager_unlock(Pager *pPager){
41366
41367   assert( pPager->eState==PAGER_READER
41368        || pPager->eState==PAGER_OPEN
41369        || pPager->eState==PAGER_ERROR
41370   );
41371
41372   sqlite3BitvecDestroy(pPager->pInJournal);
41373   pPager->pInJournal = 0;
41374   releaseAllSavepoints(pPager);
41375
41376   if( pagerUseWal(pPager) ){
41377     assert( !isOpen(pPager->jfd) );
41378     sqlite3WalEndReadTransaction(pPager->pWal);
41379     pPager->eState = PAGER_OPEN;
41380   }else if( !pPager->exclusiveMode ){
41381     int rc;                       /* Error code returned by pagerUnlockDb() */
41382     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
41383
41384     /* If the operating system support deletion of open files, then
41385     ** close the journal file when dropping the database lock.  Otherwise
41386     ** another connection with journal_mode=delete might delete the file
41387     ** out from under us.
41388     */
41389     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
41390     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
41391     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
41392     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
41393     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41394     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
41395     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
41396      || 1!=(pPager->journalMode & 5)
41397     ){
41398       sqlite3OsClose(pPager->jfd);
41399     }
41400
41401     /* If the pager is in the ERROR state and the call to unlock the database
41402     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
41403     ** above the #define for UNKNOWN_LOCK for an explanation of why this
41404     ** is necessary.
41405     */
41406     rc = pagerUnlockDb(pPager, NO_LOCK);
41407     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
41408       pPager->eLock = UNKNOWN_LOCK;
41409     }
41410
41411     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
41412     ** without clearing the error code. This is intentional - the error
41413     ** code is cleared and the cache reset in the block below.
41414     */
41415     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
41416     pPager->changeCountDone = 0;
41417     pPager->eState = PAGER_OPEN;
41418   }
41419
41420   /* If Pager.errCode is set, the contents of the pager cache cannot be
41421   ** trusted. Now that there are no outstanding references to the pager,
41422   ** it can safely move back to PAGER_OPEN state. This happens in both
41423   ** normal and exclusive-locking mode.
41424   */
41425   if( pPager->errCode ){
41426     assert( !MEMDB );
41427     pager_reset(pPager);
41428     pPager->changeCountDone = pPager->tempFile;
41429     pPager->eState = PAGER_OPEN;
41430     pPager->errCode = SQLITE_OK;
41431   }
41432
41433   pPager->journalOff = 0;
41434   pPager->journalHdr = 0;
41435   pPager->setMaster = 0;
41436 }
41437
41438 /*
41439 ** This function is called whenever an IOERR or FULL error that requires
41440 ** the pager to transition into the ERROR state may ahve occurred.
41441 ** The first argument is a pointer to the pager structure, the second
41442 ** the error-code about to be returned by a pager API function. The
41443 ** value returned is a copy of the second argument to this function.
41444 **
41445 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
41446 ** IOERR sub-codes, the pager enters the ERROR state and the error code
41447 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
41448 ** all major API calls on the Pager will immediately return Pager.errCode.
41449 **
41450 ** The ERROR state indicates that the contents of the pager-cache
41451 ** cannot be trusted. This state can be cleared by completely discarding
41452 ** the contents of the pager-cache. If a transaction was active when
41453 ** the persistent error occurred, then the rollback journal may need
41454 ** to be replayed to restore the contents of the database file (as if
41455 ** it were a hot-journal).
41456 */
41457 static int pager_error(Pager *pPager, int rc){
41458   int rc2 = rc & 0xff;
41459   assert( rc==SQLITE_OK || !MEMDB );
41460   assert(
41461        pPager->errCode==SQLITE_FULL ||
41462        pPager->errCode==SQLITE_OK ||
41463        (pPager->errCode & 0xff)==SQLITE_IOERR
41464   );
41465   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
41466     pPager->errCode = rc;
41467     pPager->eState = PAGER_ERROR;
41468   }
41469   return rc;
41470 }
41471
41472 /*
41473 ** This routine ends a transaction. A transaction is usually ended by
41474 ** either a COMMIT or a ROLLBACK operation. This routine may be called
41475 ** after rollback of a hot-journal, or if an error occurs while opening
41476 ** the journal file or writing the very first journal-header of a
41477 ** database transaction.
41478 **
41479 ** This routine is never called in PAGER_ERROR state. If it is called
41480 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
41481 ** exclusive than a RESERVED lock, it is a no-op.
41482 **
41483 ** Otherwise, any active savepoints are released.
41484 **
41485 ** If the journal file is open, then it is "finalized". Once a journal
41486 ** file has been finalized it is not possible to use it to roll back a
41487 ** transaction. Nor will it be considered to be a hot-journal by this
41488 ** or any other database connection. Exactly how a journal is finalized
41489 ** depends on whether or not the pager is running in exclusive mode and
41490 ** the current journal-mode (Pager.journalMode value), as follows:
41491 **
41492 **   journalMode==MEMORY
41493 **     Journal file descriptor is simply closed. This destroys an
41494 **     in-memory journal.
41495 **
41496 **   journalMode==TRUNCATE
41497 **     Journal file is truncated to zero bytes in size.
41498 **
41499 **   journalMode==PERSIST
41500 **     The first 28 bytes of the journal file are zeroed. This invalidates
41501 **     the first journal header in the file, and hence the entire journal
41502 **     file. An invalid journal file cannot be rolled back.
41503 **
41504 **   journalMode==DELETE
41505 **     The journal file is closed and deleted using sqlite3OsDelete().
41506 **
41507 **     If the pager is running in exclusive mode, this method of finalizing
41508 **     the journal file is never used. Instead, if the journalMode is
41509 **     DELETE and the pager is in exclusive mode, the method described under
41510 **     journalMode==PERSIST is used instead.
41511 **
41512 ** After the journal is finalized, the pager moves to PAGER_READER state.
41513 ** If running in non-exclusive rollback mode, the lock on the file is
41514 ** downgraded to a SHARED_LOCK.
41515 **
41516 ** SQLITE_OK is returned if no error occurs. If an error occurs during
41517 ** any of the IO operations to finalize the journal file or unlock the
41518 ** database then the IO error code is returned to the user. If the
41519 ** operation to finalize the journal file fails, then the code still
41520 ** tries to unlock the database file if not in exclusive mode. If the
41521 ** unlock operation fails as well, then the first error code related
41522 ** to the first error encountered (the journal finalization one) is
41523 ** returned.
41524 */
41525 static int pager_end_transaction(Pager *pPager, int hasMaster){
41526   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
41527   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
41528
41529   /* Do nothing if the pager does not have an open write transaction
41530   ** or at least a RESERVED lock. This function may be called when there
41531   ** is no write-transaction active but a RESERVED or greater lock is
41532   ** held under two circumstances:
41533   **
41534   **   1. After a successful hot-journal rollback, it is called with
41535   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
41536   **
41537   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
41538   **      lock switches back to locking_mode=normal and then executes a
41539   **      read-transaction, this function is called with eState==PAGER_READER
41540   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
41541   */
41542   assert( assert_pager_state(pPager) );
41543   assert( pPager->eState!=PAGER_ERROR );
41544   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
41545     return SQLITE_OK;
41546   }
41547
41548   releaseAllSavepoints(pPager);
41549   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
41550   if( isOpen(pPager->jfd) ){
41551     assert( !pagerUseWal(pPager) );
41552
41553     /* Finalize the journal file. */
41554     if( sqlite3IsMemJournal(pPager->jfd) ){
41555       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
41556       sqlite3OsClose(pPager->jfd);
41557     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
41558       if( pPager->journalOff==0 ){
41559         rc = SQLITE_OK;
41560       }else{
41561         rc = sqlite3OsTruncate(pPager->jfd, 0);
41562       }
41563       pPager->journalOff = 0;
41564     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
41565       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
41566     ){
41567       rc = zeroJournalHdr(pPager, hasMaster);
41568       pPager->journalOff = 0;
41569     }else{
41570       /* This branch may be executed with Pager.journalMode==MEMORY if
41571       ** a hot-journal was just rolled back. In this case the journal
41572       ** file should be closed and deleted. If this connection writes to
41573       ** the database file, it will do so using an in-memory journal.
41574       */
41575       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
41576       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
41577            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
41578            || pPager->journalMode==PAGER_JOURNALMODE_WAL
41579       );
41580       sqlite3OsClose(pPager->jfd);
41581       if( bDelete ){
41582         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41583       }
41584     }
41585   }
41586
41587 #ifdef SQLITE_CHECK_PAGES
41588   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
41589   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
41590     PgHdr *p = pager_lookup(pPager, 1);
41591     if( p ){
41592       p->pageHash = 0;
41593       sqlite3PagerUnref(p);
41594     }
41595   }
41596 #endif
41597
41598   sqlite3BitvecDestroy(pPager->pInJournal);
41599   pPager->pInJournal = 0;
41600   pPager->nRec = 0;
41601   sqlite3PcacheCleanAll(pPager->pPCache);
41602   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
41603
41604   if( pagerUseWal(pPager) ){
41605     /* Drop the WAL write-lock, if any. Also, if the connection was in
41606     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
41607     ** lock held on the database file.
41608     */
41609     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
41610     assert( rc2==SQLITE_OK );
41611   }
41612   if( !pPager->exclusiveMode
41613    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
41614   ){
41615     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
41616     pPager->changeCountDone = 0;
41617   }
41618   pPager->eState = PAGER_READER;
41619   pPager->setMaster = 0;
41620
41621   return (rc==SQLITE_OK?rc2:rc);
41622 }
41623
41624 /*
41625 ** Execute a rollback if a transaction is active and unlock the
41626 ** database file.
41627 **
41628 ** If the pager has already entered the ERROR state, do not attempt
41629 ** the rollback at this time. Instead, pager_unlock() is called. The
41630 ** call to pager_unlock() will discard all in-memory pages, unlock
41631 ** the database file and move the pager back to OPEN state. If this
41632 ** means that there is a hot-journal left in the file-system, the next
41633 ** connection to obtain a shared lock on the pager (which may be this one)
41634 ** will roll it back.
41635 **
41636 ** If the pager has not already entered the ERROR state, but an IO or
41637 ** malloc error occurs during a rollback, then this will itself cause
41638 ** the pager to enter the ERROR state. Which will be cleared by the
41639 ** call to pager_unlock(), as described above.
41640 */
41641 static void pagerUnlockAndRollback(Pager *pPager){
41642   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
41643     assert( assert_pager_state(pPager) );
41644     if( pPager->eState>=PAGER_WRITER_LOCKED ){
41645       sqlite3BeginBenignMalloc();
41646       sqlite3PagerRollback(pPager);
41647       sqlite3EndBenignMalloc();
41648     }else if( !pPager->exclusiveMode ){
41649       assert( pPager->eState==PAGER_READER );
41650       pager_end_transaction(pPager, 0);
41651     }
41652   }
41653   pager_unlock(pPager);
41654 }
41655
41656 /*
41657 ** Parameter aData must point to a buffer of pPager->pageSize bytes
41658 ** of data. Compute and return a checksum based ont the contents of the
41659 ** page of data and the current value of pPager->cksumInit.
41660 **
41661 ** This is not a real checksum. It is really just the sum of the
41662 ** random initial value (pPager->cksumInit) and every 200th byte
41663 ** of the page data, starting with byte offset (pPager->pageSize%200).
41664 ** Each byte is interpreted as an 8-bit unsigned integer.
41665 **
41666 ** Changing the formula used to compute this checksum results in an
41667 ** incompatible journal file format.
41668 **
41669 ** If journal corruption occurs due to a power failure, the most likely
41670 ** scenario is that one end or the other of the record will be changed.
41671 ** It is much less likely that the two ends of the journal record will be
41672 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
41673 ** though fast and simple, catches the mostly likely kind of corruption.
41674 */
41675 static u32 pager_cksum(Pager *pPager, const u8 *aData){
41676   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
41677   int i = pPager->pageSize-200;          /* Loop counter */
41678   while( i>0 ){
41679     cksum += aData[i];
41680     i -= 200;
41681   }
41682   return cksum;
41683 }
41684
41685 /*
41686 ** Report the current page size and number of reserved bytes back
41687 ** to the codec.
41688 */
41689 #ifdef SQLITE_HAS_CODEC
41690 static void pagerReportSize(Pager *pPager){
41691   if( pPager->xCodecSizeChng ){
41692     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
41693                            (int)pPager->nReserve);
41694   }
41695 }
41696 #else
41697 # define pagerReportSize(X)     /* No-op if we do not support a codec */
41698 #endif
41699
41700 /*
41701 ** Read a single page from either the journal file (if isMainJrnl==1) or
41702 ** from the sub-journal (if isMainJrnl==0) and playback that page.
41703 ** The page begins at offset *pOffset into the file. The *pOffset
41704 ** value is increased to the start of the next page in the journal.
41705 **
41706 ** The main rollback journal uses checksums - the statement journal does
41707 ** not.
41708 **
41709 ** If the page number of the page record read from the (sub-)journal file
41710 ** is greater than the current value of Pager.dbSize, then playback is
41711 ** skipped and SQLITE_OK is returned.
41712 **
41713 ** If pDone is not NULL, then it is a record of pages that have already
41714 ** been played back.  If the page at *pOffset has already been played back
41715 ** (if the corresponding pDone bit is set) then skip the playback.
41716 ** Make sure the pDone bit corresponding to the *pOffset page is set
41717 ** prior to returning.
41718 **
41719 ** If the page record is successfully read from the (sub-)journal file
41720 ** and played back, then SQLITE_OK is returned. If an IO error occurs
41721 ** while reading the record from the (sub-)journal file or while writing
41722 ** to the database file, then the IO error code is returned. If data
41723 ** is successfully read from the (sub-)journal file but appears to be
41724 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
41725 ** two circumstances:
41726 **
41727 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
41728 **   * If the record is being rolled back from the main journal file
41729 **     and the checksum field does not match the record content.
41730 **
41731 ** Neither of these two scenarios are possible during a savepoint rollback.
41732 **
41733 ** If this is a savepoint rollback, then memory may have to be dynamically
41734 ** allocated by this function. If this is the case and an allocation fails,
41735 ** SQLITE_NOMEM is returned.
41736 */
41737 static int pager_playback_one_page(
41738   Pager *pPager,                /* The pager being played back */
41739   i64 *pOffset,                 /* Offset of record to playback */
41740   Bitvec *pDone,                /* Bitvec of pages already played back */
41741   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
41742   int isSavepnt                 /* True for a savepoint rollback */
41743 ){
41744   int rc;
41745   PgHdr *pPg;                   /* An existing page in the cache */
41746   Pgno pgno;                    /* The page number of a page in journal */
41747   u32 cksum;                    /* Checksum used for sanity checking */
41748   char *aData;                  /* Temporary storage for the page */
41749   sqlite3_file *jfd;            /* The file descriptor for the journal file */
41750   int isSynced;                 /* True if journal page is synced */
41751
41752   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
41753   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
41754   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
41755   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
41756
41757   aData = pPager->pTmpSpace;
41758   assert( aData );         /* Temp storage must have already been allocated */
41759   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
41760
41761   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
41762   ** or savepoint rollback done at the request of the caller) or this is
41763   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
41764   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
41765   ** only reads from the main journal, not the sub-journal.
41766   */
41767   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
41768        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
41769   );
41770   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
41771
41772   /* Read the page number and page data from the journal or sub-journal
41773   ** file. Return an error code to the caller if an IO error occurs.
41774   */
41775   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
41776   rc = read32bits(jfd, *pOffset, &pgno);
41777   if( rc!=SQLITE_OK ) return rc;
41778   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
41779   if( rc!=SQLITE_OK ) return rc;
41780   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
41781
41782   /* Sanity checking on the page.  This is more important that I originally
41783   ** thought.  If a power failure occurs while the journal is being written,
41784   ** it could cause invalid data to be written into the journal.  We need to
41785   ** detect this invalid data (with high probability) and ignore it.
41786   */
41787   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
41788     assert( !isSavepnt );
41789     return SQLITE_DONE;
41790   }
41791   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
41792     return SQLITE_OK;
41793   }
41794   if( isMainJrnl ){
41795     rc = read32bits(jfd, (*pOffset)-4, &cksum);
41796     if( rc ) return rc;
41797     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
41798       return SQLITE_DONE;
41799     }
41800   }
41801
41802   /* If this page has already been played by before during the current
41803   ** rollback, then don't bother to play it back again.
41804   */
41805   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
41806     return rc;
41807   }
41808
41809   /* When playing back page 1, restore the nReserve setting
41810   */
41811   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
41812     pPager->nReserve = ((u8*)aData)[20];
41813     pagerReportSize(pPager);
41814   }
41815
41816   /* If the pager is in CACHEMOD state, then there must be a copy of this
41817   ** page in the pager cache. In this case just update the pager cache,
41818   ** not the database file. The page is left marked dirty in this case.
41819   **
41820   ** An exception to the above rule: If the database is in no-sync mode
41821   ** and a page is moved during an incremental vacuum then the page may
41822   ** not be in the pager cache. Later: if a malloc() or IO error occurs
41823   ** during a Movepage() call, then the page may not be in the cache
41824   ** either. So the condition described in the above paragraph is not
41825   ** assert()able.
41826   **
41827   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
41828   ** pager cache if it exists and the main file. The page is then marked
41829   ** not dirty. Since this code is only executed in PAGER_OPEN state for
41830   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
41831   ** if the pager is in OPEN state.
41832   **
41833   ** Ticket #1171:  The statement journal might contain page content that is
41834   ** different from the page content at the start of the transaction.
41835   ** This occurs when a page is changed prior to the start of a statement
41836   ** then changed again within the statement.  When rolling back such a
41837   ** statement we must not write to the original database unless we know
41838   ** for certain that original page contents are synced into the main rollback
41839   ** journal.  Otherwise, a power loss might leave modified data in the
41840   ** database file without an entry in the rollback journal that can
41841   ** restore the database to its original form.  Two conditions must be
41842   ** met before writing to the database files. (1) the database must be
41843   ** locked.  (2) we know that the original page content is fully synced
41844   ** in the main journal either because the page is not in cache or else
41845   ** the page is marked as needSync==0.
41846   **
41847   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
41848   ** is possible to fail a statement on a database that does not yet exist.
41849   ** Do not attempt to write if database file has never been opened.
41850   */
41851   if( pagerUseWal(pPager) ){
41852     pPg = 0;
41853   }else{
41854     pPg = pager_lookup(pPager, pgno);
41855   }
41856   assert( pPg || !MEMDB );
41857   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
41858   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
41859            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
41860            (isMainJrnl?"main-journal":"sub-journal")
41861   ));
41862   if( isMainJrnl ){
41863     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
41864   }else{
41865     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
41866   }
41867   if( isOpen(pPager->fd)
41868    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41869    && isSynced
41870   ){
41871     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
41872     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
41873     assert( !pagerUseWal(pPager) );
41874     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
41875     if( pgno>pPager->dbFileSize ){
41876       pPager->dbFileSize = pgno;
41877     }
41878     if( pPager->pBackup ){
41879       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
41880       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
41881       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
41882     }
41883   }else if( !isMainJrnl && pPg==0 ){
41884     /* If this is a rollback of a savepoint and data was not written to
41885     ** the database and the page is not in-memory, there is a potential
41886     ** problem. When the page is next fetched by the b-tree layer, it
41887     ** will be read from the database file, which may or may not be
41888     ** current.
41889     **
41890     ** There are a couple of different ways this can happen. All are quite
41891     ** obscure. When running in synchronous mode, this can only happen
41892     ** if the page is on the free-list at the start of the transaction, then
41893     ** populated, then moved using sqlite3PagerMovepage().
41894     **
41895     ** The solution is to add an in-memory page to the cache containing
41896     ** the data just read from the sub-journal. Mark the page as dirty
41897     ** and if the pager requires a journal-sync, then mark the page as
41898     ** requiring a journal-sync before it is written.
41899     */
41900     assert( isSavepnt );
41901     assert( pPager->doNotSpill==0 );
41902     pPager->doNotSpill++;
41903     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
41904     assert( pPager->doNotSpill==1 );
41905     pPager->doNotSpill--;
41906     if( rc!=SQLITE_OK ) return rc;
41907     pPg->flags &= ~PGHDR_NEED_READ;
41908     sqlite3PcacheMakeDirty(pPg);
41909   }
41910   if( pPg ){
41911     /* No page should ever be explicitly rolled back that is in use, except
41912     ** for page 1 which is held in use in order to keep the lock on the
41913     ** database active. However such a page may be rolled back as a result
41914     ** of an internal error resulting in an automatic call to
41915     ** sqlite3PagerRollback().
41916     */
41917     void *pData;
41918     pData = pPg->pData;
41919     memcpy(pData, (u8*)aData, pPager->pageSize);
41920     pPager->xReiniter(pPg);
41921     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
41922       /* If the contents of this page were just restored from the main
41923       ** journal file, then its content must be as they were when the
41924       ** transaction was first opened. In this case we can mark the page
41925       ** as clean, since there will be no need to write it out to the
41926       ** database.
41927       **
41928       ** There is one exception to this rule. If the page is being rolled
41929       ** back as part of a savepoint (or statement) rollback from an
41930       ** unsynced portion of the main journal file, then it is not safe
41931       ** to mark the page as clean. This is because marking the page as
41932       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
41933       ** already in the journal file (recorded in Pager.pInJournal) and
41934       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
41935       ** again within this transaction, it will be marked as dirty but
41936       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
41937       ** be written out into the database file before its journal file
41938       ** segment is synced. If a crash occurs during or following this,
41939       ** database corruption may ensue.
41940       */
41941       assert( !pagerUseWal(pPager) );
41942       sqlite3PcacheMakeClean(pPg);
41943     }
41944     pager_set_pagehash(pPg);
41945
41946     /* If this was page 1, then restore the value of Pager.dbFileVers.
41947     ** Do this before any decoding. */
41948     if( pgno==1 ){
41949       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
41950     }
41951
41952     /* Decode the page just read from disk */
41953     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
41954     sqlite3PcacheRelease(pPg);
41955   }
41956   return rc;
41957 }
41958
41959 /*
41960 ** Parameter zMaster is the name of a master journal file. A single journal
41961 ** file that referred to the master journal file has just been rolled back.
41962 ** This routine checks if it is possible to delete the master journal file,
41963 ** and does so if it is.
41964 **
41965 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
41966 ** available for use within this function.
41967 **
41968 ** When a master journal file is created, it is populated with the names
41969 ** of all of its child journals, one after another, formatted as utf-8
41970 ** encoded text. The end of each child journal file is marked with a
41971 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
41972 ** file for a transaction involving two databases might be:
41973 **
41974 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
41975 **
41976 ** A master journal file may only be deleted once all of its child
41977 ** journals have been rolled back.
41978 **
41979 ** This function reads the contents of the master-journal file into
41980 ** memory and loops through each of the child journal names. For
41981 ** each child journal, it checks if:
41982 **
41983 **   * if the child journal exists, and if so
41984 **   * if the child journal contains a reference to master journal
41985 **     file zMaster
41986 **
41987 ** If a child journal can be found that matches both of the criteria
41988 ** above, this function returns without doing anything. Otherwise, if
41989 ** no such child journal can be found, file zMaster is deleted from
41990 ** the file-system using sqlite3OsDelete().
41991 **
41992 ** If an IO error within this function, an error code is returned. This
41993 ** function allocates memory by calling sqlite3Malloc(). If an allocation
41994 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
41995 ** occur, SQLITE_OK is returned.
41996 **
41997 ** TODO: This function allocates a single block of memory to load
41998 ** the entire contents of the master journal file. This could be
41999 ** a couple of kilobytes or so - potentially larger than the page
42000 ** size.
42001 */
42002 static int pager_delmaster(Pager *pPager, const char *zMaster){
42003   sqlite3_vfs *pVfs = pPager->pVfs;
42004   int rc;                   /* Return code */
42005   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
42006   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
42007   char *zMasterJournal = 0; /* Contents of master journal file */
42008   i64 nMasterJournal;       /* Size of master journal file */
42009   char *zJournal;           /* Pointer to one journal within MJ file */
42010   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
42011   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
42012
42013   /* Allocate space for both the pJournal and pMaster file descriptors.
42014   ** If successful, open the master journal file for reading.
42015   */
42016   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
42017   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
42018   if( !pMaster ){
42019     rc = SQLITE_NOMEM;
42020   }else{
42021     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
42022     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
42023   }
42024   if( rc!=SQLITE_OK ) goto delmaster_out;
42025
42026   /* Load the entire master journal file into space obtained from
42027   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
42028   ** sufficient space (in zMasterPtr) to hold the names of master
42029   ** journal files extracted from regular rollback-journals.
42030   */
42031   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
42032   if( rc!=SQLITE_OK ) goto delmaster_out;
42033   nMasterPtr = pVfs->mxPathname+1;
42034   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
42035   if( !zMasterJournal ){
42036     rc = SQLITE_NOMEM;
42037     goto delmaster_out;
42038   }
42039   zMasterPtr = &zMasterJournal[nMasterJournal+1];
42040   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
42041   if( rc!=SQLITE_OK ) goto delmaster_out;
42042   zMasterJournal[nMasterJournal] = 0;
42043
42044   zJournal = zMasterJournal;
42045   while( (zJournal-zMasterJournal)<nMasterJournal ){
42046     int exists;
42047     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
42048     if( rc!=SQLITE_OK ){
42049       goto delmaster_out;
42050     }
42051     if( exists ){
42052       /* One of the journals pointed to by the master journal exists.
42053       ** Open it and check if it points at the master journal. If
42054       ** so, return without deleting the master journal file.
42055       */
42056       int c;
42057       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
42058       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
42059       if( rc!=SQLITE_OK ){
42060         goto delmaster_out;
42061       }
42062
42063       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
42064       sqlite3OsClose(pJournal);
42065       if( rc!=SQLITE_OK ){
42066         goto delmaster_out;
42067       }
42068
42069       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
42070       if( c ){
42071         /* We have a match. Do not delete the master journal file. */
42072         goto delmaster_out;
42073       }
42074     }
42075     zJournal += (sqlite3Strlen30(zJournal)+1);
42076   }
42077
42078   sqlite3OsClose(pMaster);
42079   rc = sqlite3OsDelete(pVfs, zMaster, 0);
42080
42081 delmaster_out:
42082   sqlite3_free(zMasterJournal);
42083   if( pMaster ){
42084     sqlite3OsClose(pMaster);
42085     assert( !isOpen(pJournal) );
42086     sqlite3_free(pMaster);
42087   }
42088   return rc;
42089 }
42090
42091
42092 /*
42093 ** This function is used to change the actual size of the database
42094 ** file in the file-system. This only happens when committing a transaction,
42095 ** or rolling back a transaction (including rolling back a hot-journal).
42096 **
42097 ** If the main database file is not open, or the pager is not in either
42098 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
42099 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
42100 ** If the file on disk is currently larger than nPage pages, then use the VFS
42101 ** xTruncate() method to truncate it.
42102 **
42103 ** Or, it might might be the case that the file on disk is smaller than
42104 ** nPage pages. Some operating system implementations can get confused if
42105 ** you try to truncate a file to some size that is larger than it
42106 ** currently is, so detect this case and write a single zero byte to
42107 ** the end of the new file instead.
42108 **
42109 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
42110 ** the database file, return the error code to the caller.
42111 */
42112 static int pager_truncate(Pager *pPager, Pgno nPage){
42113   int rc = SQLITE_OK;
42114   assert( pPager->eState!=PAGER_ERROR );
42115   assert( pPager->eState!=PAGER_READER );
42116
42117   if( isOpen(pPager->fd)
42118    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42119   ){
42120     i64 currentSize, newSize;
42121     int szPage = pPager->pageSize;
42122     assert( pPager->eLock==EXCLUSIVE_LOCK );
42123     /* TODO: Is it safe to use Pager.dbFileSize here? */
42124     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
42125     newSize = szPage*(i64)nPage;
42126     if( rc==SQLITE_OK && currentSize!=newSize ){
42127       if( currentSize>newSize ){
42128         rc = sqlite3OsTruncate(pPager->fd, newSize);
42129       }else if( (currentSize+szPage)<=newSize ){
42130         char *pTmp = pPager->pTmpSpace;
42131         memset(pTmp, 0, szPage);
42132         testcase( (newSize-szPage) == currentSize );
42133         testcase( (newSize-szPage) >  currentSize );
42134         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
42135       }
42136       if( rc==SQLITE_OK ){
42137         pPager->dbFileSize = nPage;
42138       }
42139     }
42140   }
42141   return rc;
42142 }
42143
42144 /*
42145 ** Return a sanitized version of the sector-size of OS file pFile. The
42146 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
42147 */
42148 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
42149   int iRet = sqlite3OsSectorSize(pFile);
42150   if( iRet<32 ){
42151     iRet = 512;
42152   }else if( iRet>MAX_SECTOR_SIZE ){
42153     assert( MAX_SECTOR_SIZE>=512 );
42154     iRet = MAX_SECTOR_SIZE;
42155   }
42156   return iRet;
42157 }
42158
42159 /*
42160 ** Set the value of the Pager.sectorSize variable for the given
42161 ** pager based on the value returned by the xSectorSize method
42162 ** of the open database file. The sector size will be used used
42163 ** to determine the size and alignment of journal header and
42164 ** master journal pointers within created journal files.
42165 **
42166 ** For temporary files the effective sector size is always 512 bytes.
42167 **
42168 ** Otherwise, for non-temporary files, the effective sector size is
42169 ** the value returned by the xSectorSize() method rounded up to 32 if
42170 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
42171 ** is greater than MAX_SECTOR_SIZE.
42172 **
42173 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
42174 ** the effective sector size to its minimum value (512).  The purpose of
42175 ** pPager->sectorSize is to define the "blast radius" of bytes that
42176 ** might change if a crash occurs while writing to a single byte in
42177 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
42178 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
42179 ** size.  For backwards compatibility of the rollback journal file format,
42180 ** we cannot reduce the effective sector size below 512.
42181 */
42182 static void setSectorSize(Pager *pPager){
42183   assert( isOpen(pPager->fd) || pPager->tempFile );
42184
42185   if( pPager->tempFile
42186    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
42187               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
42188   ){
42189     /* Sector size doesn't matter for temporary files. Also, the file
42190     ** may not have been opened yet, in which case the OsSectorSize()
42191     ** call will segfault. */
42192     pPager->sectorSize = 512;
42193   }else{
42194     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
42195   }
42196 }
42197
42198 /*
42199 ** Playback the journal and thus restore the database file to
42200 ** the state it was in before we started making changes.
42201 **
42202 ** The journal file format is as follows:
42203 **
42204 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
42205 **  (2)  4 byte big-endian integer which is the number of valid page records
42206 **       in the journal.  If this value is 0xffffffff, then compute the
42207 **       number of page records from the journal size.
42208 **  (3)  4 byte big-endian integer which is the initial value for the
42209 **       sanity checksum.
42210 **  (4)  4 byte integer which is the number of pages to truncate the
42211 **       database to during a rollback.
42212 **  (5)  4 byte big-endian integer which is the sector size.  The header
42213 **       is this many bytes in size.
42214 **  (6)  4 byte big-endian integer which is the page size.
42215 **  (7)  zero padding out to the next sector size.
42216 **  (8)  Zero or more pages instances, each as follows:
42217 **        +  4 byte page number.
42218 **        +  pPager->pageSize bytes of data.
42219 **        +  4 byte checksum
42220 **
42221 ** When we speak of the journal header, we mean the first 7 items above.
42222 ** Each entry in the journal is an instance of the 8th item.
42223 **
42224 ** Call the value from the second bullet "nRec".  nRec is the number of
42225 ** valid page entries in the journal.  In most cases, you can compute the
42226 ** value of nRec from the size of the journal file.  But if a power
42227 ** failure occurred while the journal was being written, it could be the
42228 ** case that the size of the journal file had already been increased but
42229 ** the extra entries had not yet made it safely to disk.  In such a case,
42230 ** the value of nRec computed from the file size would be too large.  For
42231 ** that reason, we always use the nRec value in the header.
42232 **
42233 ** If the nRec value is 0xffffffff it means that nRec should be computed
42234 ** from the file size.  This value is used when the user selects the
42235 ** no-sync option for the journal.  A power failure could lead to corruption
42236 ** in this case.  But for things like temporary table (which will be
42237 ** deleted when the power is restored) we don't care.
42238 **
42239 ** If the file opened as the journal file is not a well-formed
42240 ** journal file then all pages up to the first corrupted page are rolled
42241 ** back (or no pages if the journal header is corrupted). The journal file
42242 ** is then deleted and SQLITE_OK returned, just as if no corruption had
42243 ** been encountered.
42244 **
42245 ** If an I/O or malloc() error occurs, the journal-file is not deleted
42246 ** and an error code is returned.
42247 **
42248 ** The isHot parameter indicates that we are trying to rollback a journal
42249 ** that might be a hot journal.  Or, it could be that the journal is
42250 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
42251 ** If the journal really is hot, reset the pager cache prior rolling
42252 ** back any content.  If the journal is merely persistent, no reset is
42253 ** needed.
42254 */
42255 static int pager_playback(Pager *pPager, int isHot){
42256   sqlite3_vfs *pVfs = pPager->pVfs;
42257   i64 szJ;                 /* Size of the journal file in bytes */
42258   u32 nRec;                /* Number of Records in the journal */
42259   u32 u;                   /* Unsigned loop counter */
42260   Pgno mxPg = 0;           /* Size of the original file in pages */
42261   int rc;                  /* Result code of a subroutine */
42262   int res = 1;             /* Value returned by sqlite3OsAccess() */
42263   char *zMaster = 0;       /* Name of master journal file if any */
42264   int needPagerReset;      /* True to reset page prior to first page rollback */
42265
42266   /* Figure out how many records are in the journal.  Abort early if
42267   ** the journal is empty.
42268   */
42269   assert( isOpen(pPager->jfd) );
42270   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
42271   if( rc!=SQLITE_OK ){
42272     goto end_playback;
42273   }
42274
42275   /* Read the master journal name from the journal, if it is present.
42276   ** If a master journal file name is specified, but the file is not
42277   ** present on disk, then the journal is not hot and does not need to be
42278   ** played back.
42279   **
42280   ** TODO: Technically the following is an error because it assumes that
42281   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
42282   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
42283   **  mxPathname is 512, which is the same as the minimum allowable value
42284   ** for pageSize.
42285   */
42286   zMaster = pPager->pTmpSpace;
42287   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42288   if( rc==SQLITE_OK && zMaster[0] ){
42289     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
42290   }
42291   zMaster = 0;
42292   if( rc!=SQLITE_OK || !res ){
42293     goto end_playback;
42294   }
42295   pPager->journalOff = 0;
42296   needPagerReset = isHot;
42297
42298   /* This loop terminates either when a readJournalHdr() or
42299   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
42300   ** occurs.
42301   */
42302   while( 1 ){
42303     /* Read the next journal header from the journal file.  If there are
42304     ** not enough bytes left in the journal file for a complete header, or
42305     ** it is corrupted, then a process must have failed while writing it.
42306     ** This indicates nothing more needs to be rolled back.
42307     */
42308     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
42309     if( rc!=SQLITE_OK ){
42310       if( rc==SQLITE_DONE ){
42311         rc = SQLITE_OK;
42312       }
42313       goto end_playback;
42314     }
42315
42316     /* If nRec is 0xffffffff, then this journal was created by a process
42317     ** working in no-sync mode. This means that the rest of the journal
42318     ** file consists of pages, there are no more journal headers. Compute
42319     ** the value of nRec based on this assumption.
42320     */
42321     if( nRec==0xffffffff ){
42322       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
42323       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
42324     }
42325
42326     /* If nRec is 0 and this rollback is of a transaction created by this
42327     ** process and if this is the final header in the journal, then it means
42328     ** that this part of the journal was being filled but has not yet been
42329     ** synced to disk.  Compute the number of pages based on the remaining
42330     ** size of the file.
42331     **
42332     ** The third term of the test was added to fix ticket #2565.
42333     ** When rolling back a hot journal, nRec==0 always means that the next
42334     ** chunk of the journal contains zero pages to be rolled back.  But
42335     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
42336     ** the journal, it means that the journal might contain additional
42337     ** pages that need to be rolled back and that the number of pages
42338     ** should be computed based on the journal file size.
42339     */
42340     if( nRec==0 && !isHot &&
42341         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
42342       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
42343     }
42344
42345     /* If this is the first header read from the journal, truncate the
42346     ** database file back to its original size.
42347     */
42348     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
42349       rc = pager_truncate(pPager, mxPg);
42350       if( rc!=SQLITE_OK ){
42351         goto end_playback;
42352       }
42353       pPager->dbSize = mxPg;
42354     }
42355
42356     /* Copy original pages out of the journal and back into the
42357     ** database file and/or page cache.
42358     */
42359     for(u=0; u<nRec; u++){
42360       if( needPagerReset ){
42361         pager_reset(pPager);
42362         needPagerReset = 0;
42363       }
42364       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
42365       if( rc!=SQLITE_OK ){
42366         if( rc==SQLITE_DONE ){
42367           pPager->journalOff = szJ;
42368           break;
42369         }else if( rc==SQLITE_IOERR_SHORT_READ ){
42370           /* If the journal has been truncated, simply stop reading and
42371           ** processing the journal. This might happen if the journal was
42372           ** not completely written and synced prior to a crash.  In that
42373           ** case, the database should have never been written in the
42374           ** first place so it is OK to simply abandon the rollback. */
42375           rc = SQLITE_OK;
42376           goto end_playback;
42377         }else{
42378           /* If we are unable to rollback, quit and return the error
42379           ** code.  This will cause the pager to enter the error state
42380           ** so that no further harm will be done.  Perhaps the next
42381           ** process to come along will be able to rollback the database.
42382           */
42383           goto end_playback;
42384         }
42385       }
42386     }
42387   }
42388   /*NOTREACHED*/
42389   assert( 0 );
42390
42391 end_playback:
42392   /* Following a rollback, the database file should be back in its original
42393   ** state prior to the start of the transaction, so invoke the
42394   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
42395   ** assertion that the transaction counter was modified.
42396   */
42397 #ifdef SQLITE_DEBUG
42398   if( pPager->fd->pMethods ){
42399     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
42400   }
42401 #endif
42402
42403   /* If this playback is happening automatically as a result of an IO or
42404   ** malloc error that occurred after the change-counter was updated but
42405   ** before the transaction was committed, then the change-counter
42406   ** modification may just have been reverted. If this happens in exclusive
42407   ** mode, then subsequent transactions performed by the connection will not
42408   ** update the change-counter at all. This may lead to cache inconsistency
42409   ** problems for other processes at some point in the future. So, just
42410   ** in case this has happened, clear the changeCountDone flag now.
42411   */
42412   pPager->changeCountDone = pPager->tempFile;
42413
42414   if( rc==SQLITE_OK ){
42415     zMaster = pPager->pTmpSpace;
42416     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42417     testcase( rc!=SQLITE_OK );
42418   }
42419   if( rc==SQLITE_OK
42420    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42421   ){
42422     rc = sqlite3PagerSync(pPager);
42423   }
42424   if( rc==SQLITE_OK ){
42425     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
42426     testcase( rc!=SQLITE_OK );
42427   }
42428   if( rc==SQLITE_OK && zMaster[0] && res ){
42429     /* If there was a master journal and this routine will return success,
42430     ** see if it is possible to delete the master journal.
42431     */
42432     rc = pager_delmaster(pPager, zMaster);
42433     testcase( rc!=SQLITE_OK );
42434   }
42435
42436   /* The Pager.sectorSize variable may have been updated while rolling
42437   ** back a journal created by a process with a different sector size
42438   ** value. Reset it to the correct value for this process.
42439   */
42440   setSectorSize(pPager);
42441   return rc;
42442 }
42443
42444
42445 /*
42446 ** Read the content for page pPg out of the database file and into
42447 ** pPg->pData. A shared lock or greater must be held on the database
42448 ** file before this function is called.
42449 **
42450 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
42451 ** the value read from the database file.
42452 **
42453 ** If an IO error occurs, then the IO error is returned to the caller.
42454 ** Otherwise, SQLITE_OK is returned.
42455 */
42456 static int readDbPage(PgHdr *pPg){
42457   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
42458   Pgno pgno = pPg->pgno;       /* Page number to read */
42459   int rc = SQLITE_OK;          /* Return code */
42460   int isInWal = 0;             /* True if page is in log file */
42461   int pgsz = pPager->pageSize; /* Number of bytes to read */
42462
42463   assert( pPager->eState>=PAGER_READER && !MEMDB );
42464   assert( isOpen(pPager->fd) );
42465
42466   if( NEVER(!isOpen(pPager->fd)) ){
42467     assert( pPager->tempFile );
42468     memset(pPg->pData, 0, pPager->pageSize);
42469     return SQLITE_OK;
42470   }
42471
42472   if( pagerUseWal(pPager) ){
42473     /* Try to pull the page from the write-ahead log. */
42474     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
42475   }
42476   if( rc==SQLITE_OK && !isInWal ){
42477     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
42478     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
42479     if( rc==SQLITE_IOERR_SHORT_READ ){
42480       rc = SQLITE_OK;
42481     }
42482   }
42483
42484   if( pgno==1 ){
42485     if( rc ){
42486       /* If the read is unsuccessful, set the dbFileVers[] to something
42487       ** that will never be a valid file version.  dbFileVers[] is a copy
42488       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
42489       ** zero or the size of the database in page. Bytes 32..35 and 35..39
42490       ** should be page numbers which are never 0xffffffff.  So filling
42491       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
42492       **
42493       ** For an encrypted database, the situation is more complex:  bytes
42494       ** 24..39 of the database are white noise.  But the probability of
42495       ** white noising equaling 16 bytes of 0xff is vanishingly small so
42496       ** we should still be ok.
42497       */
42498       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
42499     }else{
42500       u8 *dbFileVers = &((u8*)pPg->pData)[24];
42501       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
42502     }
42503   }
42504   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
42505
42506   PAGER_INCR(sqlite3_pager_readdb_count);
42507   PAGER_INCR(pPager->nRead);
42508   IOTRACE(("PGIN %p %d\n", pPager, pgno));
42509   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
42510                PAGERID(pPager), pgno, pager_pagehash(pPg)));
42511
42512   return rc;
42513 }
42514
42515 /*
42516 ** Update the value of the change-counter at offsets 24 and 92 in
42517 ** the header and the sqlite version number at offset 96.
42518 **
42519 ** This is an unconditional update.  See also the pager_incr_changecounter()
42520 ** routine which only updates the change-counter if the update is actually
42521 ** needed, as determined by the pPager->changeCountDone state variable.
42522 */
42523 static void pager_write_changecounter(PgHdr *pPg){
42524   u32 change_counter;
42525
42526   /* Increment the value just read and write it back to byte 24. */
42527   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
42528   put32bits(((char*)pPg->pData)+24, change_counter);
42529
42530   /* Also store the SQLite version number in bytes 96..99 and in
42531   ** bytes 92..95 store the change counter for which the version number
42532   ** is valid. */
42533   put32bits(((char*)pPg->pData)+92, change_counter);
42534   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
42535 }
42536
42537 #ifndef SQLITE_OMIT_WAL
42538 /*
42539 ** This function is invoked once for each page that has already been
42540 ** written into the log file when a WAL transaction is rolled back.
42541 ** Parameter iPg is the page number of said page. The pCtx argument
42542 ** is actually a pointer to the Pager structure.
42543 **
42544 ** If page iPg is present in the cache, and has no outstanding references,
42545 ** it is discarded. Otherwise, if there are one or more outstanding
42546 ** references, the page content is reloaded from the database. If the
42547 ** attempt to reload content from the database is required and fails,
42548 ** return an SQLite error code. Otherwise, SQLITE_OK.
42549 */
42550 static int pagerUndoCallback(void *pCtx, Pgno iPg){
42551   int rc = SQLITE_OK;
42552   Pager *pPager = (Pager *)pCtx;
42553   PgHdr *pPg;
42554
42555   pPg = sqlite3PagerLookup(pPager, iPg);
42556   if( pPg ){
42557     if( sqlite3PcachePageRefcount(pPg)==1 ){
42558       sqlite3PcacheDrop(pPg);
42559     }else{
42560       rc = readDbPage(pPg);
42561       if( rc==SQLITE_OK ){
42562         pPager->xReiniter(pPg);
42563       }
42564       sqlite3PagerUnref(pPg);
42565     }
42566   }
42567
42568   /* Normally, if a transaction is rolled back, any backup processes are
42569   ** updated as data is copied out of the rollback journal and into the
42570   ** database. This is not generally possible with a WAL database, as
42571   ** rollback involves simply truncating the log file. Therefore, if one
42572   ** or more frames have already been written to the log (and therefore
42573   ** also copied into the backup databases) as part of this transaction,
42574   ** the backups must be restarted.
42575   */
42576   sqlite3BackupRestart(pPager->pBackup);
42577
42578   return rc;
42579 }
42580
42581 /*
42582 ** This function is called to rollback a transaction on a WAL database.
42583 */
42584 static int pagerRollbackWal(Pager *pPager){
42585   int rc;                         /* Return Code */
42586   PgHdr *pList;                   /* List of dirty pages to revert */
42587
42588   /* For all pages in the cache that are currently dirty or have already
42589   ** been written (but not committed) to the log file, do one of the
42590   ** following:
42591   **
42592   **   + Discard the cached page (if refcount==0), or
42593   **   + Reload page content from the database (if refcount>0).
42594   */
42595   pPager->dbSize = pPager->dbOrigSize;
42596   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
42597   pList = sqlite3PcacheDirtyList(pPager->pPCache);
42598   while( pList && rc==SQLITE_OK ){
42599     PgHdr *pNext = pList->pDirty;
42600     rc = pagerUndoCallback((void *)pPager, pList->pgno);
42601     pList = pNext;
42602   }
42603
42604   return rc;
42605 }
42606
42607 /*
42608 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
42609 ** the contents of the list of pages headed by pList (connected by pDirty),
42610 ** this function notifies any active backup processes that the pages have
42611 ** changed.
42612 **
42613 ** The list of pages passed into this routine is always sorted by page number.
42614 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
42615 */
42616 static int pagerWalFrames(
42617   Pager *pPager,                  /* Pager object */
42618   PgHdr *pList,                   /* List of frames to log */
42619   Pgno nTruncate,                 /* Database size after this commit */
42620   int isCommit                    /* True if this is a commit */
42621 ){
42622   int rc;                         /* Return code */
42623   int nList;                      /* Number of pages in pList */
42624 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
42625   PgHdr *p;                       /* For looping over pages */
42626 #endif
42627
42628   assert( pPager->pWal );
42629   assert( pList );
42630 #ifdef SQLITE_DEBUG
42631   /* Verify that the page list is in accending order */
42632   for(p=pList; p && p->pDirty; p=p->pDirty){
42633     assert( p->pgno < p->pDirty->pgno );
42634   }
42635 #endif
42636
42637   assert( pList->pDirty==0 || isCommit );
42638   if( isCommit ){
42639     /* If a WAL transaction is being committed, there is no point in writing
42640     ** any pages with page numbers greater than nTruncate into the WAL file.
42641     ** They will never be read by any client. So remove them from the pDirty
42642     ** list here. */
42643     PgHdr *p;
42644     PgHdr **ppNext = &pList;
42645     nList = 0;
42646     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
42647       if( p->pgno<=nTruncate ){
42648         ppNext = &p->pDirty;
42649         nList++;
42650       }
42651     }
42652     assert( pList );
42653   }else{
42654     nList = 1;
42655   }
42656   pPager->aStat[PAGER_STAT_WRITE] += nList;
42657
42658   if( pList->pgno==1 ) pager_write_changecounter(pList);
42659   rc = sqlite3WalFrames(pPager->pWal,
42660       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
42661   );
42662   if( rc==SQLITE_OK && pPager->pBackup ){
42663     PgHdr *p;
42664     for(p=pList; p; p=p->pDirty){
42665       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
42666     }
42667   }
42668
42669 #ifdef SQLITE_CHECK_PAGES
42670   pList = sqlite3PcacheDirtyList(pPager->pPCache);
42671   for(p=pList; p; p=p->pDirty){
42672     pager_set_pagehash(p);
42673   }
42674 #endif
42675
42676   return rc;
42677 }
42678
42679 /*
42680 ** Begin a read transaction on the WAL.
42681 **
42682 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
42683 ** makes a snapshot of the database at the current point in time and preserves
42684 ** that snapshot for use by the reader in spite of concurrently changes by
42685 ** other writers or checkpointers.
42686 */
42687 static int pagerBeginReadTransaction(Pager *pPager){
42688   int rc;                         /* Return code */
42689   int changed = 0;                /* True if cache must be reset */
42690
42691   assert( pagerUseWal(pPager) );
42692   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42693
42694   /* sqlite3WalEndReadTransaction() was not called for the previous
42695   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
42696   ** are in locking_mode=NORMAL and EndRead() was previously called,
42697   ** the duplicate call is harmless.
42698   */
42699   sqlite3WalEndReadTransaction(pPager->pWal);
42700
42701   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
42702   if( rc!=SQLITE_OK || changed ){
42703     pager_reset(pPager);
42704   }
42705
42706   return rc;
42707 }
42708 #endif
42709
42710 /*
42711 ** This function is called as part of the transition from PAGER_OPEN
42712 ** to PAGER_READER state to determine the size of the database file
42713 ** in pages (assuming the page size currently stored in Pager.pageSize).
42714 **
42715 ** If no error occurs, SQLITE_OK is returned and the size of the database
42716 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
42717 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
42718 */
42719 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
42720   Pgno nPage;                     /* Value to return via *pnPage */
42721
42722   /* Query the WAL sub-system for the database size. The WalDbsize()
42723   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
42724   ** if the database size is not available. The database size is not
42725   ** available from the WAL sub-system if the log file is empty or
42726   ** contains no valid committed transactions.
42727   */
42728   assert( pPager->eState==PAGER_OPEN );
42729   assert( pPager->eLock>=SHARED_LOCK );
42730   nPage = sqlite3WalDbsize(pPager->pWal);
42731
42732   /* If the database size was not available from the WAL sub-system,
42733   ** determine it based on the size of the database file. If the size
42734   ** of the database file is not an integer multiple of the page-size,
42735   ** round down to the nearest page. Except, any file larger than 0
42736   ** bytes in size is considered to contain at least one page.
42737   */
42738   if( nPage==0 ){
42739     i64 n = 0;                    /* Size of db file in bytes */
42740     assert( isOpen(pPager->fd) || pPager->tempFile );
42741     if( isOpen(pPager->fd) ){
42742       int rc = sqlite3OsFileSize(pPager->fd, &n);
42743       if( rc!=SQLITE_OK ){
42744         return rc;
42745       }
42746     }
42747     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
42748   }
42749
42750   /* If the current number of pages in the file is greater than the
42751   ** configured maximum pager number, increase the allowed limit so
42752   ** that the file can be read.
42753   */
42754   if( nPage>pPager->mxPgno ){
42755     pPager->mxPgno = (Pgno)nPage;
42756   }
42757
42758   *pnPage = nPage;
42759   return SQLITE_OK;
42760 }
42761
42762 #ifndef SQLITE_OMIT_WAL
42763 /*
42764 ** Check if the *-wal file that corresponds to the database opened by pPager
42765 ** exists if the database is not empy, or verify that the *-wal file does
42766 ** not exist (by deleting it) if the database file is empty.
42767 **
42768 ** If the database is not empty and the *-wal file exists, open the pager
42769 ** in WAL mode.  If the database is empty or if no *-wal file exists and
42770 ** if no error occurs, make sure Pager.journalMode is not set to
42771 ** PAGER_JOURNALMODE_WAL.
42772 **
42773 ** Return SQLITE_OK or an error code.
42774 **
42775 ** The caller must hold a SHARED lock on the database file to call this
42776 ** function. Because an EXCLUSIVE lock on the db file is required to delete
42777 ** a WAL on a none-empty database, this ensures there is no race condition
42778 ** between the xAccess() below and an xDelete() being executed by some
42779 ** other connection.
42780 */
42781 static int pagerOpenWalIfPresent(Pager *pPager){
42782   int rc = SQLITE_OK;
42783   assert( pPager->eState==PAGER_OPEN );
42784   assert( pPager->eLock>=SHARED_LOCK );
42785
42786   if( !pPager->tempFile ){
42787     int isWal;                    /* True if WAL file exists */
42788     Pgno nPage;                   /* Size of the database file */
42789
42790     rc = pagerPagecount(pPager, &nPage);
42791     if( rc ) return rc;
42792     if( nPage==0 ){
42793       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
42794       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
42795       isWal = 0;
42796     }else{
42797       rc = sqlite3OsAccess(
42798           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
42799       );
42800     }
42801     if( rc==SQLITE_OK ){
42802       if( isWal ){
42803         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
42804         rc = sqlite3PagerOpenWal(pPager, 0);
42805       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
42806         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
42807       }
42808     }
42809   }
42810   return rc;
42811 }
42812 #endif
42813
42814 /*
42815 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
42816 ** the entire master journal file. The case pSavepoint==NULL occurs when
42817 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
42818 ** savepoint.
42819 **
42820 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
42821 ** being rolled back), then the rollback consists of up to three stages,
42822 ** performed in the order specified:
42823 **
42824 **   * Pages are played back from the main journal starting at byte
42825 **     offset PagerSavepoint.iOffset and continuing to
42826 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
42827 **     file if PagerSavepoint.iHdrOffset is zero.
42828 **
42829 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
42830 **     back starting from the journal header immediately following
42831 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
42832 **
42833 **   * Pages are then played back from the sub-journal file, starting
42834 **     with the PagerSavepoint.iSubRec and continuing to the end of
42835 **     the journal file.
42836 **
42837 ** Throughout the rollback process, each time a page is rolled back, the
42838 ** corresponding bit is set in a bitvec structure (variable pDone in the
42839 ** implementation below). This is used to ensure that a page is only
42840 ** rolled back the first time it is encountered in either journal.
42841 **
42842 ** If pSavepoint is NULL, then pages are only played back from the main
42843 ** journal file. There is no need for a bitvec in this case.
42844 **
42845 ** In either case, before playback commences the Pager.dbSize variable
42846 ** is reset to the value that it held at the start of the savepoint
42847 ** (or transaction). No page with a page-number greater than this value
42848 ** is played back. If one is encountered it is simply skipped.
42849 */
42850 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
42851   i64 szJ;                 /* Effective size of the main journal */
42852   i64 iHdrOff;             /* End of first segment of main-journal records */
42853   int rc = SQLITE_OK;      /* Return code */
42854   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
42855
42856   assert( pPager->eState!=PAGER_ERROR );
42857   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42858
42859   /* Allocate a bitvec to use to store the set of pages rolled back */
42860   if( pSavepoint ){
42861     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
42862     if( !pDone ){
42863       return SQLITE_NOMEM;
42864     }
42865   }
42866
42867   /* Set the database size back to the value it was before the savepoint
42868   ** being reverted was opened.
42869   */
42870   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
42871   pPager->changeCountDone = pPager->tempFile;
42872
42873   if( !pSavepoint && pagerUseWal(pPager) ){
42874     return pagerRollbackWal(pPager);
42875   }
42876
42877   /* Use pPager->journalOff as the effective size of the main rollback
42878   ** journal.  The actual file might be larger than this in
42879   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
42880   ** past pPager->journalOff is off-limits to us.
42881   */
42882   szJ = pPager->journalOff;
42883   assert( pagerUseWal(pPager)==0 || szJ==0 );
42884
42885   /* Begin by rolling back records from the main journal starting at
42886   ** PagerSavepoint.iOffset and continuing to the next journal header.
42887   ** There might be records in the main journal that have a page number
42888   ** greater than the current database size (pPager->dbSize) but those
42889   ** will be skipped automatically.  Pages are added to pDone as they
42890   ** are played back.
42891   */
42892   if( pSavepoint && !pagerUseWal(pPager) ){
42893     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
42894     pPager->journalOff = pSavepoint->iOffset;
42895     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
42896       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42897     }
42898     assert( rc!=SQLITE_DONE );
42899   }else{
42900     pPager->journalOff = 0;
42901   }
42902
42903   /* Continue rolling back records out of the main journal starting at
42904   ** the first journal header seen and continuing until the effective end
42905   ** of the main journal file.  Continue to skip out-of-range pages and
42906   ** continue adding pages rolled back to pDone.
42907   */
42908   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
42909     u32 ii;            /* Loop counter */
42910     u32 nJRec = 0;     /* Number of Journal Records */
42911     u32 dummy;
42912     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
42913     assert( rc!=SQLITE_DONE );
42914
42915     /*
42916     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
42917     ** test is related to ticket #2565.  See the discussion in the
42918     ** pager_playback() function for additional information.
42919     */
42920     if( nJRec==0
42921      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
42922     ){
42923       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
42924     }
42925     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
42926       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42927     }
42928     assert( rc!=SQLITE_DONE );
42929   }
42930   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
42931
42932   /* Finally,  rollback pages from the sub-journal.  Page that were
42933   ** previously rolled back out of the main journal (and are hence in pDone)
42934   ** will be skipped.  Out-of-range pages are also skipped.
42935   */
42936   if( pSavepoint ){
42937     u32 ii;            /* Loop counter */
42938     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
42939
42940     if( pagerUseWal(pPager) ){
42941       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
42942     }
42943     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
42944       assert( offset==(i64)ii*(4+pPager->pageSize) );
42945       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
42946     }
42947     assert( rc!=SQLITE_DONE );
42948   }
42949
42950   sqlite3BitvecDestroy(pDone);
42951   if( rc==SQLITE_OK ){
42952     pPager->journalOff = szJ;
42953   }
42954
42955   return rc;
42956 }
42957
42958 /*
42959 ** Change the maximum number of in-memory pages that are allowed.
42960 */
42961 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
42962   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
42963 }
42964
42965 /*
42966 ** Free as much memory as possible from the pager.
42967 */
42968 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
42969   sqlite3PcacheShrink(pPager->pPCache);
42970 }
42971
42972 /*
42973 ** Adjust the robustness of the database to damage due to OS crashes
42974 ** or power failures by changing the number of syncs()s when writing
42975 ** the rollback journal.  There are three levels:
42976 **
42977 **    OFF       sqlite3OsSync() is never called.  This is the default
42978 **              for temporary and transient files.
42979 **
42980 **    NORMAL    The journal is synced once before writes begin on the
42981 **              database.  This is normally adequate protection, but
42982 **              it is theoretically possible, though very unlikely,
42983 **              that an inopertune power failure could leave the journal
42984 **              in a state which would cause damage to the database
42985 **              when it is rolled back.
42986 **
42987 **    FULL      The journal is synced twice before writes begin on the
42988 **              database (with some additional information - the nRec field
42989 **              of the journal header - being written in between the two
42990 **              syncs).  If we assume that writing a
42991 **              single disk sector is atomic, then this mode provides
42992 **              assurance that the journal will not be corrupted to the
42993 **              point of causing damage to the database during rollback.
42994 **
42995 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
42996 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
42997 ** prior to the start of checkpoint and that the database file is synced
42998 ** at the conclusion of the checkpoint if the entire content of the WAL
42999 ** was written back into the database.  But no sync operations occur for
43000 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
43001 ** file is synced following each commit operation, in addition to the
43002 ** syncs associated with NORMAL.
43003 **
43004 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
43005 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
43006 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
43007 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
43008 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
43009 ** synchronous=FULL versus synchronous=NORMAL setting determines when
43010 ** the xSync primitive is called and is relevant to all platforms.
43011 **
43012 ** Numeric values associated with these states are OFF==1, NORMAL=2,
43013 ** and FULL=3.
43014 */
43015 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
43016 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
43017   Pager *pPager,        /* The pager to set safety level for */
43018   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
43019   int bFullFsync,       /* PRAGMA fullfsync */
43020   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
43021 ){
43022   assert( level>=1 && level<=3 );
43023   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
43024   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
43025   if( pPager->noSync ){
43026     pPager->syncFlags = 0;
43027     pPager->ckptSyncFlags = 0;
43028   }else if( bFullFsync ){
43029     pPager->syncFlags = SQLITE_SYNC_FULL;
43030     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
43031   }else if( bCkptFullFsync ){
43032     pPager->syncFlags = SQLITE_SYNC_NORMAL;
43033     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
43034   }else{
43035     pPager->syncFlags = SQLITE_SYNC_NORMAL;
43036     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
43037   }
43038   pPager->walSyncFlags = pPager->syncFlags;
43039   if( pPager->fullSync ){
43040     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
43041   }
43042 }
43043 #endif
43044
43045 /*
43046 ** The following global variable is incremented whenever the library
43047 ** attempts to open a temporary file.  This information is used for
43048 ** testing and analysis only.
43049 */
43050 #ifdef SQLITE_TEST
43051 SQLITE_API int sqlite3_opentemp_count = 0;
43052 #endif
43053
43054 /*
43055 ** Open a temporary file.
43056 **
43057 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
43058 ** or some other error code if we fail. The OS will automatically
43059 ** delete the temporary file when it is closed.
43060 **
43061 ** The flags passed to the VFS layer xOpen() call are those specified
43062 ** by parameter vfsFlags ORed with the following:
43063 **
43064 **     SQLITE_OPEN_READWRITE
43065 **     SQLITE_OPEN_CREATE
43066 **     SQLITE_OPEN_EXCLUSIVE
43067 **     SQLITE_OPEN_DELETEONCLOSE
43068 */
43069 static int pagerOpentemp(
43070   Pager *pPager,        /* The pager object */
43071   sqlite3_file *pFile,  /* Write the file descriptor here */
43072   int vfsFlags          /* Flags passed through to the VFS */
43073 ){
43074   int rc;               /* Return code */
43075
43076 #ifdef SQLITE_TEST
43077   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
43078 #endif
43079
43080   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
43081             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
43082   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
43083   assert( rc!=SQLITE_OK || isOpen(pFile) );
43084   return rc;
43085 }
43086
43087 /*
43088 ** Set the busy handler function.
43089 **
43090 ** The pager invokes the busy-handler if sqlite3OsLock() returns
43091 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
43092 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
43093 ** lock. It does *not* invoke the busy handler when upgrading from
43094 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
43095 ** (which occurs during hot-journal rollback). Summary:
43096 **
43097 **   Transition                        | Invokes xBusyHandler
43098 **   --------------------------------------------------------
43099 **   NO_LOCK       -> SHARED_LOCK      | Yes
43100 **   SHARED_LOCK   -> RESERVED_LOCK    | No
43101 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
43102 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
43103 **
43104 ** If the busy-handler callback returns non-zero, the lock is
43105 ** retried. If it returns zero, then the SQLITE_BUSY error is
43106 ** returned to the caller of the pager API function.
43107 */
43108 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
43109   Pager *pPager,                       /* Pager object */
43110   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
43111   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
43112 ){
43113   pPager->xBusyHandler = xBusyHandler;
43114   pPager->pBusyHandlerArg = pBusyHandlerArg;
43115
43116   if( isOpen(pPager->fd) ){
43117     void **ap = (void **)&pPager->xBusyHandler;
43118     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
43119     assert( ap[1]==pBusyHandlerArg );
43120     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
43121   }
43122 }
43123
43124 /*
43125 ** Change the page size used by the Pager object. The new page size
43126 ** is passed in *pPageSize.
43127 **
43128 ** If the pager is in the error state when this function is called, it
43129 ** is a no-op. The value returned is the error state error code (i.e.
43130 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
43131 **
43132 ** Otherwise, if all of the following are true:
43133 **
43134 **   * the new page size (value of *pPageSize) is valid (a power
43135 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
43136 **
43137 **   * there are no outstanding page references, and
43138 **
43139 **   * the database is either not an in-memory database or it is
43140 **     an in-memory database that currently consists of zero pages.
43141 **
43142 ** then the pager object page size is set to *pPageSize.
43143 **
43144 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
43145 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
43146 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
43147 ** In all other cases, SQLITE_OK is returned.
43148 **
43149 ** If the page size is not changed, either because one of the enumerated
43150 ** conditions above is not true, the pager was in error state when this
43151 ** function was called, or because the memory allocation attempt failed,
43152 ** then *pPageSize is set to the old, retained page size before returning.
43153 */
43154 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
43155   int rc = SQLITE_OK;
43156
43157   /* It is not possible to do a full assert_pager_state() here, as this
43158   ** function may be called from within PagerOpen(), before the state
43159   ** of the Pager object is internally consistent.
43160   **
43161   ** At one point this function returned an error if the pager was in
43162   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
43163   ** there is at least one outstanding page reference, this function
43164   ** is a no-op for that case anyhow.
43165   */
43166
43167   u32 pageSize = *pPageSize;
43168   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
43169   if( (pPager->memDb==0 || pPager->dbSize==0)
43170    && sqlite3PcacheRefCount(pPager->pPCache)==0
43171    && pageSize && pageSize!=(u32)pPager->pageSize
43172   ){
43173     char *pNew = NULL;             /* New temp space */
43174     i64 nByte = 0;
43175
43176     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
43177       rc = sqlite3OsFileSize(pPager->fd, &nByte);
43178     }
43179     if( rc==SQLITE_OK ){
43180       pNew = (char *)sqlite3PageMalloc(pageSize);
43181       if( !pNew ) rc = SQLITE_NOMEM;
43182     }
43183
43184     if( rc==SQLITE_OK ){
43185       pager_reset(pPager);
43186       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
43187       pPager->pageSize = pageSize;
43188       sqlite3PageFree(pPager->pTmpSpace);
43189       pPager->pTmpSpace = pNew;
43190       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
43191     }
43192   }
43193
43194   *pPageSize = pPager->pageSize;
43195   if( rc==SQLITE_OK ){
43196     if( nReserve<0 ) nReserve = pPager->nReserve;
43197     assert( nReserve>=0 && nReserve<1000 );
43198     pPager->nReserve = (i16)nReserve;
43199     pagerReportSize(pPager);
43200   }
43201   return rc;
43202 }
43203
43204 /*
43205 ** Return a pointer to the "temporary page" buffer held internally
43206 ** by the pager.  This is a buffer that is big enough to hold the
43207 ** entire content of a database page.  This buffer is used internally
43208 ** during rollback and will be overwritten whenever a rollback
43209 ** occurs.  But other modules are free to use it too, as long as
43210 ** no rollbacks are happening.
43211 */
43212 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
43213   return pPager->pTmpSpace;
43214 }
43215
43216 /*
43217 ** Attempt to set the maximum database page count if mxPage is positive.
43218 ** Make no changes if mxPage is zero or negative.  And never reduce the
43219 ** maximum page count below the current size of the database.
43220 **
43221 ** Regardless of mxPage, return the current maximum page count.
43222 */
43223 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
43224   if( mxPage>0 ){
43225     pPager->mxPgno = mxPage;
43226   }
43227   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
43228   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
43229   return pPager->mxPgno;
43230 }
43231
43232 /*
43233 ** The following set of routines are used to disable the simulated
43234 ** I/O error mechanism.  These routines are used to avoid simulated
43235 ** errors in places where we do not care about errors.
43236 **
43237 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
43238 ** and generate no code.
43239 */
43240 #ifdef SQLITE_TEST
43241 SQLITE_API extern int sqlite3_io_error_pending;
43242 SQLITE_API extern int sqlite3_io_error_hit;
43243 static int saved_cnt;
43244 void disable_simulated_io_errors(void){
43245   saved_cnt = sqlite3_io_error_pending;
43246   sqlite3_io_error_pending = -1;
43247 }
43248 void enable_simulated_io_errors(void){
43249   sqlite3_io_error_pending = saved_cnt;
43250 }
43251 #else
43252 # define disable_simulated_io_errors()
43253 # define enable_simulated_io_errors()
43254 #endif
43255
43256 /*
43257 ** Read the first N bytes from the beginning of the file into memory
43258 ** that pDest points to.
43259 **
43260 ** If the pager was opened on a transient file (zFilename==""), or
43261 ** opened on a file less than N bytes in size, the output buffer is
43262 ** zeroed and SQLITE_OK returned. The rationale for this is that this
43263 ** function is used to read database headers, and a new transient or
43264 ** zero sized database has a header than consists entirely of zeroes.
43265 **
43266 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
43267 ** the error code is returned to the caller and the contents of the
43268 ** output buffer undefined.
43269 */
43270 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
43271   int rc = SQLITE_OK;
43272   memset(pDest, 0, N);
43273   assert( isOpen(pPager->fd) || pPager->tempFile );
43274
43275   /* This routine is only called by btree immediately after creating
43276   ** the Pager object.  There has not been an opportunity to transition
43277   ** to WAL mode yet.
43278   */
43279   assert( !pagerUseWal(pPager) );
43280
43281   if( isOpen(pPager->fd) ){
43282     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
43283     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
43284     if( rc==SQLITE_IOERR_SHORT_READ ){
43285       rc = SQLITE_OK;
43286     }
43287   }
43288   return rc;
43289 }
43290
43291 /*
43292 ** This function may only be called when a read-transaction is open on
43293 ** the pager. It returns the total number of pages in the database.
43294 **
43295 ** However, if the file is between 1 and <page-size> bytes in size, then
43296 ** this is considered a 1 page file.
43297 */
43298 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
43299   assert( pPager->eState>=PAGER_READER );
43300   assert( pPager->eState!=PAGER_WRITER_FINISHED );
43301   *pnPage = (int)pPager->dbSize;
43302 }
43303
43304
43305 /*
43306 ** Try to obtain a lock of type locktype on the database file. If
43307 ** a similar or greater lock is already held, this function is a no-op
43308 ** (returning SQLITE_OK immediately).
43309 **
43310 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
43311 ** the busy callback if the lock is currently not available. Repeat
43312 ** until the busy callback returns false or until the attempt to
43313 ** obtain the lock succeeds.
43314 **
43315 ** Return SQLITE_OK on success and an error code if we cannot obtain
43316 ** the lock. If the lock is obtained successfully, set the Pager.state
43317 ** variable to locktype before returning.
43318 */
43319 static int pager_wait_on_lock(Pager *pPager, int locktype){
43320   int rc;                              /* Return code */
43321
43322   /* Check that this is either a no-op (because the requested lock is
43323   ** already held, or one of the transistions that the busy-handler
43324   ** may be invoked during, according to the comment above
43325   ** sqlite3PagerSetBusyhandler().
43326   */
43327   assert( (pPager->eLock>=locktype)
43328        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
43329        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
43330   );
43331
43332   do {
43333     rc = pagerLockDb(pPager, locktype);
43334   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
43335   return rc;
43336 }
43337
43338 /*
43339 ** Function assertTruncateConstraint(pPager) checks that one of the
43340 ** following is true for all dirty pages currently in the page-cache:
43341 **
43342 **   a) The page number is less than or equal to the size of the
43343 **      current database image, in pages, OR
43344 **
43345 **   b) if the page content were written at this time, it would not
43346 **      be necessary to write the current content out to the sub-journal
43347 **      (as determined by function subjRequiresPage()).
43348 **
43349 ** If the condition asserted by this function were not true, and the
43350 ** dirty page were to be discarded from the cache via the pagerStress()
43351 ** routine, pagerStress() would not write the current page content to
43352 ** the database file. If a savepoint transaction were rolled back after
43353 ** this happened, the correct behaviour would be to restore the current
43354 ** content of the page. However, since this content is not present in either
43355 ** the database file or the portion of the rollback journal and
43356 ** sub-journal rolled back the content could not be restored and the
43357 ** database image would become corrupt. It is therefore fortunate that
43358 ** this circumstance cannot arise.
43359 */
43360 #if defined(SQLITE_DEBUG)
43361 static void assertTruncateConstraintCb(PgHdr *pPg){
43362   assert( pPg->flags&PGHDR_DIRTY );
43363   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
43364 }
43365 static void assertTruncateConstraint(Pager *pPager){
43366   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
43367 }
43368 #else
43369 # define assertTruncateConstraint(pPager)
43370 #endif
43371
43372 /*
43373 ** Truncate the in-memory database file image to nPage pages. This
43374 ** function does not actually modify the database file on disk. It
43375 ** just sets the internal state of the pager object so that the
43376 ** truncation will be done when the current transaction is committed.
43377 */
43378 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
43379   assert( pPager->dbSize>=nPage );
43380   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43381   pPager->dbSize = nPage;
43382   assertTruncateConstraint(pPager);
43383 }
43384
43385
43386 /*
43387 ** This function is called before attempting a hot-journal rollback. It
43388 ** syncs the journal file to disk, then sets pPager->journalHdr to the
43389 ** size of the journal file so that the pager_playback() routine knows
43390 ** that the entire journal file has been synced.
43391 **
43392 ** Syncing a hot-journal to disk before attempting to roll it back ensures
43393 ** that if a power-failure occurs during the rollback, the process that
43394 ** attempts rollback following system recovery sees the same journal
43395 ** content as this process.
43396 **
43397 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
43398 ** an SQLite error code.
43399 */
43400 static int pagerSyncHotJournal(Pager *pPager){
43401   int rc = SQLITE_OK;
43402   if( !pPager->noSync ){
43403     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
43404   }
43405   if( rc==SQLITE_OK ){
43406     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
43407   }
43408   return rc;
43409 }
43410
43411 /*
43412 ** Shutdown the page cache.  Free all memory and close all files.
43413 **
43414 ** If a transaction was in progress when this routine is called, that
43415 ** transaction is rolled back.  All outstanding pages are invalidated
43416 ** and their memory is freed.  Any attempt to use a page associated
43417 ** with this page cache after this function returns will likely
43418 ** result in a coredump.
43419 **
43420 ** This function always succeeds. If a transaction is active an attempt
43421 ** is made to roll it back. If an error occurs during the rollback
43422 ** a hot journal may be left in the filesystem but no error is returned
43423 ** to the caller.
43424 */
43425 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
43426   u8 *pTmp = (u8 *)pPager->pTmpSpace;
43427
43428   assert( assert_pager_state(pPager) );
43429   disable_simulated_io_errors();
43430   sqlite3BeginBenignMalloc();
43431   /* pPager->errCode = 0; */
43432   pPager->exclusiveMode = 0;
43433 #ifndef SQLITE_OMIT_WAL
43434   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
43435   pPager->pWal = 0;
43436 #endif
43437   pager_reset(pPager);
43438   if( MEMDB ){
43439     pager_unlock(pPager);
43440   }else{
43441     /* If it is open, sync the journal file before calling UnlockAndRollback.
43442     ** If this is not done, then an unsynced portion of the open journal
43443     ** file may be played back into the database. If a power failure occurs
43444     ** while this is happening, the database could become corrupt.
43445     **
43446     ** If an error occurs while trying to sync the journal, shift the pager
43447     ** into the ERROR state. This causes UnlockAndRollback to unlock the
43448     ** database and close the journal file without attempting to roll it
43449     ** back or finalize it. The next database user will have to do hot-journal
43450     ** rollback before accessing the database file.
43451     */
43452     if( isOpen(pPager->jfd) ){
43453       pager_error(pPager, pagerSyncHotJournal(pPager));
43454     }
43455     pagerUnlockAndRollback(pPager);
43456   }
43457   sqlite3EndBenignMalloc();
43458   enable_simulated_io_errors();
43459   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
43460   IOTRACE(("CLOSE %p\n", pPager))
43461   sqlite3OsClose(pPager->jfd);
43462   sqlite3OsClose(pPager->fd);
43463   sqlite3PageFree(pTmp);
43464   sqlite3PcacheClose(pPager->pPCache);
43465
43466 #ifdef SQLITE_HAS_CODEC
43467   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43468 #endif
43469
43470   assert( !pPager->aSavepoint && !pPager->pInJournal );
43471   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
43472
43473   sqlite3_free(pPager);
43474   return SQLITE_OK;
43475 }
43476
43477 #if !defined(NDEBUG) || defined(SQLITE_TEST)
43478 /*
43479 ** Return the page number for page pPg.
43480 */
43481 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
43482   return pPg->pgno;
43483 }
43484 #endif
43485
43486 /*
43487 ** Increment the reference count for page pPg.
43488 */
43489 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
43490   sqlite3PcacheRef(pPg);
43491 }
43492
43493 /*
43494 ** Sync the journal. In other words, make sure all the pages that have
43495 ** been written to the journal have actually reached the surface of the
43496 ** disk and can be restored in the event of a hot-journal rollback.
43497 **
43498 ** If the Pager.noSync flag is set, then this function is a no-op.
43499 ** Otherwise, the actions required depend on the journal-mode and the
43500 ** device characteristics of the file-system, as follows:
43501 **
43502 **   * If the journal file is an in-memory journal file, no action need
43503 **     be taken.
43504 **
43505 **   * Otherwise, if the device does not support the SAFE_APPEND property,
43506 **     then the nRec field of the most recently written journal header
43507 **     is updated to contain the number of journal records that have
43508 **     been written following it. If the pager is operating in full-sync
43509 **     mode, then the journal file is synced before this field is updated.
43510 **
43511 **   * If the device does not support the SEQUENTIAL property, then
43512 **     journal file is synced.
43513 **
43514 ** Or, in pseudo-code:
43515 **
43516 **   if( NOT <in-memory journal> ){
43517 **     if( NOT SAFE_APPEND ){
43518 **       if( <full-sync mode> ) xSync(<journal file>);
43519 **       <update nRec field>
43520 **     }
43521 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
43522 **   }
43523 **
43524 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
43525 ** page currently held in memory before returning SQLITE_OK. If an IO
43526 ** error is encountered, then the IO error code is returned to the caller.
43527 */
43528 static int syncJournal(Pager *pPager, int newHdr){
43529   int rc;                         /* Return code */
43530
43531   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43532        || pPager->eState==PAGER_WRITER_DBMOD
43533   );
43534   assert( assert_pager_state(pPager) );
43535   assert( !pagerUseWal(pPager) );
43536
43537   rc = sqlite3PagerExclusiveLock(pPager);
43538   if( rc!=SQLITE_OK ) return rc;
43539
43540   if( !pPager->noSync ){
43541     assert( !pPager->tempFile );
43542     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
43543       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
43544       assert( isOpen(pPager->jfd) );
43545
43546       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
43547         /* This block deals with an obscure problem. If the last connection
43548         ** that wrote to this database was operating in persistent-journal
43549         ** mode, then the journal file may at this point actually be larger
43550         ** than Pager.journalOff bytes. If the next thing in the journal
43551         ** file happens to be a journal-header (written as part of the
43552         ** previous connection's transaction), and a crash or power-failure
43553         ** occurs after nRec is updated but before this connection writes
43554         ** anything else to the journal file (or commits/rolls back its
43555         ** transaction), then SQLite may become confused when doing the
43556         ** hot-journal rollback following recovery. It may roll back all
43557         ** of this connections data, then proceed to rolling back the old,
43558         ** out-of-date data that follows it. Database corruption.
43559         **
43560         ** To work around this, if the journal file does appear to contain
43561         ** a valid header following Pager.journalOff, then write a 0x00
43562         ** byte to the start of it to prevent it from being recognized.
43563         **
43564         ** Variable iNextHdrOffset is set to the offset at which this
43565         ** problematic header will occur, if it exists. aMagic is used
43566         ** as a temporary buffer to inspect the first couple of bytes of
43567         ** the potential journal header.
43568         */
43569         i64 iNextHdrOffset;
43570         u8 aMagic[8];
43571         u8 zHeader[sizeof(aJournalMagic)+4];
43572
43573         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
43574         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
43575
43576         iNextHdrOffset = journalHdrOffset(pPager);
43577         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
43578         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
43579           static const u8 zerobyte = 0;
43580           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
43581         }
43582         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
43583           return rc;
43584         }
43585
43586         /* Write the nRec value into the journal file header. If in
43587         ** full-synchronous mode, sync the journal first. This ensures that
43588         ** all data has really hit the disk before nRec is updated to mark
43589         ** it as a candidate for rollback.
43590         **
43591         ** This is not required if the persistent media supports the
43592         ** SAFE_APPEND property. Because in this case it is not possible
43593         ** for garbage data to be appended to the file, the nRec field
43594         ** is populated with 0xFFFFFFFF when the journal header is written
43595         ** and never needs to be updated.
43596         */
43597         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
43598           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43599           IOTRACE(("JSYNC %p\n", pPager))
43600           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
43601           if( rc!=SQLITE_OK ) return rc;
43602         }
43603         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
43604         rc = sqlite3OsWrite(
43605             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
43606         );
43607         if( rc!=SQLITE_OK ) return rc;
43608       }
43609       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
43610         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43611         IOTRACE(("JSYNC %p\n", pPager))
43612         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
43613           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
43614         );
43615         if( rc!=SQLITE_OK ) return rc;
43616       }
43617
43618       pPager->journalHdr = pPager->journalOff;
43619       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
43620         pPager->nRec = 0;
43621         rc = writeJournalHdr(pPager);
43622         if( rc!=SQLITE_OK ) return rc;
43623       }
43624     }else{
43625       pPager->journalHdr = pPager->journalOff;
43626     }
43627   }
43628
43629   /* Unless the pager is in noSync mode, the journal file was just
43630   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
43631   ** all pages.
43632   */
43633   sqlite3PcacheClearSyncFlags(pPager->pPCache);
43634   pPager->eState = PAGER_WRITER_DBMOD;
43635   assert( assert_pager_state(pPager) );
43636   return SQLITE_OK;
43637 }
43638
43639 /*
43640 ** The argument is the first in a linked list of dirty pages connected
43641 ** by the PgHdr.pDirty pointer. This function writes each one of the
43642 ** in-memory pages in the list to the database file. The argument may
43643 ** be NULL, representing an empty list. In this case this function is
43644 ** a no-op.
43645 **
43646 ** The pager must hold at least a RESERVED lock when this function
43647 ** is called. Before writing anything to the database file, this lock
43648 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
43649 ** SQLITE_BUSY is returned and no data is written to the database file.
43650 **
43651 ** If the pager is a temp-file pager and the actual file-system file
43652 ** is not yet open, it is created and opened before any data is
43653 ** written out.
43654 **
43655 ** Once the lock has been upgraded and, if necessary, the file opened,
43656 ** the pages are written out to the database file in list order. Writing
43657 ** a page is skipped if it meets either of the following criteria:
43658 **
43659 **   * The page number is greater than Pager.dbSize, or
43660 **   * The PGHDR_DONT_WRITE flag is set on the page.
43661 **
43662 ** If writing out a page causes the database file to grow, Pager.dbFileSize
43663 ** is updated accordingly. If page 1 is written out, then the value cached
43664 ** in Pager.dbFileVers[] is updated to match the new value stored in
43665 ** the database file.
43666 **
43667 ** If everything is successful, SQLITE_OK is returned. If an IO error
43668 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
43669 ** be obtained, SQLITE_BUSY is returned.
43670 */
43671 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
43672   int rc = SQLITE_OK;                  /* Return code */
43673
43674   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
43675   assert( !pagerUseWal(pPager) );
43676   assert( pPager->eState==PAGER_WRITER_DBMOD );
43677   assert( pPager->eLock==EXCLUSIVE_LOCK );
43678
43679   /* If the file is a temp-file has not yet been opened, open it now. It
43680   ** is not possible for rc to be other than SQLITE_OK if this branch
43681   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
43682   */
43683   if( !isOpen(pPager->fd) ){
43684     assert( pPager->tempFile && rc==SQLITE_OK );
43685     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
43686   }
43687
43688   /* Before the first write, give the VFS a hint of what the final
43689   ** file size will be.
43690   */
43691   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
43692   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
43693     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
43694     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
43695     pPager->dbHintSize = pPager->dbSize;
43696   }
43697
43698   while( rc==SQLITE_OK && pList ){
43699     Pgno pgno = pList->pgno;
43700
43701     /* If there are dirty pages in the page cache with page numbers greater
43702     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
43703     ** make the file smaller (presumably by auto-vacuum code). Do not write
43704     ** any such pages to the file.
43705     **
43706     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
43707     ** set (set by sqlite3PagerDontWrite()).
43708     */
43709     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
43710       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
43711       char *pData;                                   /* Data to write */
43712
43713       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
43714       if( pList->pgno==1 ) pager_write_changecounter(pList);
43715
43716       /* Encode the database */
43717       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
43718
43719       /* Write out the page data. */
43720       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
43721
43722       /* If page 1 was just written, update Pager.dbFileVers to match
43723       ** the value now stored in the database file. If writing this
43724       ** page caused the database file to grow, update dbFileSize.
43725       */
43726       if( pgno==1 ){
43727         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
43728       }
43729       if( pgno>pPager->dbFileSize ){
43730         pPager->dbFileSize = pgno;
43731       }
43732       pPager->aStat[PAGER_STAT_WRITE]++;
43733
43734       /* Update any backup objects copying the contents of this pager. */
43735       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
43736
43737       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
43738                    PAGERID(pPager), pgno, pager_pagehash(pList)));
43739       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
43740       PAGER_INCR(sqlite3_pager_writedb_count);
43741     }else{
43742       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
43743     }
43744     pager_set_pagehash(pList);
43745     pList = pList->pDirty;
43746   }
43747
43748   return rc;
43749 }
43750
43751 /*
43752 ** Ensure that the sub-journal file is open. If it is already open, this
43753 ** function is a no-op.
43754 **
43755 ** SQLITE_OK is returned if everything goes according to plan. An
43756 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
43757 ** fails.
43758 */
43759 static int openSubJournal(Pager *pPager){
43760   int rc = SQLITE_OK;
43761   if( !isOpen(pPager->sjfd) ){
43762     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
43763       sqlite3MemJournalOpen(pPager->sjfd);
43764     }else{
43765       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
43766     }
43767   }
43768   return rc;
43769 }
43770
43771 /*
43772 ** Append a record of the current state of page pPg to the sub-journal.
43773 ** It is the callers responsibility to use subjRequiresPage() to check
43774 ** that it is really required before calling this function.
43775 **
43776 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
43777 ** for all open savepoints before returning.
43778 **
43779 ** This function returns SQLITE_OK if everything is successful, an IO
43780 ** error code if the attempt to write to the sub-journal fails, or
43781 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
43782 ** bitvec.
43783 */
43784 static int subjournalPage(PgHdr *pPg){
43785   int rc = SQLITE_OK;
43786   Pager *pPager = pPg->pPager;
43787   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43788
43789     /* Open the sub-journal, if it has not already been opened */
43790     assert( pPager->useJournal );
43791     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
43792     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
43793     assert( pagerUseWal(pPager)
43794          || pageInJournal(pPg)
43795          || pPg->pgno>pPager->dbOrigSize
43796     );
43797     rc = openSubJournal(pPager);
43798
43799     /* If the sub-journal was opened successfully (or was already open),
43800     ** write the journal record into the file.  */
43801     if( rc==SQLITE_OK ){
43802       void *pData = pPg->pData;
43803       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
43804       char *pData2;
43805
43806       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
43807       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
43808       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
43809       if( rc==SQLITE_OK ){
43810         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
43811       }
43812     }
43813   }
43814   if( rc==SQLITE_OK ){
43815     pPager->nSubRec++;
43816     assert( pPager->nSavepoint>0 );
43817     rc = addToSavepointBitvecs(pPager, pPg->pgno);
43818   }
43819   return rc;
43820 }
43821
43822 /*
43823 ** This function is called by the pcache layer when it has reached some
43824 ** soft memory limit. The first argument is a pointer to a Pager object
43825 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
43826 ** database). The second argument is a reference to a page that is
43827 ** currently dirty but has no outstanding references. The page
43828 ** is always associated with the Pager object passed as the first
43829 ** argument.
43830 **
43831 ** The job of this function is to make pPg clean by writing its contents
43832 ** out to the database file, if possible. This may involve syncing the
43833 ** journal file.
43834 **
43835 ** If successful, sqlite3PcacheMakeClean() is called on the page and
43836 ** SQLITE_OK returned. If an IO error occurs while trying to make the
43837 ** page clean, the IO error code is returned. If the page cannot be
43838 ** made clean for some other reason, but no error occurs, then SQLITE_OK
43839 ** is returned by sqlite3PcacheMakeClean() is not called.
43840 */
43841 static int pagerStress(void *p, PgHdr *pPg){
43842   Pager *pPager = (Pager *)p;
43843   int rc = SQLITE_OK;
43844
43845   assert( pPg->pPager==pPager );
43846   assert( pPg->flags&PGHDR_DIRTY );
43847
43848   /* The doNotSyncSpill flag is set during times when doing a sync of
43849   ** journal (and adding a new header) is not allowed.  This occurs
43850   ** during calls to sqlite3PagerWrite() while trying to journal multiple
43851   ** pages belonging to the same sector.
43852   **
43853   ** The doNotSpill flag inhibits all cache spilling regardless of whether
43854   ** or not a sync is required.  This is set during a rollback.
43855   **
43856   ** Spilling is also prohibited when in an error state since that could
43857   ** lead to database corruption.   In the current implementaton it
43858   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
43859   ** while in the error state, hence it is impossible for this routine to
43860   ** be called in the error state.  Nevertheless, we include a NEVER()
43861   ** test for the error state as a safeguard against future changes.
43862   */
43863   if( NEVER(pPager->errCode) ) return SQLITE_OK;
43864   if( pPager->doNotSpill ) return SQLITE_OK;
43865   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
43866     return SQLITE_OK;
43867   }
43868
43869   pPg->pDirty = 0;
43870   if( pagerUseWal(pPager) ){
43871     /* Write a single frame for this page to the log. */
43872     if( subjRequiresPage(pPg) ){
43873       rc = subjournalPage(pPg);
43874     }
43875     if( rc==SQLITE_OK ){
43876       rc = pagerWalFrames(pPager, pPg, 0, 0);
43877     }
43878   }else{
43879
43880     /* Sync the journal file if required. */
43881     if( pPg->flags&PGHDR_NEED_SYNC
43882      || pPager->eState==PAGER_WRITER_CACHEMOD
43883     ){
43884       rc = syncJournal(pPager, 1);
43885     }
43886
43887     /* If the page number of this page is larger than the current size of
43888     ** the database image, it may need to be written to the sub-journal.
43889     ** This is because the call to pager_write_pagelist() below will not
43890     ** actually write data to the file in this case.
43891     **
43892     ** Consider the following sequence of events:
43893     **
43894     **   BEGIN;
43895     **     <journal page X>
43896     **     <modify page X>
43897     **     SAVEPOINT sp;
43898     **       <shrink database file to Y pages>
43899     **       pagerStress(page X)
43900     **     ROLLBACK TO sp;
43901     **
43902     ** If (X>Y), then when pagerStress is called page X will not be written
43903     ** out to the database file, but will be dropped from the cache. Then,
43904     ** following the "ROLLBACK TO sp" statement, reading page X will read
43905     ** data from the database file. This will be the copy of page X as it
43906     ** was when the transaction started, not as it was when "SAVEPOINT sp"
43907     ** was executed.
43908     **
43909     ** The solution is to write the current data for page X into the
43910     ** sub-journal file now (if it is not already there), so that it will
43911     ** be restored to its current value when the "ROLLBACK TO sp" is
43912     ** executed.
43913     */
43914     if( NEVER(
43915         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
43916     ) ){
43917       rc = subjournalPage(pPg);
43918     }
43919
43920     /* Write the contents of the page out to the database file. */
43921     if( rc==SQLITE_OK ){
43922       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
43923       rc = pager_write_pagelist(pPager, pPg);
43924     }
43925   }
43926
43927   /* Mark the page as clean. */
43928   if( rc==SQLITE_OK ){
43929     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
43930     sqlite3PcacheMakeClean(pPg);
43931   }
43932
43933   return pager_error(pPager, rc);
43934 }
43935
43936
43937 /*
43938 ** Allocate and initialize a new Pager object and put a pointer to it
43939 ** in *ppPager. The pager should eventually be freed by passing it
43940 ** to sqlite3PagerClose().
43941 **
43942 ** The zFilename argument is the path to the database file to open.
43943 ** If zFilename is NULL then a randomly-named temporary file is created
43944 ** and used as the file to be cached. Temporary files are be deleted
43945 ** automatically when they are closed. If zFilename is ":memory:" then
43946 ** all information is held in cache. It is never written to disk.
43947 ** This can be used to implement an in-memory database.
43948 **
43949 ** The nExtra parameter specifies the number of bytes of space allocated
43950 ** along with each page reference. This space is available to the user
43951 ** via the sqlite3PagerGetExtra() API.
43952 **
43953 ** The flags argument is used to specify properties that affect the
43954 ** operation of the pager. It should be passed some bitwise combination
43955 ** of the PAGER_* flags.
43956 **
43957 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
43958 ** of the xOpen() method of the supplied VFS when opening files.
43959 **
43960 ** If the pager object is allocated and the specified file opened
43961 ** successfully, SQLITE_OK is returned and *ppPager set to point to
43962 ** the new pager object. If an error occurs, *ppPager is set to NULL
43963 ** and error code returned. This function may return SQLITE_NOMEM
43964 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
43965 ** various SQLITE_IO_XXX errors.
43966 */
43967 SQLITE_PRIVATE int sqlite3PagerOpen(
43968   sqlite3_vfs *pVfs,       /* The virtual file system to use */
43969   Pager **ppPager,         /* OUT: Return the Pager structure here */
43970   const char *zFilename,   /* Name of the database file to open */
43971   int nExtra,              /* Extra bytes append to each in-memory page */
43972   int flags,               /* flags controlling this file */
43973   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
43974   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
43975 ){
43976   u8 *pPtr;
43977   Pager *pPager = 0;       /* Pager object to allocate and return */
43978   int rc = SQLITE_OK;      /* Return code */
43979   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
43980   int memDb = 0;           /* True if this is an in-memory file */
43981   int readOnly = 0;        /* True if this is a read-only file */
43982   int journalFileSize;     /* Bytes to allocate for each journal fd */
43983   char *zPathname = 0;     /* Full path to database file */
43984   int nPathname = 0;       /* Number of bytes in zPathname */
43985   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
43986   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
43987   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
43988   const char *zUri = 0;    /* URI args to copy */
43989   int nUri = 0;            /* Number of bytes of URI args at *zUri */
43990
43991   /* Figure out how much space is required for each journal file-handle
43992   ** (there are two of them, the main journal and the sub-journal). This
43993   ** is the maximum space required for an in-memory journal file handle
43994   ** and a regular journal file-handle. Note that a "regular journal-handle"
43995   ** may be a wrapper capable of caching the first portion of the journal
43996   ** file in memory to implement the atomic-write optimization (see
43997   ** source file journal.c).
43998   */
43999   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
44000     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
44001   }else{
44002     journalFileSize = ROUND8(sqlite3MemJournalSize());
44003   }
44004
44005   /* Set the output variable to NULL in case an error occurs. */
44006   *ppPager = 0;
44007
44008 #ifndef SQLITE_OMIT_MEMORYDB
44009   if( flags & PAGER_MEMORY ){
44010     memDb = 1;
44011     if( zFilename && zFilename[0] ){
44012       zPathname = sqlite3DbStrDup(0, zFilename);
44013       if( zPathname==0  ) return SQLITE_NOMEM;
44014       nPathname = sqlite3Strlen30(zPathname);
44015       zFilename = 0;
44016     }
44017   }
44018 #endif
44019
44020   /* Compute and store the full pathname in an allocated buffer pointed
44021   ** to by zPathname, length nPathname. Or, if this is a temporary file,
44022   ** leave both nPathname and zPathname set to 0.
44023   */
44024   if( zFilename && zFilename[0] ){
44025     const char *z;
44026     nPathname = pVfs->mxPathname+1;
44027     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
44028     if( zPathname==0 ){
44029       return SQLITE_NOMEM;
44030     }
44031     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
44032     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
44033     nPathname = sqlite3Strlen30(zPathname);
44034     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
44035     while( *z ){
44036       z += sqlite3Strlen30(z)+1;
44037       z += sqlite3Strlen30(z)+1;
44038     }
44039     nUri = (int)(&z[1] - zUri);
44040     assert( nUri>=0 );
44041     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
44042       /* This branch is taken when the journal path required by
44043       ** the database being opened will be more than pVfs->mxPathname
44044       ** bytes in length. This means the database cannot be opened,
44045       ** as it will not be possible to open the journal file or even
44046       ** check for a hot-journal before reading.
44047       */
44048       rc = SQLITE_CANTOPEN_BKPT;
44049     }
44050     if( rc!=SQLITE_OK ){
44051       sqlite3DbFree(0, zPathname);
44052       return rc;
44053     }
44054   }
44055
44056   /* Allocate memory for the Pager structure, PCache object, the
44057   ** three file descriptors, the database file name and the journal
44058   ** file name. The layout in memory is as follows:
44059   **
44060   **     Pager object                    (sizeof(Pager) bytes)
44061   **     PCache object                   (sqlite3PcacheSize() bytes)
44062   **     Database file handle            (pVfs->szOsFile bytes)
44063   **     Sub-journal file handle         (journalFileSize bytes)
44064   **     Main journal file handle        (journalFileSize bytes)
44065   **     Database file name              (nPathname+1 bytes)
44066   **     Journal file name               (nPathname+8+1 bytes)
44067   */
44068   pPtr = (u8 *)sqlite3MallocZero(
44069     ROUND8(sizeof(*pPager)) +      /* Pager structure */
44070     ROUND8(pcacheSize) +           /* PCache object */
44071     ROUND8(pVfs->szOsFile) +       /* The main db file */
44072     journalFileSize * 2 +          /* The two journal files */
44073     nPathname + 1 + nUri +         /* zFilename */
44074     nPathname + 8 + 2              /* zJournal */
44075 #ifndef SQLITE_OMIT_WAL
44076     + nPathname + 4 + 2            /* zWal */
44077 #endif
44078   );
44079   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
44080   if( !pPtr ){
44081     sqlite3DbFree(0, zPathname);
44082     return SQLITE_NOMEM;
44083   }
44084   pPager =              (Pager*)(pPtr);
44085   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
44086   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
44087   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
44088   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
44089   pPager->zFilename =    (char*)(pPtr += journalFileSize);
44090   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
44091
44092   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
44093   if( zPathname ){
44094     assert( nPathname>0 );
44095     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
44096     memcpy(pPager->zFilename, zPathname, nPathname);
44097     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
44098     memcpy(pPager->zJournal, zPathname, nPathname);
44099     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
44100     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
44101 #ifndef SQLITE_OMIT_WAL
44102     pPager->zWal = &pPager->zJournal[nPathname+8+1];
44103     memcpy(pPager->zWal, zPathname, nPathname);
44104     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
44105     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
44106 #endif
44107     sqlite3DbFree(0, zPathname);
44108   }
44109   pPager->pVfs = pVfs;
44110   pPager->vfsFlags = vfsFlags;
44111
44112   /* Open the pager file.
44113   */
44114   if( zFilename && zFilename[0] ){
44115     int fout = 0;                    /* VFS flags returned by xOpen() */
44116     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
44117     assert( !memDb );
44118     readOnly = (fout&SQLITE_OPEN_READONLY);
44119
44120     /* If the file was successfully opened for read/write access,
44121     ** choose a default page size in case we have to create the
44122     ** database file. The default page size is the maximum of:
44123     **
44124     **    + SQLITE_DEFAULT_PAGE_SIZE,
44125     **    + The value returned by sqlite3OsSectorSize()
44126     **    + The largest page size that can be written atomically.
44127     */
44128     if( rc==SQLITE_OK && !readOnly ){
44129       setSectorSize(pPager);
44130       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
44131       if( szPageDflt<pPager->sectorSize ){
44132         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
44133           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
44134         }else{
44135           szPageDflt = (u32)pPager->sectorSize;
44136         }
44137       }
44138 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44139       {
44140         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
44141         int ii;
44142         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
44143         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
44144         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
44145         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
44146           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
44147             szPageDflt = ii;
44148           }
44149         }
44150       }
44151 #endif
44152     }
44153   }else{
44154     /* If a temporary file is requested, it is not opened immediately.
44155     ** In this case we accept the default page size and delay actually
44156     ** opening the file until the first call to OsWrite().
44157     **
44158     ** This branch is also run for an in-memory database. An in-memory
44159     ** database is the same as a temp-file that is never written out to
44160     ** disk and uses an in-memory rollback journal.
44161     */
44162     tempFile = 1;
44163     pPager->eState = PAGER_READER;
44164     pPager->eLock = EXCLUSIVE_LOCK;
44165     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
44166   }
44167
44168   /* The following call to PagerSetPagesize() serves to set the value of
44169   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
44170   */
44171   if( rc==SQLITE_OK ){
44172     assert( pPager->memDb==0 );
44173     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
44174     testcase( rc!=SQLITE_OK );
44175   }
44176
44177   /* If an error occurred in either of the blocks above, free the
44178   ** Pager structure and close the file.
44179   */
44180   if( rc!=SQLITE_OK ){
44181     assert( !pPager->pTmpSpace );
44182     sqlite3OsClose(pPager->fd);
44183     sqlite3_free(pPager);
44184     return rc;
44185   }
44186
44187   /* Initialize the PCache object. */
44188   assert( nExtra<1000 );
44189   nExtra = ROUND8(nExtra);
44190   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
44191                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
44192
44193   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
44194   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
44195
44196   pPager->useJournal = (u8)useJournal;
44197   /* pPager->stmtOpen = 0; */
44198   /* pPager->stmtInUse = 0; */
44199   /* pPager->nRef = 0; */
44200   /* pPager->stmtSize = 0; */
44201   /* pPager->stmtJSize = 0; */
44202   /* pPager->nPage = 0; */
44203   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
44204   /* pPager->state = PAGER_UNLOCK; */
44205 #if 0
44206   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
44207 #endif
44208   /* pPager->errMask = 0; */
44209   pPager->tempFile = (u8)tempFile;
44210   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
44211           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
44212   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
44213   pPager->exclusiveMode = (u8)tempFile;
44214   pPager->changeCountDone = pPager->tempFile;
44215   pPager->memDb = (u8)memDb;
44216   pPager->readOnly = (u8)readOnly;
44217   assert( useJournal || pPager->tempFile );
44218   pPager->noSync = pPager->tempFile;
44219   if( pPager->noSync ){
44220     assert( pPager->fullSync==0 );
44221     assert( pPager->syncFlags==0 );
44222     assert( pPager->walSyncFlags==0 );
44223     assert( pPager->ckptSyncFlags==0 );
44224   }else{
44225     pPager->fullSync = 1;
44226     pPager->syncFlags = SQLITE_SYNC_NORMAL;
44227     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
44228     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
44229   }
44230   /* pPager->pFirst = 0; */
44231   /* pPager->pFirstSynced = 0; */
44232   /* pPager->pLast = 0; */
44233   pPager->nExtra = (u16)nExtra;
44234   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
44235   assert( isOpen(pPager->fd) || tempFile );
44236   setSectorSize(pPager);
44237   if( !useJournal ){
44238     pPager->journalMode = PAGER_JOURNALMODE_OFF;
44239   }else if( memDb ){
44240     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
44241   }
44242   /* pPager->xBusyHandler = 0; */
44243   /* pPager->pBusyHandlerArg = 0; */
44244   pPager->xReiniter = xReinit;
44245   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
44246
44247   *ppPager = pPager;
44248   return SQLITE_OK;
44249 }
44250
44251
44252
44253 /*
44254 ** This function is called after transitioning from PAGER_UNLOCK to
44255 ** PAGER_SHARED state. It tests if there is a hot journal present in
44256 ** the file-system for the given pager. A hot journal is one that
44257 ** needs to be played back. According to this function, a hot-journal
44258 ** file exists if the following criteria are met:
44259 **
44260 **   * The journal file exists in the file system, and
44261 **   * No process holds a RESERVED or greater lock on the database file, and
44262 **   * The database file itself is greater than 0 bytes in size, and
44263 **   * The first byte of the journal file exists and is not 0x00.
44264 **
44265 ** If the current size of the database file is 0 but a journal file
44266 ** exists, that is probably an old journal left over from a prior
44267 ** database with the same name. In this case the journal file is
44268 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
44269 ** is returned.
44270 **
44271 ** This routine does not check if there is a master journal filename
44272 ** at the end of the file. If there is, and that master journal file
44273 ** does not exist, then the journal file is not really hot. In this
44274 ** case this routine will return a false-positive. The pager_playback()
44275 ** routine will discover that the journal file is not really hot and
44276 ** will not roll it back.
44277 **
44278 ** If a hot-journal file is found to exist, *pExists is set to 1 and
44279 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
44280 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
44281 ** to determine whether or not a hot-journal file exists, the IO error
44282 ** code is returned and the value of *pExists is undefined.
44283 */
44284 static int hasHotJournal(Pager *pPager, int *pExists){
44285   sqlite3_vfs * const pVfs = pPager->pVfs;
44286   int rc = SQLITE_OK;           /* Return code */
44287   int exists = 1;               /* True if a journal file is present */
44288   int jrnlOpen = !!isOpen(pPager->jfd);
44289
44290   assert( pPager->useJournal );
44291   assert( isOpen(pPager->fd) );
44292   assert( pPager->eState==PAGER_OPEN );
44293
44294   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
44295     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
44296   ));
44297
44298   *pExists = 0;
44299   if( !jrnlOpen ){
44300     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
44301   }
44302   if( rc==SQLITE_OK && exists ){
44303     int locked = 0;             /* True if some process holds a RESERVED lock */
44304
44305     /* Race condition here:  Another process might have been holding the
44306     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
44307     ** call above, but then delete the journal and drop the lock before
44308     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
44309     ** is the case, this routine might think there is a hot journal when
44310     ** in fact there is none.  This results in a false-positive which will
44311     ** be dealt with by the playback routine.  Ticket #3883.
44312     */
44313     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
44314     if( rc==SQLITE_OK && !locked ){
44315       Pgno nPage;                 /* Number of pages in database file */
44316
44317       /* Check the size of the database file. If it consists of 0 pages,
44318       ** then delete the journal file. See the header comment above for
44319       ** the reasoning here.  Delete the obsolete journal file under
44320       ** a RESERVED lock to avoid race conditions and to avoid violating
44321       ** [H33020].
44322       */
44323       rc = pagerPagecount(pPager, &nPage);
44324       if( rc==SQLITE_OK ){
44325         if( nPage==0 ){
44326           sqlite3BeginBenignMalloc();
44327           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
44328             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
44329             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
44330           }
44331           sqlite3EndBenignMalloc();
44332         }else{
44333           /* The journal file exists and no other connection has a reserved
44334           ** or greater lock on the database file. Now check that there is
44335           ** at least one non-zero bytes at the start of the journal file.
44336           ** If there is, then we consider this journal to be hot. If not,
44337           ** it can be ignored.
44338           */
44339           if( !jrnlOpen ){
44340             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
44341             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
44342           }
44343           if( rc==SQLITE_OK ){
44344             u8 first = 0;
44345             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
44346             if( rc==SQLITE_IOERR_SHORT_READ ){
44347               rc = SQLITE_OK;
44348             }
44349             if( !jrnlOpen ){
44350               sqlite3OsClose(pPager->jfd);
44351             }
44352             *pExists = (first!=0);
44353           }else if( rc==SQLITE_CANTOPEN ){
44354             /* If we cannot open the rollback journal file in order to see if
44355             ** its has a zero header, that might be due to an I/O error, or
44356             ** it might be due to the race condition described above and in
44357             ** ticket #3883.  Either way, assume that the journal is hot.
44358             ** This might be a false positive.  But if it is, then the
44359             ** automatic journal playback and recovery mechanism will deal
44360             ** with it under an EXCLUSIVE lock where we do not need to
44361             ** worry so much with race conditions.
44362             */
44363             *pExists = 1;
44364             rc = SQLITE_OK;
44365           }
44366         }
44367       }
44368     }
44369   }
44370
44371   return rc;
44372 }
44373
44374 /*
44375 ** This function is called to obtain a shared lock on the database file.
44376 ** It is illegal to call sqlite3PagerAcquire() until after this function
44377 ** has been successfully called. If a shared-lock is already held when
44378 ** this function is called, it is a no-op.
44379 **
44380 ** The following operations are also performed by this function.
44381 **
44382 **   1) If the pager is currently in PAGER_OPEN state (no lock held
44383 **      on the database file), then an attempt is made to obtain a
44384 **      SHARED lock on the database file. Immediately after obtaining
44385 **      the SHARED lock, the file-system is checked for a hot-journal,
44386 **      which is played back if present. Following any hot-journal
44387 **      rollback, the contents of the cache are validated by checking
44388 **      the 'change-counter' field of the database file header and
44389 **      discarded if they are found to be invalid.
44390 **
44391 **   2) If the pager is running in exclusive-mode, and there are currently
44392 **      no outstanding references to any pages, and is in the error state,
44393 **      then an attempt is made to clear the error state by discarding
44394 **      the contents of the page cache and rolling back any open journal
44395 **      file.
44396 **
44397 ** If everything is successful, SQLITE_OK is returned. If an IO error
44398 ** occurs while locking the database, checking for a hot-journal file or
44399 ** rolling back a journal file, the IO error code is returned.
44400 */
44401 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
44402   int rc = SQLITE_OK;                /* Return code */
44403
44404   /* This routine is only called from b-tree and only when there are no
44405   ** outstanding pages. This implies that the pager state should either
44406   ** be OPEN or READER. READER is only possible if the pager is or was in
44407   ** exclusive access mode.
44408   */
44409   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
44410   assert( assert_pager_state(pPager) );
44411   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44412   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
44413
44414   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
44415     int bHotJournal = 1;          /* True if there exists a hot journal-file */
44416
44417     assert( !MEMDB );
44418
44419     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
44420     if( rc!=SQLITE_OK ){
44421       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
44422       goto failed;
44423     }
44424
44425     /* If a journal file exists, and there is no RESERVED lock on the
44426     ** database file, then it either needs to be played back or deleted.
44427     */
44428     if( pPager->eLock<=SHARED_LOCK ){
44429       rc = hasHotJournal(pPager, &bHotJournal);
44430     }
44431     if( rc!=SQLITE_OK ){
44432       goto failed;
44433     }
44434     if( bHotJournal ){
44435       /* Get an EXCLUSIVE lock on the database file. At this point it is
44436       ** important that a RESERVED lock is not obtained on the way to the
44437       ** EXCLUSIVE lock. If it were, another process might open the
44438       ** database file, detect the RESERVED lock, and conclude that the
44439       ** database is safe to read while this process is still rolling the
44440       ** hot-journal back.
44441       **
44442       ** Because the intermediate RESERVED lock is not requested, any
44443       ** other process attempting to access the database file will get to
44444       ** this point in the code and fail to obtain its own EXCLUSIVE lock
44445       ** on the database file.
44446       **
44447       ** Unless the pager is in locking_mode=exclusive mode, the lock is
44448       ** downgraded to SHARED_LOCK before this function returns.
44449       */
44450       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44451       if( rc!=SQLITE_OK ){
44452         goto failed;
44453       }
44454
44455       /* If it is not already open and the file exists on disk, open the
44456       ** journal for read/write access. Write access is required because
44457       ** in exclusive-access mode the file descriptor will be kept open
44458       ** and possibly used for a transaction later on. Also, write-access
44459       ** is usually required to finalize the journal in journal_mode=persist
44460       ** mode (and also for journal_mode=truncate on some systems).
44461       **
44462       ** If the journal does not exist, it usually means that some
44463       ** other connection managed to get in and roll it back before
44464       ** this connection obtained the exclusive lock above. Or, it
44465       ** may mean that the pager was in the error-state when this
44466       ** function was called and the journal file does not exist.
44467       */
44468       if( !isOpen(pPager->jfd) ){
44469         sqlite3_vfs * const pVfs = pPager->pVfs;
44470         int bExists;              /* True if journal file exists */
44471         rc = sqlite3OsAccess(
44472             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
44473         if( rc==SQLITE_OK && bExists ){
44474           int fout = 0;
44475           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
44476           assert( !pPager->tempFile );
44477           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
44478           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
44479           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
44480             rc = SQLITE_CANTOPEN_BKPT;
44481             sqlite3OsClose(pPager->jfd);
44482           }
44483         }
44484       }
44485
44486       /* Playback and delete the journal.  Drop the database write
44487       ** lock and reacquire the read lock. Purge the cache before
44488       ** playing back the hot-journal so that we don't end up with
44489       ** an inconsistent cache.  Sync the hot journal before playing
44490       ** it back since the process that crashed and left the hot journal
44491       ** probably did not sync it and we are required to always sync
44492       ** the journal before playing it back.
44493       */
44494       if( isOpen(pPager->jfd) ){
44495         assert( rc==SQLITE_OK );
44496         rc = pagerSyncHotJournal(pPager);
44497         if( rc==SQLITE_OK ){
44498           rc = pager_playback(pPager, 1);
44499           pPager->eState = PAGER_OPEN;
44500         }
44501       }else if( !pPager->exclusiveMode ){
44502         pagerUnlockDb(pPager, SHARED_LOCK);
44503       }
44504
44505       if( rc!=SQLITE_OK ){
44506         /* This branch is taken if an error occurs while trying to open
44507         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
44508         ** pager_unlock() routine will be called before returning to unlock
44509         ** the file. If the unlock attempt fails, then Pager.eLock must be
44510         ** set to UNKNOWN_LOCK (see the comment above the #define for
44511         ** UNKNOWN_LOCK above for an explanation).
44512         **
44513         ** In order to get pager_unlock() to do this, set Pager.eState to
44514         ** PAGER_ERROR now. This is not actually counted as a transition
44515         ** to ERROR state in the state diagram at the top of this file,
44516         ** since we know that the same call to pager_unlock() will very
44517         ** shortly transition the pager object to the OPEN state. Calling
44518         ** assert_pager_state() would fail now, as it should not be possible
44519         ** to be in ERROR state when there are zero outstanding page
44520         ** references.
44521         */
44522         pager_error(pPager, rc);
44523         goto failed;
44524       }
44525
44526       assert( pPager->eState==PAGER_OPEN );
44527       assert( (pPager->eLock==SHARED_LOCK)
44528            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
44529       );
44530     }
44531
44532     if( !pPager->tempFile
44533      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
44534     ){
44535       /* The shared-lock has just been acquired on the database file
44536       ** and there are already pages in the cache (from a previous
44537       ** read or write transaction).  Check to see if the database
44538       ** has been modified.  If the database has changed, flush the
44539       ** cache.
44540       **
44541       ** Database changes is detected by looking at 15 bytes beginning
44542       ** at offset 24 into the file.  The first 4 of these 16 bytes are
44543       ** a 32-bit counter that is incremented with each change.  The
44544       ** other bytes change randomly with each file change when
44545       ** a codec is in use.
44546       **
44547       ** There is a vanishingly small chance that a change will not be
44548       ** detected.  The chance of an undetected change is so small that
44549       ** it can be neglected.
44550       */
44551       Pgno nPage = 0;
44552       char dbFileVers[sizeof(pPager->dbFileVers)];
44553
44554       rc = pagerPagecount(pPager, &nPage);
44555       if( rc ) goto failed;
44556
44557       if( nPage>0 ){
44558         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
44559         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
44560         if( rc!=SQLITE_OK ){
44561           goto failed;
44562         }
44563       }else{
44564         memset(dbFileVers, 0, sizeof(dbFileVers));
44565       }
44566
44567       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
44568         pager_reset(pPager);
44569       }
44570     }
44571
44572     /* If there is a WAL file in the file-system, open this database in WAL
44573     ** mode. Otherwise, the following function call is a no-op.
44574     */
44575     rc = pagerOpenWalIfPresent(pPager);
44576 #ifndef SQLITE_OMIT_WAL
44577     assert( pPager->pWal==0 || rc==SQLITE_OK );
44578 #endif
44579   }
44580
44581   if( pagerUseWal(pPager) ){
44582     assert( rc==SQLITE_OK );
44583     rc = pagerBeginReadTransaction(pPager);
44584   }
44585
44586   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
44587     rc = pagerPagecount(pPager, &pPager->dbSize);
44588   }
44589
44590  failed:
44591   if( rc!=SQLITE_OK ){
44592     assert( !MEMDB );
44593     pager_unlock(pPager);
44594     assert( pPager->eState==PAGER_OPEN );
44595   }else{
44596     pPager->eState = PAGER_READER;
44597   }
44598   return rc;
44599 }
44600
44601 /*
44602 ** If the reference count has reached zero, rollback any active
44603 ** transaction and unlock the pager.
44604 **
44605 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
44606 ** the rollback journal, the unlock is not performed and there is
44607 ** nothing to rollback, so this routine is a no-op.
44608 */
44609 static void pagerUnlockIfUnused(Pager *pPager){
44610   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
44611     pagerUnlockAndRollback(pPager);
44612   }
44613 }
44614
44615 /*
44616 ** Acquire a reference to page number pgno in pager pPager (a page
44617 ** reference has type DbPage*). If the requested reference is
44618 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
44619 **
44620 ** If the requested page is already in the cache, it is returned.
44621 ** Otherwise, a new page object is allocated and populated with data
44622 ** read from the database file. In some cases, the pcache module may
44623 ** choose not to allocate a new page object and may reuse an existing
44624 ** object with no outstanding references.
44625 **
44626 ** The extra data appended to a page is always initialized to zeros the
44627 ** first time a page is loaded into memory. If the page requested is
44628 ** already in the cache when this function is called, then the extra
44629 ** data is left as it was when the page object was last used.
44630 **
44631 ** If the database image is smaller than the requested page or if a
44632 ** non-zero value is passed as the noContent parameter and the
44633 ** requested page is not already stored in the cache, then no
44634 ** actual disk read occurs. In this case the memory image of the
44635 ** page is initialized to all zeros.
44636 **
44637 ** If noContent is true, it means that we do not care about the contents
44638 ** of the page. This occurs in two seperate scenarios:
44639 **
44640 **   a) When reading a free-list leaf page from the database, and
44641 **
44642 **   b) When a savepoint is being rolled back and we need to load
44643 **      a new page into the cache to be filled with the data read
44644 **      from the savepoint journal.
44645 **
44646 ** If noContent is true, then the data returned is zeroed instead of
44647 ** being read from the database. Additionally, the bits corresponding
44648 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
44649 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
44650 ** savepoints are set. This means if the page is made writable at any
44651 ** point in the future, using a call to sqlite3PagerWrite(), its contents
44652 ** will not be journaled. This saves IO.
44653 **
44654 ** The acquisition might fail for several reasons.  In all cases,
44655 ** an appropriate error code is returned and *ppPage is set to NULL.
44656 **
44657 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
44658 ** to find a page in the in-memory cache first.  If the page is not already
44659 ** in memory, this routine goes to disk to read it in whereas Lookup()
44660 ** just returns 0.  This routine acquires a read-lock the first time it
44661 ** has to go to disk, and could also playback an old journal if necessary.
44662 ** Since Lookup() never goes to disk, it never has to deal with locks
44663 ** or journal files.
44664 */
44665 SQLITE_PRIVATE int sqlite3PagerAcquire(
44666   Pager *pPager,      /* The pager open on the database file */
44667   Pgno pgno,          /* Page number to fetch */
44668   DbPage **ppPage,    /* Write a pointer to the page here */
44669   int noContent       /* Do not bother reading content from disk if true */
44670 ){
44671   int rc;
44672   PgHdr *pPg;
44673
44674   assert( pPager->eState>=PAGER_READER );
44675   assert( assert_pager_state(pPager) );
44676
44677   if( pgno==0 ){
44678     return SQLITE_CORRUPT_BKPT;
44679   }
44680
44681   /* If the pager is in the error state, return an error immediately.
44682   ** Otherwise, request the page from the PCache layer. */
44683   if( pPager->errCode!=SQLITE_OK ){
44684     rc = pPager->errCode;
44685   }else{
44686     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
44687   }
44688
44689   if( rc!=SQLITE_OK ){
44690     /* Either the call to sqlite3PcacheFetch() returned an error or the
44691     ** pager was already in the error-state when this function was called.
44692     ** Set pPg to 0 and jump to the exception handler.  */
44693     pPg = 0;
44694     goto pager_acquire_err;
44695   }
44696   assert( (*ppPage)->pgno==pgno );
44697   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
44698
44699   if( (*ppPage)->pPager && !noContent ){
44700     /* In this case the pcache already contains an initialized copy of
44701     ** the page. Return without further ado.  */
44702     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
44703     pPager->aStat[PAGER_STAT_HIT]++;
44704     return SQLITE_OK;
44705
44706   }else{
44707     /* The pager cache has created a new page. Its content needs to
44708     ** be initialized.  */
44709
44710     pPg = *ppPage;
44711     pPg->pPager = pPager;
44712
44713     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
44714     ** number greater than this, or the unused locking-page, is requested. */
44715     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
44716       rc = SQLITE_CORRUPT_BKPT;
44717       goto pager_acquire_err;
44718     }
44719
44720     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
44721       if( pgno>pPager->mxPgno ){
44722         rc = SQLITE_FULL;
44723         goto pager_acquire_err;
44724       }
44725       if( noContent ){
44726         /* Failure to set the bits in the InJournal bit-vectors is benign.
44727         ** It merely means that we might do some extra work to journal a
44728         ** page that does not need to be journaled.  Nevertheless, be sure
44729         ** to test the case where a malloc error occurs while trying to set
44730         ** a bit in a bit vector.
44731         */
44732         sqlite3BeginBenignMalloc();
44733         if( pgno<=pPager->dbOrigSize ){
44734           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
44735           testcase( rc==SQLITE_NOMEM );
44736         }
44737         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
44738         testcase( rc==SQLITE_NOMEM );
44739         sqlite3EndBenignMalloc();
44740       }
44741       memset(pPg->pData, 0, pPager->pageSize);
44742       IOTRACE(("ZERO %p %d\n", pPager, pgno));
44743     }else{
44744       assert( pPg->pPager==pPager );
44745       pPager->aStat[PAGER_STAT_MISS]++;
44746       rc = readDbPage(pPg);
44747       if( rc!=SQLITE_OK ){
44748         goto pager_acquire_err;
44749       }
44750     }
44751     pager_set_pagehash(pPg);
44752   }
44753
44754   return SQLITE_OK;
44755
44756 pager_acquire_err:
44757   assert( rc!=SQLITE_OK );
44758   if( pPg ){
44759     sqlite3PcacheDrop(pPg);
44760   }
44761   pagerUnlockIfUnused(pPager);
44762
44763   *ppPage = 0;
44764   return rc;
44765 }
44766
44767 /*
44768 ** Acquire a page if it is already in the in-memory cache.  Do
44769 ** not read the page from disk.  Return a pointer to the page,
44770 ** or 0 if the page is not in cache.
44771 **
44772 ** See also sqlite3PagerGet().  The difference between this routine
44773 ** and sqlite3PagerGet() is that _get() will go to the disk and read
44774 ** in the page if the page is not already in cache.  This routine
44775 ** returns NULL if the page is not in cache or if a disk I/O error
44776 ** has ever happened.
44777 */
44778 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
44779   PgHdr *pPg = 0;
44780   assert( pPager!=0 );
44781   assert( pgno!=0 );
44782   assert( pPager->pPCache!=0 );
44783   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
44784   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
44785   return pPg;
44786 }
44787
44788 /*
44789 ** Release a page reference.
44790 **
44791 ** If the number of references to the page drop to zero, then the
44792 ** page is added to the LRU list.  When all references to all pages
44793 ** are released, a rollback occurs and the lock on the database is
44794 ** removed.
44795 */
44796 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
44797   if( pPg ){
44798     Pager *pPager = pPg->pPager;
44799     sqlite3PcacheRelease(pPg);
44800     pagerUnlockIfUnused(pPager);
44801   }
44802 }
44803
44804 /*
44805 ** This function is called at the start of every write transaction.
44806 ** There must already be a RESERVED or EXCLUSIVE lock on the database
44807 ** file when this routine is called.
44808 **
44809 ** Open the journal file for pager pPager and write a journal header
44810 ** to the start of it. If there are active savepoints, open the sub-journal
44811 ** as well. This function is only used when the journal file is being
44812 ** opened to write a rollback log for a transaction. It is not used
44813 ** when opening a hot journal file to roll it back.
44814 **
44815 ** If the journal file is already open (as it may be in exclusive mode),
44816 ** then this function just writes a journal header to the start of the
44817 ** already open file.
44818 **
44819 ** Whether or not the journal file is opened by this function, the
44820 ** Pager.pInJournal bitvec structure is allocated.
44821 **
44822 ** Return SQLITE_OK if everything is successful. Otherwise, return
44823 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
44824 ** an IO error code if opening or writing the journal file fails.
44825 */
44826 static int pager_open_journal(Pager *pPager){
44827   int rc = SQLITE_OK;                        /* Return code */
44828   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
44829
44830   assert( pPager->eState==PAGER_WRITER_LOCKED );
44831   assert( assert_pager_state(pPager) );
44832   assert( pPager->pInJournal==0 );
44833
44834   /* If already in the error state, this function is a no-op.  But on
44835   ** the other hand, this routine is never called if we are already in
44836   ** an error state. */
44837   if( NEVER(pPager->errCode) ) return pPager->errCode;
44838
44839   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
44840     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
44841     if( pPager->pInJournal==0 ){
44842       return SQLITE_NOMEM;
44843     }
44844
44845     /* Open the journal file if it is not already open. */
44846     if( !isOpen(pPager->jfd) ){
44847       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
44848         sqlite3MemJournalOpen(pPager->jfd);
44849       }else{
44850         const int flags =                   /* VFS flags to open journal file */
44851           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
44852           (pPager->tempFile ?
44853             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
44854             (SQLITE_OPEN_MAIN_JOURNAL)
44855           );
44856   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44857         rc = sqlite3JournalOpen(
44858             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
44859         );
44860   #else
44861         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
44862   #endif
44863       }
44864       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
44865     }
44866
44867
44868     /* Write the first journal header to the journal file and open
44869     ** the sub-journal if necessary.
44870     */
44871     if( rc==SQLITE_OK ){
44872       /* TODO: Check if all of these are really required. */
44873       pPager->nRec = 0;
44874       pPager->journalOff = 0;
44875       pPager->setMaster = 0;
44876       pPager->journalHdr = 0;
44877       rc = writeJournalHdr(pPager);
44878     }
44879   }
44880
44881   if( rc!=SQLITE_OK ){
44882     sqlite3BitvecDestroy(pPager->pInJournal);
44883     pPager->pInJournal = 0;
44884   }else{
44885     assert( pPager->eState==PAGER_WRITER_LOCKED );
44886     pPager->eState = PAGER_WRITER_CACHEMOD;
44887   }
44888
44889   return rc;
44890 }
44891
44892 /*
44893 ** Begin a write-transaction on the specified pager object. If a
44894 ** write-transaction has already been opened, this function is a no-op.
44895 **
44896 ** If the exFlag argument is false, then acquire at least a RESERVED
44897 ** lock on the database file. If exFlag is true, then acquire at least
44898 ** an EXCLUSIVE lock. If such a lock is already held, no locking
44899 ** functions need be called.
44900 **
44901 ** If the subjInMemory argument is non-zero, then any sub-journal opened
44902 ** within this transaction will be opened as an in-memory file. This
44903 ** has no effect if the sub-journal is already opened (as it may be when
44904 ** running in exclusive mode) or if the transaction does not require a
44905 ** sub-journal. If the subjInMemory argument is zero, then any required
44906 ** sub-journal is implemented in-memory if pPager is an in-memory database,
44907 ** or using a temporary file otherwise.
44908 */
44909 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
44910   int rc = SQLITE_OK;
44911
44912   if( pPager->errCode ) return pPager->errCode;
44913   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
44914   pPager->subjInMemory = (u8)subjInMemory;
44915
44916   if( ALWAYS(pPager->eState==PAGER_READER) ){
44917     assert( pPager->pInJournal==0 );
44918
44919     if( pagerUseWal(pPager) ){
44920       /* If the pager is configured to use locking_mode=exclusive, and an
44921       ** exclusive lock on the database is not already held, obtain it now.
44922       */
44923       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
44924         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44925         if( rc!=SQLITE_OK ){
44926           return rc;
44927         }
44928         sqlite3WalExclusiveMode(pPager->pWal, 1);
44929       }
44930
44931       /* Grab the write lock on the log file. If successful, upgrade to
44932       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
44933       ** The busy-handler is not invoked if another connection already
44934       ** holds the write-lock. If possible, the upper layer will call it.
44935       */
44936       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
44937     }else{
44938       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
44939       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
44940       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
44941       ** lock, but not when obtaining the RESERVED lock.
44942       */
44943       rc = pagerLockDb(pPager, RESERVED_LOCK);
44944       if( rc==SQLITE_OK && exFlag ){
44945         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44946       }
44947     }
44948
44949     if( rc==SQLITE_OK ){
44950       /* Change to WRITER_LOCKED state.
44951       **
44952       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
44953       ** when it has an open transaction, but never to DBMOD or FINISHED.
44954       ** This is because in those states the code to roll back savepoint
44955       ** transactions may copy data from the sub-journal into the database
44956       ** file as well as into the page cache. Which would be incorrect in
44957       ** WAL mode.
44958       */
44959       pPager->eState = PAGER_WRITER_LOCKED;
44960       pPager->dbHintSize = pPager->dbSize;
44961       pPager->dbFileSize = pPager->dbSize;
44962       pPager->dbOrigSize = pPager->dbSize;
44963       pPager->journalOff = 0;
44964     }
44965
44966     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
44967     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
44968     assert( assert_pager_state(pPager) );
44969   }
44970
44971   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
44972   return rc;
44973 }
44974
44975 /*
44976 ** Mark a single data page as writeable. The page is written into the
44977 ** main journal or sub-journal as required. If the page is written into
44978 ** one of the journals, the corresponding bit is set in the
44979 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
44980 ** of any open savepoints as appropriate.
44981 */
44982 static int pager_write(PgHdr *pPg){
44983   void *pData = pPg->pData;
44984   Pager *pPager = pPg->pPager;
44985   int rc = SQLITE_OK;
44986
44987   /* This routine is not called unless a write-transaction has already
44988   ** been started. The journal file may or may not be open at this point.
44989   ** It is never called in the ERROR state.
44990   */
44991   assert( pPager->eState==PAGER_WRITER_LOCKED
44992        || pPager->eState==PAGER_WRITER_CACHEMOD
44993        || pPager->eState==PAGER_WRITER_DBMOD
44994   );
44995   assert( assert_pager_state(pPager) );
44996
44997   /* If an error has been previously detected, report the same error
44998   ** again. This should not happen, but the check provides robustness. */
44999   if( NEVER(pPager->errCode) )  return pPager->errCode;
45000
45001   /* Higher-level routines never call this function if database is not
45002   ** writable.  But check anyway, just for robustness. */
45003   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
45004
45005   CHECK_PAGE(pPg);
45006
45007   /* The journal file needs to be opened. Higher level routines have already
45008   ** obtained the necessary locks to begin the write-transaction, but the
45009   ** rollback journal might not yet be open. Open it now if this is the case.
45010   **
45011   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
45012   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
45013   ** an error might occur and the pager would end up in WRITER_LOCKED state
45014   ** with pages marked as dirty in the cache.
45015   */
45016   if( pPager->eState==PAGER_WRITER_LOCKED ){
45017     rc = pager_open_journal(pPager);
45018     if( rc!=SQLITE_OK ) return rc;
45019   }
45020   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
45021   assert( assert_pager_state(pPager) );
45022
45023   /* Mark the page as dirty.  If the page has already been written
45024   ** to the journal then we can return right away.
45025   */
45026   sqlite3PcacheMakeDirty(pPg);
45027   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
45028     assert( !pagerUseWal(pPager) );
45029   }else{
45030
45031     /* The transaction journal now exists and we have a RESERVED or an
45032     ** EXCLUSIVE lock on the main database file.  Write the current page to
45033     ** the transaction journal if it is not there already.
45034     */
45035     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
45036       assert( pagerUseWal(pPager)==0 );
45037       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
45038         u32 cksum;
45039         char *pData2;
45040         i64 iOff = pPager->journalOff;
45041
45042         /* We should never write to the journal file the page that
45043         ** contains the database locks.  The following assert verifies
45044         ** that we do not. */
45045         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
45046
45047         assert( pPager->journalHdr<=pPager->journalOff );
45048         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45049         cksum = pager_cksum(pPager, (u8*)pData2);
45050
45051         /* Even if an IO or diskfull error occurs while journalling the
45052         ** page in the block above, set the need-sync flag for the page.
45053         ** Otherwise, when the transaction is rolled back, the logic in
45054         ** playback_one_page() will think that the page needs to be restored
45055         ** in the database file. And if an IO error occurs while doing so,
45056         ** then corruption may follow.
45057         */
45058         pPg->flags |= PGHDR_NEED_SYNC;
45059
45060         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
45061         if( rc!=SQLITE_OK ) return rc;
45062         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
45063         if( rc!=SQLITE_OK ) return rc;
45064         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
45065         if( rc!=SQLITE_OK ) return rc;
45066
45067         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
45068                  pPager->journalOff, pPager->pageSize));
45069         PAGER_INCR(sqlite3_pager_writej_count);
45070         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
45071              PAGERID(pPager), pPg->pgno,
45072              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
45073
45074         pPager->journalOff += 8 + pPager->pageSize;
45075         pPager->nRec++;
45076         assert( pPager->pInJournal!=0 );
45077         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
45078         testcase( rc==SQLITE_NOMEM );
45079         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
45080         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
45081         if( rc!=SQLITE_OK ){
45082           assert( rc==SQLITE_NOMEM );
45083           return rc;
45084         }
45085       }else{
45086         if( pPager->eState!=PAGER_WRITER_DBMOD ){
45087           pPg->flags |= PGHDR_NEED_SYNC;
45088         }
45089         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
45090                 PAGERID(pPager), pPg->pgno,
45091                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
45092       }
45093     }
45094
45095     /* If the statement journal is open and the page is not in it,
45096     ** then write the current page to the statement journal.  Note that
45097     ** the statement journal format differs from the standard journal format
45098     ** in that it omits the checksums and the header.
45099     */
45100     if( subjRequiresPage(pPg) ){
45101       rc = subjournalPage(pPg);
45102     }
45103   }
45104
45105   /* Update the database size and return.
45106   */
45107   if( pPager->dbSize<pPg->pgno ){
45108     pPager->dbSize = pPg->pgno;
45109   }
45110   return rc;
45111 }
45112
45113 /*
45114 ** Mark a data page as writeable. This routine must be called before
45115 ** making changes to a page. The caller must check the return value
45116 ** of this function and be careful not to change any page data unless
45117 ** this routine returns SQLITE_OK.
45118 **
45119 ** The difference between this function and pager_write() is that this
45120 ** function also deals with the special case where 2 or more pages
45121 ** fit on a single disk sector. In this case all co-resident pages
45122 ** must have been written to the journal file before returning.
45123 **
45124 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
45125 ** as appropriate. Otherwise, SQLITE_OK.
45126 */
45127 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
45128   int rc = SQLITE_OK;
45129
45130   PgHdr *pPg = pDbPage;
45131   Pager *pPager = pPg->pPager;
45132   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
45133
45134   assert( pPager->eState>=PAGER_WRITER_LOCKED );
45135   assert( pPager->eState!=PAGER_ERROR );
45136   assert( assert_pager_state(pPager) );
45137
45138   if( nPagePerSector>1 ){
45139     Pgno nPageCount;          /* Total number of pages in database file */
45140     Pgno pg1;                 /* First page of the sector pPg is located on. */
45141     int nPage = 0;            /* Number of pages starting at pg1 to journal */
45142     int ii;                   /* Loop counter */
45143     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
45144
45145     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
45146     ** a journal header to be written between the pages journaled by
45147     ** this function.
45148     */
45149     assert( !MEMDB );
45150     assert( pPager->doNotSyncSpill==0 );
45151     pPager->doNotSyncSpill++;
45152
45153     /* This trick assumes that both the page-size and sector-size are
45154     ** an integer power of 2. It sets variable pg1 to the identifier
45155     ** of the first page of the sector pPg is located on.
45156     */
45157     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
45158
45159     nPageCount = pPager->dbSize;
45160     if( pPg->pgno>nPageCount ){
45161       nPage = (pPg->pgno - pg1)+1;
45162     }else if( (pg1+nPagePerSector-1)>nPageCount ){
45163       nPage = nPageCount+1-pg1;
45164     }else{
45165       nPage = nPagePerSector;
45166     }
45167     assert(nPage>0);
45168     assert(pg1<=pPg->pgno);
45169     assert((pg1+nPage)>pPg->pgno);
45170
45171     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
45172       Pgno pg = pg1+ii;
45173       PgHdr *pPage;
45174       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
45175         if( pg!=PAGER_MJ_PGNO(pPager) ){
45176           rc = sqlite3PagerGet(pPager, pg, &pPage);
45177           if( rc==SQLITE_OK ){
45178             rc = pager_write(pPage);
45179             if( pPage->flags&PGHDR_NEED_SYNC ){
45180               needSync = 1;
45181             }
45182             sqlite3PagerUnref(pPage);
45183           }
45184         }
45185       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
45186         if( pPage->flags&PGHDR_NEED_SYNC ){
45187           needSync = 1;
45188         }
45189         sqlite3PagerUnref(pPage);
45190       }
45191     }
45192
45193     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
45194     ** starting at pg1, then it needs to be set for all of them. Because
45195     ** writing to any of these nPage pages may damage the others, the
45196     ** journal file must contain sync()ed copies of all of them
45197     ** before any of them can be written out to the database file.
45198     */
45199     if( rc==SQLITE_OK && needSync ){
45200       assert( !MEMDB );
45201       for(ii=0; ii<nPage; ii++){
45202         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
45203         if( pPage ){
45204           pPage->flags |= PGHDR_NEED_SYNC;
45205           sqlite3PagerUnref(pPage);
45206         }
45207       }
45208     }
45209
45210     assert( pPager->doNotSyncSpill==1 );
45211     pPager->doNotSyncSpill--;
45212   }else{
45213     rc = pager_write(pDbPage);
45214   }
45215   return rc;
45216 }
45217
45218 /*
45219 ** Return TRUE if the page given in the argument was previously passed
45220 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
45221 ** to change the content of the page.
45222 */
45223 #ifndef NDEBUG
45224 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
45225   return pPg->flags&PGHDR_DIRTY;
45226 }
45227 #endif
45228
45229 /*
45230 ** A call to this routine tells the pager that it is not necessary to
45231 ** write the information on page pPg back to the disk, even though
45232 ** that page might be marked as dirty.  This happens, for example, when
45233 ** the page has been added as a leaf of the freelist and so its
45234 ** content no longer matters.
45235 **
45236 ** The overlying software layer calls this routine when all of the data
45237 ** on the given page is unused. The pager marks the page as clean so
45238 ** that it does not get written to disk.
45239 **
45240 ** Tests show that this optimization can quadruple the speed of large
45241 ** DELETE operations.
45242 */
45243 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
45244   Pager *pPager = pPg->pPager;
45245   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
45246     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
45247     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
45248     pPg->flags |= PGHDR_DONT_WRITE;
45249     pager_set_pagehash(pPg);
45250   }
45251 }
45252
45253 /*
45254 ** This routine is called to increment the value of the database file
45255 ** change-counter, stored as a 4-byte big-endian integer starting at
45256 ** byte offset 24 of the pager file.  The secondary change counter at
45257 ** 92 is also updated, as is the SQLite version number at offset 96.
45258 **
45259 ** But this only happens if the pPager->changeCountDone flag is false.
45260 ** To avoid excess churning of page 1, the update only happens once.
45261 ** See also the pager_write_changecounter() routine that does an
45262 ** unconditional update of the change counters.
45263 **
45264 ** If the isDirectMode flag is zero, then this is done by calling
45265 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
45266 ** page data. In this case the file will be updated when the current
45267 ** transaction is committed.
45268 **
45269 ** The isDirectMode flag may only be non-zero if the library was compiled
45270 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
45271 ** if isDirect is non-zero, then the database file is updated directly
45272 ** by writing an updated version of page 1 using a call to the
45273 ** sqlite3OsWrite() function.
45274 */
45275 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
45276   int rc = SQLITE_OK;
45277
45278   assert( pPager->eState==PAGER_WRITER_CACHEMOD
45279        || pPager->eState==PAGER_WRITER_DBMOD
45280   );
45281   assert( assert_pager_state(pPager) );
45282
45283   /* Declare and initialize constant integer 'isDirect'. If the
45284   ** atomic-write optimization is enabled in this build, then isDirect
45285   ** is initialized to the value passed as the isDirectMode parameter
45286   ** to this function. Otherwise, it is always set to zero.
45287   **
45288   ** The idea is that if the atomic-write optimization is not
45289   ** enabled at compile time, the compiler can omit the tests of
45290   ** 'isDirect' below, as well as the block enclosed in the
45291   ** "if( isDirect )" condition.
45292   */
45293 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
45294 # define DIRECT_MODE 0
45295   assert( isDirectMode==0 );
45296   UNUSED_PARAMETER(isDirectMode);
45297 #else
45298 # define DIRECT_MODE isDirectMode
45299 #endif
45300
45301   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
45302     PgHdr *pPgHdr;                /* Reference to page 1 */
45303
45304     assert( !pPager->tempFile && isOpen(pPager->fd) );
45305
45306     /* Open page 1 of the file for writing. */
45307     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
45308     assert( pPgHdr==0 || rc==SQLITE_OK );
45309
45310     /* If page one was fetched successfully, and this function is not
45311     ** operating in direct-mode, make page 1 writable.  When not in
45312     ** direct mode, page 1 is always held in cache and hence the PagerGet()
45313     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
45314     */
45315     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
45316       rc = sqlite3PagerWrite(pPgHdr);
45317     }
45318
45319     if( rc==SQLITE_OK ){
45320       /* Actually do the update of the change counter */
45321       pager_write_changecounter(pPgHdr);
45322
45323       /* If running in direct mode, write the contents of page 1 to the file. */
45324       if( DIRECT_MODE ){
45325         const void *zBuf;
45326         assert( pPager->dbFileSize>0 );
45327         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
45328         if( rc==SQLITE_OK ){
45329           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
45330           pPager->aStat[PAGER_STAT_WRITE]++;
45331         }
45332         if( rc==SQLITE_OK ){
45333           pPager->changeCountDone = 1;
45334         }
45335       }else{
45336         pPager->changeCountDone = 1;
45337       }
45338     }
45339
45340     /* Release the page reference. */
45341     sqlite3PagerUnref(pPgHdr);
45342   }
45343   return rc;
45344 }
45345
45346 /*
45347 ** Sync the database file to disk. This is a no-op for in-memory databases
45348 ** or pages with the Pager.noSync flag set.
45349 **
45350 ** If successful, or if called on a pager for which it is a no-op, this
45351 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
45352 */
45353 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
45354   int rc = SQLITE_OK;
45355   if( !pPager->noSync ){
45356     assert( !MEMDB );
45357     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
45358   }else if( isOpen(pPager->fd) ){
45359     assert( !MEMDB );
45360     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
45361     if( rc==SQLITE_NOTFOUND ){
45362       rc = SQLITE_OK;
45363     }
45364   }
45365   return rc;
45366 }
45367
45368 /*
45369 ** This function may only be called while a write-transaction is active in
45370 ** rollback. If the connection is in WAL mode, this call is a no-op.
45371 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
45372 ** the database file, an attempt is made to obtain one.
45373 **
45374 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
45375 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
45376 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
45377 ** returned.
45378 */
45379 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
45380   int rc = SQLITE_OK;
45381   assert( pPager->eState==PAGER_WRITER_CACHEMOD
45382        || pPager->eState==PAGER_WRITER_DBMOD
45383        || pPager->eState==PAGER_WRITER_LOCKED
45384   );
45385   assert( assert_pager_state(pPager) );
45386   if( 0==pagerUseWal(pPager) ){
45387     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
45388   }
45389   return rc;
45390 }
45391
45392 /*
45393 ** Sync the database file for the pager pPager. zMaster points to the name
45394 ** of a master journal file that should be written into the individual
45395 ** journal file. zMaster may be NULL, which is interpreted as no master
45396 ** journal (a single database transaction).
45397 **
45398 ** This routine ensures that:
45399 **
45400 **   * The database file change-counter is updated,
45401 **   * the journal is synced (unless the atomic-write optimization is used),
45402 **   * all dirty pages are written to the database file,
45403 **   * the database file is truncated (if required), and
45404 **   * the database file synced.
45405 **
45406 ** The only thing that remains to commit the transaction is to finalize
45407 ** (delete, truncate or zero the first part of) the journal file (or
45408 ** delete the master journal file if specified).
45409 **
45410 ** Note that if zMaster==NULL, this does not overwrite a previous value
45411 ** passed to an sqlite3PagerCommitPhaseOne() call.
45412 **
45413 ** If the final parameter - noSync - is true, then the database file itself
45414 ** is not synced. The caller must call sqlite3PagerSync() directly to
45415 ** sync the database file before calling CommitPhaseTwo() to delete the
45416 ** journal file in this case.
45417 */
45418 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
45419   Pager *pPager,                  /* Pager object */
45420   const char *zMaster,            /* If not NULL, the master journal name */
45421   int noSync                      /* True to omit the xSync on the db file */
45422 ){
45423   int rc = SQLITE_OK;             /* Return code */
45424
45425   assert( pPager->eState==PAGER_WRITER_LOCKED
45426        || pPager->eState==PAGER_WRITER_CACHEMOD
45427        || pPager->eState==PAGER_WRITER_DBMOD
45428        || pPager->eState==PAGER_ERROR
45429   );
45430   assert( assert_pager_state(pPager) );
45431
45432   /* If a prior error occurred, report that error again. */
45433   if( NEVER(pPager->errCode) ) return pPager->errCode;
45434
45435   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
45436       pPager->zFilename, zMaster, pPager->dbSize));
45437
45438   /* If no database changes have been made, return early. */
45439   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
45440
45441   if( MEMDB ){
45442     /* If this is an in-memory db, or no pages have been written to, or this
45443     ** function has already been called, it is mostly a no-op.  However, any
45444     ** backup in progress needs to be restarted.
45445     */
45446     sqlite3BackupRestart(pPager->pBackup);
45447   }else{
45448     if( pagerUseWal(pPager) ){
45449       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
45450       PgHdr *pPageOne = 0;
45451       if( pList==0 ){
45452         /* Must have at least one page for the WAL commit flag.
45453         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
45454         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
45455         pList = pPageOne;
45456         pList->pDirty = 0;
45457       }
45458       assert( rc==SQLITE_OK );
45459       if( ALWAYS(pList) ){
45460         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
45461       }
45462       sqlite3PagerUnref(pPageOne);
45463       if( rc==SQLITE_OK ){
45464         sqlite3PcacheCleanAll(pPager->pPCache);
45465       }
45466     }else{
45467       /* The following block updates the change-counter. Exactly how it
45468       ** does this depends on whether or not the atomic-update optimization
45469       ** was enabled at compile time, and if this transaction meets the
45470       ** runtime criteria to use the operation:
45471       **
45472       **    * The file-system supports the atomic-write property for
45473       **      blocks of size page-size, and
45474       **    * This commit is not part of a multi-file transaction, and
45475       **    * Exactly one page has been modified and store in the journal file.
45476       **
45477       ** If the optimization was not enabled at compile time, then the
45478       ** pager_incr_changecounter() function is called to update the change
45479       ** counter in 'indirect-mode'. If the optimization is compiled in but
45480       ** is not applicable to this transaction, call sqlite3JournalCreate()
45481       ** to make sure the journal file has actually been created, then call
45482       ** pager_incr_changecounter() to update the change-counter in indirect
45483       ** mode.
45484       **
45485       ** Otherwise, if the optimization is both enabled and applicable,
45486       ** then call pager_incr_changecounter() to update the change-counter
45487       ** in 'direct' mode. In this case the journal file will never be
45488       ** created for this transaction.
45489       */
45490   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
45491       PgHdr *pPg;
45492       assert( isOpen(pPager->jfd)
45493            || pPager->journalMode==PAGER_JOURNALMODE_OFF
45494            || pPager->journalMode==PAGER_JOURNALMODE_WAL
45495       );
45496       if( !zMaster && isOpen(pPager->jfd)
45497        && pPager->journalOff==jrnlBufferSize(pPager)
45498        && pPager->dbSize>=pPager->dbOrigSize
45499        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
45500       ){
45501         /* Update the db file change counter via the direct-write method. The
45502         ** following call will modify the in-memory representation of page 1
45503         ** to include the updated change counter and then write page 1
45504         ** directly to the database file. Because of the atomic-write
45505         ** property of the host file-system, this is safe.
45506         */
45507         rc = pager_incr_changecounter(pPager, 1);
45508       }else{
45509         rc = sqlite3JournalCreate(pPager->jfd);
45510         if( rc==SQLITE_OK ){
45511           rc = pager_incr_changecounter(pPager, 0);
45512         }
45513       }
45514   #else
45515       rc = pager_incr_changecounter(pPager, 0);
45516   #endif
45517       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45518
45519       /* If this transaction has made the database smaller, then all pages
45520       ** being discarded by the truncation must be written to the journal
45521       ** file.
45522       **
45523       ** Before reading the pages with page numbers larger than the
45524       ** current value of Pager.dbSize, set dbSize back to the value
45525       ** that it took at the start of the transaction. Otherwise, the
45526       ** calls to sqlite3PagerGet() return zeroed pages instead of
45527       ** reading data from the database file.
45528       */
45529       if( pPager->dbSize<pPager->dbOrigSize
45530        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
45531       ){
45532         Pgno i;                                   /* Iterator variable */
45533         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
45534         const Pgno dbSize = pPager->dbSize;       /* Database image size */
45535         pPager->dbSize = pPager->dbOrigSize;
45536         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
45537           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
45538             PgHdr *pPage;             /* Page to journal */
45539             rc = sqlite3PagerGet(pPager, i, &pPage);
45540             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45541             rc = sqlite3PagerWrite(pPage);
45542             sqlite3PagerUnref(pPage);
45543             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45544           }
45545         }
45546         pPager->dbSize = dbSize;
45547       }
45548
45549       /* Write the master journal name into the journal file. If a master
45550       ** journal file name has already been written to the journal file,
45551       ** or if zMaster is NULL (no master journal), then this call is a no-op.
45552       */
45553       rc = writeMasterJournal(pPager, zMaster);
45554       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45555
45556       /* Sync the journal file and write all dirty pages to the database.
45557       ** If the atomic-update optimization is being used, this sync will not
45558       ** create the journal file or perform any real IO.
45559       **
45560       ** Because the change-counter page was just modified, unless the
45561       ** atomic-update optimization is used it is almost certain that the
45562       ** journal requires a sync here. However, in locking_mode=exclusive
45563       ** on a system under memory pressure it is just possible that this is
45564       ** not the case. In this case it is likely enough that the redundant
45565       ** xSync() call will be changed to a no-op by the OS anyhow.
45566       */
45567       rc = syncJournal(pPager, 0);
45568       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45569
45570       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
45571       if( rc!=SQLITE_OK ){
45572         assert( rc!=SQLITE_IOERR_BLOCKED );
45573         goto commit_phase_one_exit;
45574       }
45575       sqlite3PcacheCleanAll(pPager->pPCache);
45576
45577       /* If the file on disk is not the same size as the database image,
45578       ** then use pager_truncate to grow or shrink the file here.
45579       */
45580       if( pPager->dbSize!=pPager->dbFileSize ){
45581         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
45582         assert( pPager->eState==PAGER_WRITER_DBMOD );
45583         rc = pager_truncate(pPager, nNew);
45584         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45585       }
45586
45587       /* Finally, sync the database file. */
45588       if( !noSync ){
45589         rc = sqlite3PagerSync(pPager);
45590       }
45591       IOTRACE(("DBSYNC %p\n", pPager))
45592     }
45593   }
45594
45595 commit_phase_one_exit:
45596   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
45597     pPager->eState = PAGER_WRITER_FINISHED;
45598   }
45599   return rc;
45600 }
45601
45602
45603 /*
45604 ** When this function is called, the database file has been completely
45605 ** updated to reflect the changes made by the current transaction and
45606 ** synced to disk. The journal file still exists in the file-system
45607 ** though, and if a failure occurs at this point it will eventually
45608 ** be used as a hot-journal and the current transaction rolled back.
45609 **
45610 ** This function finalizes the journal file, either by deleting,
45611 ** truncating or partially zeroing it, so that it cannot be used
45612 ** for hot-journal rollback. Once this is done the transaction is
45613 ** irrevocably committed.
45614 **
45615 ** If an error occurs, an IO error code is returned and the pager
45616 ** moves into the error state. Otherwise, SQLITE_OK is returned.
45617 */
45618 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
45619   int rc = SQLITE_OK;                  /* Return code */
45620
45621   /* This routine should not be called if a prior error has occurred.
45622   ** But if (due to a coding error elsewhere in the system) it does get
45623   ** called, just return the same error code without doing anything. */
45624   if( NEVER(pPager->errCode) ) return pPager->errCode;
45625
45626   assert( pPager->eState==PAGER_WRITER_LOCKED
45627        || pPager->eState==PAGER_WRITER_FINISHED
45628        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
45629   );
45630   assert( assert_pager_state(pPager) );
45631
45632   /* An optimization. If the database was not actually modified during
45633   ** this transaction, the pager is running in exclusive-mode and is
45634   ** using persistent journals, then this function is a no-op.
45635   **
45636   ** The start of the journal file currently contains a single journal
45637   ** header with the nRec field set to 0. If such a journal is used as
45638   ** a hot-journal during hot-journal rollback, 0 changes will be made
45639   ** to the database file. So there is no need to zero the journal
45640   ** header. Since the pager is in exclusive mode, there is no need
45641   ** to drop any locks either.
45642   */
45643   if( pPager->eState==PAGER_WRITER_LOCKED
45644    && pPager->exclusiveMode
45645    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
45646   ){
45647     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
45648     pPager->eState = PAGER_READER;
45649     return SQLITE_OK;
45650   }
45651
45652   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
45653   rc = pager_end_transaction(pPager, pPager->setMaster);
45654   return pager_error(pPager, rc);
45655 }
45656
45657 /*
45658 ** If a write transaction is open, then all changes made within the
45659 ** transaction are reverted and the current write-transaction is closed.
45660 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
45661 ** state if an error occurs.
45662 **
45663 ** If the pager is already in PAGER_ERROR state when this function is called,
45664 ** it returns Pager.errCode immediately. No work is performed in this case.
45665 **
45666 ** Otherwise, in rollback mode, this function performs two functions:
45667 **
45668 **   1) It rolls back the journal file, restoring all database file and
45669 **      in-memory cache pages to the state they were in when the transaction
45670 **      was opened, and
45671 **
45672 **   2) It finalizes the journal file, so that it is not used for hot
45673 **      rollback at any point in the future.
45674 **
45675 ** Finalization of the journal file (task 2) is only performed if the
45676 ** rollback is successful.
45677 **
45678 ** In WAL mode, all cache-entries containing data modified within the
45679 ** current transaction are either expelled from the cache or reverted to
45680 ** their pre-transaction state by re-reading data from the database or
45681 ** WAL files. The WAL transaction is then closed.
45682 */
45683 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
45684   int rc = SQLITE_OK;                  /* Return code */
45685   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
45686
45687   /* PagerRollback() is a no-op if called in READER or OPEN state. If
45688   ** the pager is already in the ERROR state, the rollback is not
45689   ** attempted here. Instead, the error code is returned to the caller.
45690   */
45691   assert( assert_pager_state(pPager) );
45692   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
45693   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
45694
45695   if( pagerUseWal(pPager) ){
45696     int rc2;
45697     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
45698     rc2 = pager_end_transaction(pPager, pPager->setMaster);
45699     if( rc==SQLITE_OK ) rc = rc2;
45700   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
45701     int eState = pPager->eState;
45702     rc = pager_end_transaction(pPager, 0);
45703     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
45704       /* This can happen using journal_mode=off. Move the pager to the error
45705       ** state to indicate that the contents of the cache may not be trusted.
45706       ** Any active readers will get SQLITE_ABORT.
45707       */
45708       pPager->errCode = SQLITE_ABORT;
45709       pPager->eState = PAGER_ERROR;
45710       return rc;
45711     }
45712   }else{
45713     rc = pager_playback(pPager, 0);
45714   }
45715
45716   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
45717   assert( rc==SQLITE_OK || rc==SQLITE_FULL
45718           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
45719
45720   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
45721   ** cache. So call pager_error() on the way out to make any error persistent.
45722   */
45723   return pager_error(pPager, rc);
45724 }
45725
45726 /*
45727 ** Return TRUE if the database file is opened read-only.  Return FALSE
45728 ** if the database is (in theory) writable.
45729 */
45730 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
45731   return pPager->readOnly;
45732 }
45733
45734 /*
45735 ** Return the number of references to the pager.
45736 */
45737 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
45738   return sqlite3PcacheRefCount(pPager->pPCache);
45739 }
45740
45741 /*
45742 ** Return the approximate number of bytes of memory currently
45743 ** used by the pager and its associated cache.
45744 */
45745 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
45746   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
45747                                      + 5*sizeof(void*);
45748   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
45749            + sqlite3MallocSize(pPager)
45750            + pPager->pageSize;
45751 }
45752
45753 /*
45754 ** Return the number of references to the specified page.
45755 */
45756 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
45757   return sqlite3PcachePageRefcount(pPage);
45758 }
45759
45760 #ifdef SQLITE_TEST
45761 /*
45762 ** This routine is used for testing and analysis only.
45763 */
45764 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
45765   static int a[11];
45766   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
45767   a[1] = sqlite3PcachePagecount(pPager->pPCache);
45768   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
45769   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
45770   a[4] = pPager->eState;
45771   a[5] = pPager->errCode;
45772   a[6] = pPager->aStat[PAGER_STAT_HIT];
45773   a[7] = pPager->aStat[PAGER_STAT_MISS];
45774   a[8] = 0;  /* Used to be pPager->nOvfl */
45775   a[9] = pPager->nRead;
45776   a[10] = pPager->aStat[PAGER_STAT_WRITE];
45777   return a;
45778 }
45779 #endif
45780
45781 /*
45782 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
45783 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
45784 ** current cache hit or miss count, according to the value of eStat. If the
45785 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
45786 ** returning.
45787 */
45788 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
45789
45790   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
45791        || eStat==SQLITE_DBSTATUS_CACHE_MISS
45792        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
45793   );
45794
45795   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
45796   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
45797   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
45798
45799   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
45800   if( reset ){
45801     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
45802   }
45803 }
45804
45805 /*
45806 ** Return true if this is an in-memory pager.
45807 */
45808 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
45809   return MEMDB;
45810 }
45811
45812 /*
45813 ** Check that there are at least nSavepoint savepoints open. If there are
45814 ** currently less than nSavepoints open, then open one or more savepoints
45815 ** to make up the difference. If the number of savepoints is already
45816 ** equal to nSavepoint, then this function is a no-op.
45817 **
45818 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
45819 ** occurs while opening the sub-journal file, then an IO error code is
45820 ** returned. Otherwise, SQLITE_OK.
45821 */
45822 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
45823   int rc = SQLITE_OK;                       /* Return code */
45824   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
45825
45826   assert( pPager->eState>=PAGER_WRITER_LOCKED );
45827   assert( assert_pager_state(pPager) );
45828
45829   if( nSavepoint>nCurrent && pPager->useJournal ){
45830     int ii;                                 /* Iterator variable */
45831     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
45832
45833     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
45834     ** if the allocation fails. Otherwise, zero the new portion in case a
45835     ** malloc failure occurs while populating it in the for(...) loop below.
45836     */
45837     aNew = (PagerSavepoint *)sqlite3Realloc(
45838         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
45839     );
45840     if( !aNew ){
45841       return SQLITE_NOMEM;
45842     }
45843     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
45844     pPager->aSavepoint = aNew;
45845
45846     /* Populate the PagerSavepoint structures just allocated. */
45847     for(ii=nCurrent; ii<nSavepoint; ii++){
45848       aNew[ii].nOrig = pPager->dbSize;
45849       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
45850         aNew[ii].iOffset = pPager->journalOff;
45851       }else{
45852         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
45853       }
45854       aNew[ii].iSubRec = pPager->nSubRec;
45855       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
45856       if( !aNew[ii].pInSavepoint ){
45857         return SQLITE_NOMEM;
45858       }
45859       if( pagerUseWal(pPager) ){
45860         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
45861       }
45862       pPager->nSavepoint = ii+1;
45863     }
45864     assert( pPager->nSavepoint==nSavepoint );
45865     assertTruncateConstraint(pPager);
45866   }
45867
45868   return rc;
45869 }
45870
45871 /*
45872 ** This function is called to rollback or release (commit) a savepoint.
45873 ** The savepoint to release or rollback need not be the most recently
45874 ** created savepoint.
45875 **
45876 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
45877 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
45878 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
45879 ** that have occurred since the specified savepoint was created.
45880 **
45881 ** The savepoint to rollback or release is identified by parameter
45882 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
45883 ** (the first created). A value of (Pager.nSavepoint-1) means operate
45884 ** on the most recently created savepoint. If iSavepoint is greater than
45885 ** (Pager.nSavepoint-1), then this function is a no-op.
45886 **
45887 ** If a negative value is passed to this function, then the current
45888 ** transaction is rolled back. This is different to calling
45889 ** sqlite3PagerRollback() because this function does not terminate
45890 ** the transaction or unlock the database, it just restores the
45891 ** contents of the database to its original state.
45892 **
45893 ** In any case, all savepoints with an index greater than iSavepoint
45894 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
45895 ** then savepoint iSavepoint is also destroyed.
45896 **
45897 ** This function may return SQLITE_NOMEM if a memory allocation fails,
45898 ** or an IO error code if an IO error occurs while rolling back a
45899 ** savepoint. If no errors occur, SQLITE_OK is returned.
45900 */
45901 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
45902   int rc = pPager->errCode;       /* Return code */
45903
45904   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
45905   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
45906
45907   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
45908     int ii;            /* Iterator variable */
45909     int nNew;          /* Number of remaining savepoints after this op. */
45910
45911     /* Figure out how many savepoints will still be active after this
45912     ** operation. Store this value in nNew. Then free resources associated
45913     ** with any savepoints that are destroyed by this operation.
45914     */
45915     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
45916     for(ii=nNew; ii<pPager->nSavepoint; ii++){
45917       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
45918     }
45919     pPager->nSavepoint = nNew;
45920
45921     /* If this is a release of the outermost savepoint, truncate
45922     ** the sub-journal to zero bytes in size. */
45923     if( op==SAVEPOINT_RELEASE ){
45924       if( nNew==0 && isOpen(pPager->sjfd) ){
45925         /* Only truncate if it is an in-memory sub-journal. */
45926         if( sqlite3IsMemJournal(pPager->sjfd) ){
45927           rc = sqlite3OsTruncate(pPager->sjfd, 0);
45928           assert( rc==SQLITE_OK );
45929         }
45930         pPager->nSubRec = 0;
45931       }
45932     }
45933     /* Else this is a rollback operation, playback the specified savepoint.
45934     ** If this is a temp-file, it is possible that the journal file has
45935     ** not yet been opened. In this case there have been no changes to
45936     ** the database file, so the playback operation can be skipped.
45937     */
45938     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
45939       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
45940       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
45941       assert(rc!=SQLITE_DONE);
45942     }
45943   }
45944
45945   return rc;
45946 }
45947
45948 /*
45949 ** Return the full pathname of the database file.
45950 **
45951 ** Except, if the pager is in-memory only, then return an empty string if
45952 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
45953 ** used to report the filename to the user, for compatibility with legacy
45954 ** behavior.  But when the Btree needs to know the filename for matching to
45955 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
45956 ** participate in shared-cache.
45957 */
45958 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
45959   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
45960 }
45961
45962 /*
45963 ** Return the VFS structure for the pager.
45964 */
45965 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
45966   return pPager->pVfs;
45967 }
45968
45969 /*
45970 ** Return the file handle for the database file associated
45971 ** with the pager.  This might return NULL if the file has
45972 ** not yet been opened.
45973 */
45974 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
45975   return pPager->fd;
45976 }
45977
45978 /*
45979 ** Return the full pathname of the journal file.
45980 */
45981 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
45982   return pPager->zJournal;
45983 }
45984
45985 /*
45986 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
45987 ** if fsync()s are executed normally.
45988 */
45989 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
45990   return pPager->noSync;
45991 }
45992
45993 #ifdef SQLITE_HAS_CODEC
45994 /*
45995 ** Set or retrieve the codec for this pager
45996 */
45997 SQLITE_PRIVATE void sqlite3PagerSetCodec(
45998   Pager *pPager,
45999   void *(*xCodec)(void*,void*,Pgno,int),
46000   void (*xCodecSizeChng)(void*,int,int),
46001   void (*xCodecFree)(void*),
46002   void *pCodec
46003 ){
46004   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
46005   pPager->xCodec = pPager->memDb ? 0 : xCodec;
46006   pPager->xCodecSizeChng = xCodecSizeChng;
46007   pPager->xCodecFree = xCodecFree;
46008   pPager->pCodec = pCodec;
46009   pagerReportSize(pPager);
46010 }
46011 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
46012   return pPager->pCodec;
46013 }
46014 #endif
46015
46016 #ifndef SQLITE_OMIT_AUTOVACUUM
46017 /*
46018 ** Move the page pPg to location pgno in the file.
46019 **
46020 ** There must be no references to the page previously located at
46021 ** pgno (which we call pPgOld) though that page is allowed to be
46022 ** in cache.  If the page previously located at pgno is not already
46023 ** in the rollback journal, it is not put there by by this routine.
46024 **
46025 ** References to the page pPg remain valid. Updating any
46026 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
46027 ** allocated along with the page) is the responsibility of the caller.
46028 **
46029 ** A transaction must be active when this routine is called. It used to be
46030 ** required that a statement transaction was not active, but this restriction
46031 ** has been removed (CREATE INDEX needs to move a page when a statement
46032 ** transaction is active).
46033 **
46034 ** If the fourth argument, isCommit, is non-zero, then this page is being
46035 ** moved as part of a database reorganization just before the transaction
46036 ** is being committed. In this case, it is guaranteed that the database page
46037 ** pPg refers to will not be written to again within this transaction.
46038 **
46039 ** This function may return SQLITE_NOMEM or an IO error code if an error
46040 ** occurs. Otherwise, it returns SQLITE_OK.
46041 */
46042 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
46043   PgHdr *pPgOld;               /* The page being overwritten. */
46044   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
46045   int rc;                      /* Return code */
46046   Pgno origPgno;               /* The original page number */
46047
46048   assert( pPg->nRef>0 );
46049   assert( pPager->eState==PAGER_WRITER_CACHEMOD
46050        || pPager->eState==PAGER_WRITER_DBMOD
46051   );
46052   assert( assert_pager_state(pPager) );
46053
46054   /* In order to be able to rollback, an in-memory database must journal
46055   ** the page we are moving from.
46056   */
46057   if( MEMDB ){
46058     rc = sqlite3PagerWrite(pPg);
46059     if( rc ) return rc;
46060   }
46061
46062   /* If the page being moved is dirty and has not been saved by the latest
46063   ** savepoint, then save the current contents of the page into the
46064   ** sub-journal now. This is required to handle the following scenario:
46065   **
46066   **   BEGIN;
46067   **     <journal page X, then modify it in memory>
46068   **     SAVEPOINT one;
46069   **       <Move page X to location Y>
46070   **     ROLLBACK TO one;
46071   **
46072   ** If page X were not written to the sub-journal here, it would not
46073   ** be possible to restore its contents when the "ROLLBACK TO one"
46074   ** statement were is processed.
46075   **
46076   ** subjournalPage() may need to allocate space to store pPg->pgno into
46077   ** one or more savepoint bitvecs. This is the reason this function
46078   ** may return SQLITE_NOMEM.
46079   */
46080   if( pPg->flags&PGHDR_DIRTY
46081    && subjRequiresPage(pPg)
46082    && SQLITE_OK!=(rc = subjournalPage(pPg))
46083   ){
46084     return rc;
46085   }
46086
46087   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
46088       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
46089   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
46090
46091   /* If the journal needs to be sync()ed before page pPg->pgno can
46092   ** be written to, store pPg->pgno in local variable needSyncPgno.
46093   **
46094   ** If the isCommit flag is set, there is no need to remember that
46095   ** the journal needs to be sync()ed before database page pPg->pgno
46096   ** can be written to. The caller has already promised not to write to it.
46097   */
46098   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
46099     needSyncPgno = pPg->pgno;
46100     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
46101     assert( pPg->flags&PGHDR_DIRTY );
46102   }
46103
46104   /* If the cache contains a page with page-number pgno, remove it
46105   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
46106   ** page pgno before the 'move' operation, it needs to be retained
46107   ** for the page moved there.
46108   */
46109   pPg->flags &= ~PGHDR_NEED_SYNC;
46110   pPgOld = pager_lookup(pPager, pgno);
46111   assert( !pPgOld || pPgOld->nRef==1 );
46112   if( pPgOld ){
46113     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
46114     if( MEMDB ){
46115       /* Do not discard pages from an in-memory database since we might
46116       ** need to rollback later.  Just move the page out of the way. */
46117       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
46118     }else{
46119       sqlite3PcacheDrop(pPgOld);
46120     }
46121   }
46122
46123   origPgno = pPg->pgno;
46124   sqlite3PcacheMove(pPg, pgno);
46125   sqlite3PcacheMakeDirty(pPg);
46126
46127   /* For an in-memory database, make sure the original page continues
46128   ** to exist, in case the transaction needs to roll back.  Use pPgOld
46129   ** as the original page since it has already been allocated.
46130   */
46131   if( MEMDB ){
46132     assert( pPgOld );
46133     sqlite3PcacheMove(pPgOld, origPgno);
46134     sqlite3PagerUnref(pPgOld);
46135   }
46136
46137   if( needSyncPgno ){
46138     /* If needSyncPgno is non-zero, then the journal file needs to be
46139     ** sync()ed before any data is written to database file page needSyncPgno.
46140     ** Currently, no such page exists in the page-cache and the
46141     ** "is journaled" bitvec flag has been set. This needs to be remedied by
46142     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
46143     ** flag.
46144     **
46145     ** If the attempt to load the page into the page-cache fails, (due
46146     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
46147     ** array. Otherwise, if the page is loaded and written again in
46148     ** this transaction, it may be written to the database file before
46149     ** it is synced into the journal file. This way, it may end up in
46150     ** the journal file twice, but that is not a problem.
46151     */
46152     PgHdr *pPgHdr;
46153     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
46154     if( rc!=SQLITE_OK ){
46155       if( needSyncPgno<=pPager->dbOrigSize ){
46156         assert( pPager->pTmpSpace!=0 );
46157         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
46158       }
46159       return rc;
46160     }
46161     pPgHdr->flags |= PGHDR_NEED_SYNC;
46162     sqlite3PcacheMakeDirty(pPgHdr);
46163     sqlite3PagerUnref(pPgHdr);
46164   }
46165
46166   return SQLITE_OK;
46167 }
46168 #endif
46169
46170 /*
46171 ** Return a pointer to the data for the specified page.
46172 */
46173 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
46174   assert( pPg->nRef>0 || pPg->pPager->memDb );
46175   return pPg->pData;
46176 }
46177
46178 /*
46179 ** Return a pointer to the Pager.nExtra bytes of "extra" space
46180 ** allocated along with the specified page.
46181 */
46182 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
46183   return pPg->pExtra;
46184 }
46185
46186 /*
46187 ** Get/set the locking-mode for this pager. Parameter eMode must be one
46188 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
46189 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
46190 ** the locking-mode is set to the value specified.
46191 **
46192 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
46193 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
46194 ** locking-mode.
46195 */
46196 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
46197   assert( eMode==PAGER_LOCKINGMODE_QUERY
46198             || eMode==PAGER_LOCKINGMODE_NORMAL
46199             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
46200   assert( PAGER_LOCKINGMODE_QUERY<0 );
46201   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
46202   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
46203   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
46204     pPager->exclusiveMode = (u8)eMode;
46205   }
46206   return (int)pPager->exclusiveMode;
46207 }
46208
46209 /*
46210 ** Set the journal-mode for this pager. Parameter eMode must be one of:
46211 **
46212 **    PAGER_JOURNALMODE_DELETE
46213 **    PAGER_JOURNALMODE_TRUNCATE
46214 **    PAGER_JOURNALMODE_PERSIST
46215 **    PAGER_JOURNALMODE_OFF
46216 **    PAGER_JOURNALMODE_MEMORY
46217 **    PAGER_JOURNALMODE_WAL
46218 **
46219 ** The journalmode is set to the value specified if the change is allowed.
46220 ** The change may be disallowed for the following reasons:
46221 **
46222 **   *  An in-memory database can only have its journal_mode set to _OFF
46223 **      or _MEMORY.
46224 **
46225 **   *  Temporary databases cannot have _WAL journalmode.
46226 **
46227 ** The returned indicate the current (possibly updated) journal-mode.
46228 */
46229 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
46230   u8 eOld = pPager->journalMode;    /* Prior journalmode */
46231
46232 #ifdef SQLITE_DEBUG
46233   /* The print_pager_state() routine is intended to be used by the debugger
46234   ** only.  We invoke it once here to suppress a compiler warning. */
46235   print_pager_state(pPager);
46236 #endif
46237
46238
46239   /* The eMode parameter is always valid */
46240   assert(      eMode==PAGER_JOURNALMODE_DELETE
46241             || eMode==PAGER_JOURNALMODE_TRUNCATE
46242             || eMode==PAGER_JOURNALMODE_PERSIST
46243             || eMode==PAGER_JOURNALMODE_OFF
46244             || eMode==PAGER_JOURNALMODE_WAL
46245             || eMode==PAGER_JOURNALMODE_MEMORY );
46246
46247   /* This routine is only called from the OP_JournalMode opcode, and
46248   ** the logic there will never allow a temporary file to be changed
46249   ** to WAL mode.
46250   */
46251   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
46252
46253   /* Do allow the journalmode of an in-memory database to be set to
46254   ** anything other than MEMORY or OFF
46255   */
46256   if( MEMDB ){
46257     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
46258     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
46259       eMode = eOld;
46260     }
46261   }
46262
46263   if( eMode!=eOld ){
46264
46265     /* Change the journal mode. */
46266     assert( pPager->eState!=PAGER_ERROR );
46267     pPager->journalMode = (u8)eMode;
46268
46269     /* When transistioning from TRUNCATE or PERSIST to any other journal
46270     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
46271     ** delete the journal file.
46272     */
46273     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
46274     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
46275     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
46276     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
46277     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
46278     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
46279
46280     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
46281     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
46282
46283       /* In this case we would like to delete the journal file. If it is
46284       ** not possible, then that is not a problem. Deleting the journal file
46285       ** here is an optimization only.
46286       **
46287       ** Before deleting the journal file, obtain a RESERVED lock on the
46288       ** database file. This ensures that the journal file is not deleted
46289       ** while it is in use by some other client.
46290       */
46291       sqlite3OsClose(pPager->jfd);
46292       if( pPager->eLock>=RESERVED_LOCK ){
46293         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
46294       }else{
46295         int rc = SQLITE_OK;
46296         int state = pPager->eState;
46297         assert( state==PAGER_OPEN || state==PAGER_READER );
46298         if( state==PAGER_OPEN ){
46299           rc = sqlite3PagerSharedLock(pPager);
46300         }
46301         if( pPager->eState==PAGER_READER ){
46302           assert( rc==SQLITE_OK );
46303           rc = pagerLockDb(pPager, RESERVED_LOCK);
46304         }
46305         if( rc==SQLITE_OK ){
46306           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
46307         }
46308         if( rc==SQLITE_OK && state==PAGER_READER ){
46309           pagerUnlockDb(pPager, SHARED_LOCK);
46310         }else if( state==PAGER_OPEN ){
46311           pager_unlock(pPager);
46312         }
46313         assert( state==pPager->eState );
46314       }
46315     }
46316   }
46317
46318   /* Return the new journal mode */
46319   return (int)pPager->journalMode;
46320 }
46321
46322 /*
46323 ** Return the current journal mode.
46324 */
46325 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
46326   return (int)pPager->journalMode;
46327 }
46328
46329 /*
46330 ** Return TRUE if the pager is in a state where it is OK to change the
46331 ** journalmode.  Journalmode changes can only happen when the database
46332 ** is unmodified.
46333 */
46334 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
46335   assert( assert_pager_state(pPager) );
46336   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
46337   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
46338   return 1;
46339 }
46340
46341 /*
46342 ** Get/set the size-limit used for persistent journal files.
46343 **
46344 ** Setting the size limit to -1 means no limit is enforced.
46345 ** An attempt to set a limit smaller than -1 is a no-op.
46346 */
46347 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
46348   if( iLimit>=-1 ){
46349     pPager->journalSizeLimit = iLimit;
46350     sqlite3WalLimit(pPager->pWal, iLimit);
46351   }
46352   return pPager->journalSizeLimit;
46353 }
46354
46355 /*
46356 ** Return a pointer to the pPager->pBackup variable. The backup module
46357 ** in backup.c maintains the content of this variable. This module
46358 ** uses it opaquely as an argument to sqlite3BackupRestart() and
46359 ** sqlite3BackupUpdate() only.
46360 */
46361 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
46362   return &pPager->pBackup;
46363 }
46364
46365 #ifndef SQLITE_OMIT_VACUUM
46366 /*
46367 ** Unless this is an in-memory or temporary database, clear the pager cache.
46368 */
46369 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
46370   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
46371 }
46372 #endif
46373
46374 #ifndef SQLITE_OMIT_WAL
46375 /*
46376 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
46377 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
46378 ** or wal_blocking_checkpoint() API functions.
46379 **
46380 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
46381 */
46382 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
46383   int rc = SQLITE_OK;
46384   if( pPager->pWal ){
46385     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
46386         pPager->xBusyHandler, pPager->pBusyHandlerArg,
46387         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
46388         pnLog, pnCkpt
46389     );
46390   }
46391   return rc;
46392 }
46393
46394 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
46395   return sqlite3WalCallback(pPager->pWal);
46396 }
46397
46398 /*
46399 ** Return true if the underlying VFS for the given pager supports the
46400 ** primitives necessary for write-ahead logging.
46401 */
46402 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
46403   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
46404   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
46405 }
46406
46407 /*
46408 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
46409 ** is obtained instead, immediately release it.
46410 */
46411 static int pagerExclusiveLock(Pager *pPager){
46412   int rc;                         /* Return code */
46413
46414   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46415   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46416   if( rc!=SQLITE_OK ){
46417     /* If the attempt to grab the exclusive lock failed, release the
46418     ** pending lock that may have been obtained instead.  */
46419     pagerUnlockDb(pPager, SHARED_LOCK);
46420   }
46421
46422   return rc;
46423 }
46424
46425 /*
46426 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
46427 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
46428 ** lock on the database file and use heap-memory to store the wal-index
46429 ** in. Otherwise, use the normal shared-memory.
46430 */
46431 static int pagerOpenWal(Pager *pPager){
46432   int rc = SQLITE_OK;
46433
46434   assert( pPager->pWal==0 && pPager->tempFile==0 );
46435   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46436
46437   /* If the pager is already in exclusive-mode, the WAL module will use
46438   ** heap-memory for the wal-index instead of the VFS shared-memory
46439   ** implementation. Take the exclusive lock now, before opening the WAL
46440   ** file, to make sure this is safe.
46441   */
46442   if( pPager->exclusiveMode ){
46443     rc = pagerExclusiveLock(pPager);
46444   }
46445
46446   /* Open the connection to the log file. If this operation fails,
46447   ** (e.g. due to malloc() failure), return an error code.
46448   */
46449   if( rc==SQLITE_OK ){
46450     rc = sqlite3WalOpen(pPager->pVfs,
46451         pPager->fd, pPager->zWal, pPager->exclusiveMode,
46452         pPager->journalSizeLimit, &pPager->pWal
46453     );
46454   }
46455
46456   return rc;
46457 }
46458
46459
46460 /*
46461 ** The caller must be holding a SHARED lock on the database file to call
46462 ** this function.
46463 **
46464 ** If the pager passed as the first argument is open on a real database
46465 ** file (not a temp file or an in-memory database), and the WAL file
46466 ** is not already open, make an attempt to open it now. If successful,
46467 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
46468 ** not support the xShmXXX() methods, return an error code. *pbOpen is
46469 ** not modified in either case.
46470 **
46471 ** If the pager is open on a temp-file (or in-memory database), or if
46472 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
46473 ** without doing anything.
46474 */
46475 SQLITE_PRIVATE int sqlite3PagerOpenWal(
46476   Pager *pPager,                  /* Pager object */
46477   int *pbOpen                     /* OUT: Set to true if call is a no-op */
46478 ){
46479   int rc = SQLITE_OK;             /* Return code */
46480
46481   assert( assert_pager_state(pPager) );
46482   assert( pPager->eState==PAGER_OPEN   || pbOpen );
46483   assert( pPager->eState==PAGER_READER || !pbOpen );
46484   assert( pbOpen==0 || *pbOpen==0 );
46485   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
46486
46487   if( !pPager->tempFile && !pPager->pWal ){
46488     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
46489
46490     /* Close any rollback journal previously open */
46491     sqlite3OsClose(pPager->jfd);
46492
46493     rc = pagerOpenWal(pPager);
46494     if( rc==SQLITE_OK ){
46495       pPager->journalMode = PAGER_JOURNALMODE_WAL;
46496       pPager->eState = PAGER_OPEN;
46497     }
46498   }else{
46499     *pbOpen = 1;
46500   }
46501
46502   return rc;
46503 }
46504
46505 /*
46506 ** This function is called to close the connection to the log file prior
46507 ** to switching from WAL to rollback mode.
46508 **
46509 ** Before closing the log file, this function attempts to take an
46510 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
46511 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
46512 ** If successful, the EXCLUSIVE lock is not released before returning.
46513 */
46514 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
46515   int rc = SQLITE_OK;
46516
46517   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
46518
46519   /* If the log file is not already open, but does exist in the file-system,
46520   ** it may need to be checkpointed before the connection can switch to
46521   ** rollback mode. Open it now so this can happen.
46522   */
46523   if( !pPager->pWal ){
46524     int logexists = 0;
46525     rc = pagerLockDb(pPager, SHARED_LOCK);
46526     if( rc==SQLITE_OK ){
46527       rc = sqlite3OsAccess(
46528           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
46529       );
46530     }
46531     if( rc==SQLITE_OK && logexists ){
46532       rc = pagerOpenWal(pPager);
46533     }
46534   }
46535
46536   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
46537   ** the database file, the log and log-summary files will be deleted.
46538   */
46539   if( rc==SQLITE_OK && pPager->pWal ){
46540     rc = pagerExclusiveLock(pPager);
46541     if( rc==SQLITE_OK ){
46542       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
46543                            pPager->pageSize, (u8*)pPager->pTmpSpace);
46544       pPager->pWal = 0;
46545     }
46546   }
46547   return rc;
46548 }
46549
46550 #endif /* !SQLITE_OMIT_WAL */
46551
46552 #ifdef SQLITE_ENABLE_ZIPVFS
46553 /*
46554 ** A read-lock must be held on the pager when this function is called. If
46555 ** the pager is in WAL mode and the WAL file currently contains one or more
46556 ** frames, return the size in bytes of the page images stored within the
46557 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
46558 ** is empty, return 0.
46559 */
46560 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
46561   assert( pPager->eState==PAGER_READER );
46562   return sqlite3WalFramesize(pPager->pWal);
46563 }
46564 #endif
46565
46566 #ifdef SQLITE_HAS_CODEC
46567 /*
46568 ** This function is called by the wal module when writing page content
46569 ** into the log file.
46570 **
46571 ** This function returns a pointer to a buffer containing the encrypted
46572 ** page content. If a malloc fails, this function may return NULL.
46573 */
46574 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
46575   void *aData = 0;
46576   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
46577   return aData;
46578 }
46579 #endif /* SQLITE_HAS_CODEC */
46580
46581 #endif /* SQLITE_OMIT_DISKIO */
46582
46583 /* BEGIN CRYPTO */
46584 #ifdef SQLITE_HAS_CODEC
46585 SQLITE_PRIVATE void sqlite3pager_get_codec(Pager *pPager, void **ctx) {
46586   *ctx = pPager->pCodec;
46587 }
46588
46589 SQLITE_PRIVATE int sqlite3pager_is_mj_pgno(Pager *pPager, Pgno pgno) {
46590   return (PAGER_MJ_PGNO(pPager) == pgno) ? 1 : 0;
46591 }
46592
46593 SQLITE_PRIVATE sqlite3_file *sqlite3Pager_get_fd(Pager *pPager) {
46594   return (isOpen(pPager->fd)) ? pPager->fd : NULL;
46595 }
46596
46597 SQLITE_PRIVATE void sqlite3pager_sqlite3PagerSetCodec(
46598   Pager *pPager,
46599   void *(*xCodec)(void*,void*,Pgno,int),
46600   void (*xCodecSizeChng)(void*,int,int),
46601   void (*xCodecFree)(void*),
46602   void *pCodec
46603 ){
46604   sqlite3PagerSetCodec(pPager, xCodec, xCodecSizeChng, xCodecFree, pCodec);
46605 }
46606
46607 SQLITE_PRIVATE void sqlite3pager_sqlite3PagerSetError( Pager *pPager, int error) {
46608   pPager->errCode = error;
46609 }
46610
46611 #endif
46612 /* END CRYPTO */
46613
46614
46615 /************** End of pager.c ***********************************************/
46616 /************** Begin file wal.c *********************************************/
46617 /*
46618 ** 2010 February 1
46619 **
46620 ** The author disclaims copyright to this source code.  In place of
46621 ** a legal notice, here is a blessing:
46622 **
46623 **    May you do good and not evil.
46624 **    May you find forgiveness for yourself and forgive others.
46625 **    May you share freely, never taking more than you give.
46626 **
46627 *************************************************************************
46628 **
46629 ** This file contains the implementation of a write-ahead log (WAL) used in
46630 ** "journal_mode=WAL" mode.
46631 **
46632 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
46633 **
46634 ** A WAL file consists of a header followed by zero or more "frames".
46635 ** Each frame records the revised content of a single page from the
46636 ** database file.  All changes to the database are recorded by writing
46637 ** frames into the WAL.  Transactions commit when a frame is written that
46638 ** contains a commit marker.  A single WAL can and usually does record
46639 ** multiple transactions.  Periodically, the content of the WAL is
46640 ** transferred back into the database file in an operation called a
46641 ** "checkpoint".
46642 **
46643 ** A single WAL file can be used multiple times.  In other words, the
46644 ** WAL can fill up with frames and then be checkpointed and then new
46645 ** frames can overwrite the old ones.  A WAL always grows from beginning
46646 ** toward the end.  Checksums and counters attached to each frame are
46647 ** used to determine which frames within the WAL are valid and which
46648 ** are leftovers from prior checkpoints.
46649 **
46650 ** The WAL header is 32 bytes in size and consists of the following eight
46651 ** big-endian 32-bit unsigned integer values:
46652 **
46653 **     0: Magic number.  0x377f0682 or 0x377f0683
46654 **     4: File format version.  Currently 3007000
46655 **     8: Database page size.  Example: 1024
46656 **    12: Checkpoint sequence number
46657 **    16: Salt-1, random integer incremented with each checkpoint
46658 **    20: Salt-2, a different random integer changing with each ckpt
46659 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
46660 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
46661 **
46662 ** Immediately following the wal-header are zero or more frames. Each
46663 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
46664 ** of page data. The frame-header is six big-endian 32-bit unsigned
46665 ** integer values, as follows:
46666 **
46667 **     0: Page number.
46668 **     4: For commit records, the size of the database image in pages
46669 **        after the commit. For all other records, zero.
46670 **     8: Salt-1 (copied from the header)
46671 **    12: Salt-2 (copied from the header)
46672 **    16: Checksum-1.
46673 **    20: Checksum-2.
46674 **
46675 ** A frame is considered valid if and only if the following conditions are
46676 ** true:
46677 **
46678 **    (1) The salt-1 and salt-2 values in the frame-header match
46679 **        salt values in the wal-header
46680 **
46681 **    (2) The checksum values in the final 8 bytes of the frame-header
46682 **        exactly match the checksum computed consecutively on the
46683 **        WAL header and the first 8 bytes and the content of all frames
46684 **        up to and including the current frame.
46685 **
46686 ** The checksum is computed using 32-bit big-endian integers if the
46687 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
46688 ** is computed using little-endian if the magic number is 0x377f0682.
46689 ** The checksum values are always stored in the frame header in a
46690 ** big-endian format regardless of which byte order is used to compute
46691 ** the checksum.  The checksum is computed by interpreting the input as
46692 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
46693 ** algorithm used for the checksum is as follows:
46694 **
46695 **   for i from 0 to n-1 step 2:
46696 **     s0 += x[i] + s1;
46697 **     s1 += x[i+1] + s0;
46698 **   endfor
46699 **
46700 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
46701 ** in reverse order (the largest fibonacci weight occurs on the first element
46702 ** of the sequence being summed.)  The s1 value spans all 32-bit
46703 ** terms of the sequence whereas s0 omits the final term.
46704 **
46705 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
46706 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
46707 ** The VFS.xSync operations serve as write barriers - all writes launched
46708 ** before the xSync must complete before any write that launches after the
46709 ** xSync begins.
46710 **
46711 ** After each checkpoint, the salt-1 value is incremented and the salt-2
46712 ** value is randomized.  This prevents old and new frames in the WAL from
46713 ** being considered valid at the same time and being checkpointing together
46714 ** following a crash.
46715 **
46716 ** READER ALGORITHM
46717 **
46718 ** To read a page from the database (call it page number P), a reader
46719 ** first checks the WAL to see if it contains page P.  If so, then the
46720 ** last valid instance of page P that is a followed by a commit frame
46721 ** or is a commit frame itself becomes the value read.  If the WAL
46722 ** contains no copies of page P that are valid and which are a commit
46723 ** frame or are followed by a commit frame, then page P is read from
46724 ** the database file.
46725 **
46726 ** To start a read transaction, the reader records the index of the last
46727 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
46728 ** for all subsequent read operations.  New transactions can be appended
46729 ** to the WAL, but as long as the reader uses its original mxFrame value
46730 ** and ignores the newly appended content, it will see a consistent snapshot
46731 ** of the database from a single point in time.  This technique allows
46732 ** multiple concurrent readers to view different versions of the database
46733 ** content simultaneously.
46734 **
46735 ** The reader algorithm in the previous paragraphs works correctly, but
46736 ** because frames for page P can appear anywhere within the WAL, the
46737 ** reader has to scan the entire WAL looking for page P frames.  If the
46738 ** WAL is large (multiple megabytes is typical) that scan can be slow,
46739 ** and read performance suffers.  To overcome this problem, a separate
46740 ** data structure called the wal-index is maintained to expedite the
46741 ** search for frames of a particular page.
46742 **
46743 ** WAL-INDEX FORMAT
46744 **
46745 ** Conceptually, the wal-index is shared memory, though VFS implementations
46746 ** might choose to implement the wal-index using a mmapped file.  Because
46747 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
46748 ** on a network filesystem.  All users of the database must be able to
46749 ** share memory.
46750 **
46751 ** The wal-index is transient.  After a crash, the wal-index can (and should
46752 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
46753 ** to either truncate or zero the header of the wal-index when the last
46754 ** connection to it closes.  Because the wal-index is transient, it can
46755 ** use an architecture-specific format; it does not have to be cross-platform.
46756 ** Hence, unlike the database and WAL file formats which store all values
46757 ** as big endian, the wal-index can store multi-byte values in the native
46758 ** byte order of the host computer.
46759 **
46760 ** The purpose of the wal-index is to answer this question quickly:  Given
46761 ** a page number P and a maximum frame index M, return the index of the
46762 ** last frame in the wal before frame M for page P in the WAL, or return
46763 ** NULL if there are no frames for page P in the WAL prior to M.
46764 **
46765 ** The wal-index consists of a header region, followed by an one or
46766 ** more index blocks.
46767 **
46768 ** The wal-index header contains the total number of frames within the WAL
46769 ** in the mxFrame field.
46770 **
46771 ** Each index block except for the first contains information on
46772 ** HASHTABLE_NPAGE frames. The first index block contains information on
46773 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
46774 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
46775 ** first index block are the same size as all other index blocks in the
46776 ** wal-index.
46777 **
46778 ** Each index block contains two sections, a page-mapping that contains the
46779 ** database page number associated with each wal frame, and a hash-table
46780 ** that allows readers to query an index block for a specific page number.
46781 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
46782 ** for the first index block) 32-bit page numbers. The first entry in the
46783 ** first index-block contains the database page number corresponding to the
46784 ** first frame in the WAL file. The first entry in the second index block
46785 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
46786 ** the log, and so on.
46787 **
46788 ** The last index block in a wal-index usually contains less than the full
46789 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
46790 ** depending on the contents of the WAL file. This does not change the
46791 ** allocated size of the page-mapping array - the page-mapping array merely
46792 ** contains unused entries.
46793 **
46794 ** Even without using the hash table, the last frame for page P
46795 ** can be found by scanning the page-mapping sections of each index block
46796 ** starting with the last index block and moving toward the first, and
46797 ** within each index block, starting at the end and moving toward the
46798 ** beginning.  The first entry that equals P corresponds to the frame
46799 ** holding the content for that page.
46800 **
46801 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
46802 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
46803 ** hash table for each page number in the mapping section, so the hash
46804 ** table is never more than half full.  The expected number of collisions
46805 ** prior to finding a match is 1.  Each entry of the hash table is an
46806 ** 1-based index of an entry in the mapping section of the same
46807 ** index block.   Let K be the 1-based index of the largest entry in
46808 ** the mapping section.  (For index blocks other than the last, K will
46809 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
46810 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
46811 ** contain a value of 0.
46812 **
46813 ** To look for page P in the hash table, first compute a hash iKey on
46814 ** P as follows:
46815 **
46816 **      iKey = (P * 383) % HASHTABLE_NSLOT
46817 **
46818 ** Then start scanning entries of the hash table, starting with iKey
46819 ** (wrapping around to the beginning when the end of the hash table is
46820 ** reached) until an unused hash slot is found. Let the first unused slot
46821 ** be at index iUnused.  (iUnused might be less than iKey if there was
46822 ** wrap-around.) Because the hash table is never more than half full,
46823 ** the search is guaranteed to eventually hit an unused entry.  Let
46824 ** iMax be the value between iKey and iUnused, closest to iUnused,
46825 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
46826 ** no hash slot such that aHash[i]==p) then page P is not in the
46827 ** current index block.  Otherwise the iMax-th mapping entry of the
46828 ** current index block corresponds to the last entry that references
46829 ** page P.
46830 **
46831 ** A hash search begins with the last index block and moves toward the
46832 ** first index block, looking for entries corresponding to page P.  On
46833 ** average, only two or three slots in each index block need to be
46834 ** examined in order to either find the last entry for page P, or to
46835 ** establish that no such entry exists in the block.  Each index block
46836 ** holds over 4000 entries.  So two or three index blocks are sufficient
46837 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
46838 ** comparisons (on average) suffice to either locate a frame in the
46839 ** WAL or to establish that the frame does not exist in the WAL.  This
46840 ** is much faster than scanning the entire 10MB WAL.
46841 **
46842 ** Note that entries are added in order of increasing K.  Hence, one
46843 ** reader might be using some value K0 and a second reader that started
46844 ** at a later time (after additional transactions were added to the WAL
46845 ** and to the wal-index) might be using a different value K1, where K1>K0.
46846 ** Both readers can use the same hash table and mapping section to get
46847 ** the correct result.  There may be entries in the hash table with
46848 ** K>K0 but to the first reader, those entries will appear to be unused
46849 ** slots in the hash table and so the first reader will get an answer as
46850 ** if no values greater than K0 had ever been inserted into the hash table
46851 ** in the first place - which is what reader one wants.  Meanwhile, the
46852 ** second reader using K1 will see additional values that were inserted
46853 ** later, which is exactly what reader two wants.
46854 **
46855 ** When a rollback occurs, the value of K is decreased. Hash table entries
46856 ** that correspond to frames greater than the new K value are removed
46857 ** from the hash table at this point.
46858 */
46859 #ifndef SQLITE_OMIT_WAL
46860
46861
46862 /*
46863 ** Trace output macros
46864 */
46865 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46866 SQLITE_PRIVATE int sqlite3WalTrace = 0;
46867 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
46868 #else
46869 # define WALTRACE(X)
46870 #endif
46871
46872 /*
46873 ** The maximum (and only) versions of the wal and wal-index formats
46874 ** that may be interpreted by this version of SQLite.
46875 **
46876 ** If a client begins recovering a WAL file and finds that (a) the checksum
46877 ** values in the wal-header are correct and (b) the version field is not
46878 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
46879 **
46880 ** Similarly, if a client successfully reads a wal-index header (i.e. the
46881 ** checksum test is successful) and finds that the version field is not
46882 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
46883 ** returns SQLITE_CANTOPEN.
46884 */
46885 #define WAL_MAX_VERSION      3007000
46886 #define WALINDEX_MAX_VERSION 3007000
46887
46888 /*
46889 ** Indices of various locking bytes.   WAL_NREADER is the number
46890 ** of available reader locks and should be at least 3.
46891 */
46892 #define WAL_WRITE_LOCK         0
46893 #define WAL_ALL_BUT_WRITE      1
46894 #define WAL_CKPT_LOCK          1
46895 #define WAL_RECOVER_LOCK       2
46896 #define WAL_READ_LOCK(I)       (3+(I))
46897 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
46898
46899
46900 /* Object declarations */
46901 typedef struct WalIndexHdr WalIndexHdr;
46902 typedef struct WalIterator WalIterator;
46903 typedef struct WalCkptInfo WalCkptInfo;
46904
46905
46906 /*
46907 ** The following object holds a copy of the wal-index header content.
46908 **
46909 ** The actual header in the wal-index consists of two copies of this
46910 ** object.
46911 **
46912 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
46913 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
46914 ** added in 3.7.1 when support for 64K pages was added.
46915 */
46916 struct WalIndexHdr {
46917   u32 iVersion;                   /* Wal-index version */
46918   u32 unused;                     /* Unused (padding) field */
46919   u32 iChange;                    /* Counter incremented each transaction */
46920   u8 isInit;                      /* 1 when initialized */
46921   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
46922   u16 szPage;                     /* Database page size in bytes. 1==64K */
46923   u32 mxFrame;                    /* Index of last valid frame in the WAL */
46924   u32 nPage;                      /* Size of database in pages */
46925   u32 aFrameCksum[2];             /* Checksum of last frame in log */
46926   u32 aSalt[2];                   /* Two salt values copied from WAL header */
46927   u32 aCksum[2];                  /* Checksum over all prior fields */
46928 };
46929
46930 /*
46931 ** A copy of the following object occurs in the wal-index immediately
46932 ** following the second copy of the WalIndexHdr.  This object stores
46933 ** information used by checkpoint.
46934 **
46935 ** nBackfill is the number of frames in the WAL that have been written
46936 ** back into the database. (We call the act of moving content from WAL to
46937 ** database "backfilling".)  The nBackfill number is never greater than
46938 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
46939 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
46940 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
46941 ** mxFrame back to zero when the WAL is reset.
46942 **
46943 ** There is one entry in aReadMark[] for each reader lock.  If a reader
46944 ** holds read-lock K, then the value in aReadMark[K] is no greater than
46945 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
46946 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
46947 ** a special case; its value is never used and it exists as a place-holder
46948 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
46949 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
46950 ** directly from the database.
46951 **
46952 ** The value of aReadMark[K] may only be changed by a thread that
46953 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
46954 ** aReadMark[K] cannot changed while there is a reader is using that mark
46955 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
46956 **
46957 ** The checkpointer may only transfer frames from WAL to database where
46958 ** the frame numbers are less than or equal to every aReadMark[] that is
46959 ** in use (that is, every aReadMark[j] for which there is a corresponding
46960 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
46961 ** largest value and will increase an unused aReadMark[] to mxFrame if there
46962 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
46963 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
46964 ** in the WAL has been backfilled into the database) then new readers
46965 ** will choose aReadMark[0] which has value 0 and hence such reader will
46966 ** get all their all content directly from the database file and ignore
46967 ** the WAL.
46968 **
46969 ** Writers normally append new frames to the end of the WAL.  However,
46970 ** if nBackfill equals mxFrame (meaning that all WAL content has been
46971 ** written back into the database) and if no readers are using the WAL
46972 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
46973 ** the writer will first "reset" the WAL back to the beginning and start
46974 ** writing new content beginning at frame 1.
46975 **
46976 ** We assume that 32-bit loads are atomic and so no locks are needed in
46977 ** order to read from any aReadMark[] entries.
46978 */
46979 struct WalCkptInfo {
46980   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
46981   u32 aReadMark[WAL_NREADER];     /* Reader marks */
46982 };
46983 #define READMARK_NOT_USED  0xffffffff
46984
46985
46986 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
46987 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
46988 ** only support mandatory file-locks, we do not read or write data
46989 ** from the region of the file on which locks are applied.
46990 */
46991 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
46992 #define WALINDEX_LOCK_RESERVED 16
46993 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
46994
46995 /* Size of header before each frame in wal */
46996 #define WAL_FRAME_HDRSIZE 24
46997
46998 /* Size of write ahead log header, including checksum. */
46999 /* #define WAL_HDRSIZE 24 */
47000 #define WAL_HDRSIZE 32
47001
47002 /* WAL magic value. Either this value, or the same value with the least
47003 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
47004 ** big-endian format in the first 4 bytes of a WAL file.
47005 **
47006 ** If the LSB is set, then the checksums for each frame within the WAL
47007 ** file are calculated by treating all data as an array of 32-bit
47008 ** big-endian words. Otherwise, they are calculated by interpreting
47009 ** all data as 32-bit little-endian words.
47010 */
47011 #define WAL_MAGIC 0x377f0682
47012
47013 /*
47014 ** Return the offset of frame iFrame in the write-ahead log file,
47015 ** assuming a database page size of szPage bytes. The offset returned
47016 ** is to the start of the write-ahead log frame-header.
47017 */
47018 #define walFrameOffset(iFrame, szPage) (                               \
47019   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
47020 )
47021
47022 /*
47023 ** An open write-ahead log file is represented by an instance of the
47024 ** following object.
47025 */
47026 struct Wal {
47027   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
47028   sqlite3_file *pDbFd;       /* File handle for the database file */
47029   sqlite3_file *pWalFd;      /* File handle for WAL file */
47030   u32 iCallback;             /* Value to pass to log callback (or 0) */
47031   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
47032   int nWiData;               /* Size of array apWiData */
47033   int szFirstBlock;          /* Size of first block written to WAL file */
47034   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
47035   u32 szPage;                /* Database page size */
47036   i16 readLock;              /* Which read lock is being held.  -1 for none */
47037   u8 syncFlags;              /* Flags to use to sync header writes */
47038   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
47039   u8 writeLock;              /* True if in a write transaction */
47040   u8 ckptLock;               /* True if holding a checkpoint lock */
47041   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
47042   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
47043   u8 syncHeader;             /* Fsync the WAL header if true */
47044   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
47045   WalIndexHdr hdr;           /* Wal-index header for current transaction */
47046   const char *zWalName;      /* Name of WAL file */
47047   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
47048 #ifdef SQLITE_DEBUG
47049   u8 lockError;              /* True if a locking error has occurred */
47050 #endif
47051 };
47052
47053 /*
47054 ** Candidate values for Wal.exclusiveMode.
47055 */
47056 #define WAL_NORMAL_MODE     0
47057 #define WAL_EXCLUSIVE_MODE  1
47058 #define WAL_HEAPMEMORY_MODE 2
47059
47060 /*
47061 ** Possible values for WAL.readOnly
47062 */
47063 #define WAL_RDWR        0    /* Normal read/write connection */
47064 #define WAL_RDONLY      1    /* The WAL file is readonly */
47065 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
47066
47067 /*
47068 ** Each page of the wal-index mapping contains a hash-table made up of
47069 ** an array of HASHTABLE_NSLOT elements of the following type.
47070 */
47071 typedef u16 ht_slot;
47072
47073 /*
47074 ** This structure is used to implement an iterator that loops through
47075 ** all frames in the WAL in database page order. Where two or more frames
47076 ** correspond to the same database page, the iterator visits only the
47077 ** frame most recently written to the WAL (in other words, the frame with
47078 ** the largest index).
47079 **
47080 ** The internals of this structure are only accessed by:
47081 **
47082 **   walIteratorInit() - Create a new iterator,
47083 **   walIteratorNext() - Step an iterator,
47084 **   walIteratorFree() - Free an iterator.
47085 **
47086 ** This functionality is used by the checkpoint code (see walCheckpoint()).
47087 */
47088 struct WalIterator {
47089   int iPrior;                     /* Last result returned from the iterator */
47090   int nSegment;                   /* Number of entries in aSegment[] */
47091   struct WalSegment {
47092     int iNext;                    /* Next slot in aIndex[] not yet returned */
47093     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
47094     u32 *aPgno;                   /* Array of page numbers. */
47095     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
47096     int iZero;                    /* Frame number associated with aPgno[0] */
47097   } aSegment[1];                  /* One for every 32KB page in the wal-index */
47098 };
47099
47100 /*
47101 ** Define the parameters of the hash tables in the wal-index file. There
47102 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
47103 ** wal-index.
47104 **
47105 ** Changing any of these constants will alter the wal-index format and
47106 ** create incompatibilities.
47107 */
47108 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
47109 #define HASHTABLE_HASH_1     383                  /* Should be prime */
47110 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
47111
47112 /*
47113 ** The block of page numbers associated with the first hash-table in a
47114 ** wal-index is smaller than usual. This is so that there is a complete
47115 ** hash-table on each aligned 32KB page of the wal-index.
47116 */
47117 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
47118
47119 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
47120 #define WALINDEX_PGSZ   (                                         \
47121     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
47122 )
47123
47124 /*
47125 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
47126 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
47127 ** numbered from zero.
47128 **
47129 ** If this call is successful, *ppPage is set to point to the wal-index
47130 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
47131 ** then an SQLite error code is returned and *ppPage is set to 0.
47132 */
47133 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
47134   int rc = SQLITE_OK;
47135
47136   /* Enlarge the pWal->apWiData[] array if required */
47137   if( pWal->nWiData<=iPage ){
47138     int nByte = sizeof(u32*)*(iPage+1);
47139     volatile u32 **apNew;
47140     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
47141     if( !apNew ){
47142       *ppPage = 0;
47143       return SQLITE_NOMEM;
47144     }
47145     memset((void*)&apNew[pWal->nWiData], 0,
47146            sizeof(u32*)*(iPage+1-pWal->nWiData));
47147     pWal->apWiData = apNew;
47148     pWal->nWiData = iPage+1;
47149   }
47150
47151   /* Request a pointer to the required page from the VFS */
47152   if( pWal->apWiData[iPage]==0 ){
47153     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47154       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
47155       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
47156     }else{
47157       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
47158           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
47159       );
47160       if( rc==SQLITE_READONLY ){
47161         pWal->readOnly |= WAL_SHM_RDONLY;
47162         rc = SQLITE_OK;
47163       }
47164     }
47165   }
47166
47167   *ppPage = pWal->apWiData[iPage];
47168   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
47169   return rc;
47170 }
47171
47172 /*
47173 ** Return a pointer to the WalCkptInfo structure in the wal-index.
47174 */
47175 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
47176   assert( pWal->nWiData>0 && pWal->apWiData[0] );
47177   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
47178 }
47179
47180 /*
47181 ** Return a pointer to the WalIndexHdr structure in the wal-index.
47182 */
47183 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
47184   assert( pWal->nWiData>0 && pWal->apWiData[0] );
47185   return (volatile WalIndexHdr*)pWal->apWiData[0];
47186 }
47187
47188 /*
47189 ** The argument to this macro must be of type u32. On a little-endian
47190 ** architecture, it returns the u32 value that results from interpreting
47191 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
47192 ** returns the value that would be produced by intepreting the 4 bytes
47193 ** of the input value as a little-endian integer.
47194 */
47195 #define BYTESWAP32(x) ( \
47196     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
47197   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
47198 )
47199
47200 /*
47201 ** Generate or extend an 8 byte checksum based on the data in
47202 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
47203 ** initial values of 0 and 0 if aIn==NULL).
47204 **
47205 ** The checksum is written back into aOut[] before returning.
47206 **
47207 ** nByte must be a positive multiple of 8.
47208 */
47209 static void walChecksumBytes(
47210   int nativeCksum, /* True for native byte-order, false for non-native */
47211   u8 *a,           /* Content to be checksummed */
47212   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
47213   const u32 *aIn,  /* Initial checksum value input */
47214   u32 *aOut        /* OUT: Final checksum value output */
47215 ){
47216   u32 s1, s2;
47217   u32 *aData = (u32 *)a;
47218   u32 *aEnd = (u32 *)&a[nByte];
47219
47220   if( aIn ){
47221     s1 = aIn[0];
47222     s2 = aIn[1];
47223   }else{
47224     s1 = s2 = 0;
47225   }
47226
47227   assert( nByte>=8 );
47228   assert( (nByte&0x00000007)==0 );
47229
47230   if( nativeCksum ){
47231     do {
47232       s1 += *aData++ + s2;
47233       s2 += *aData++ + s1;
47234     }while( aData<aEnd );
47235   }else{
47236     do {
47237       s1 += BYTESWAP32(aData[0]) + s2;
47238       s2 += BYTESWAP32(aData[1]) + s1;
47239       aData += 2;
47240     }while( aData<aEnd );
47241   }
47242
47243   aOut[0] = s1;
47244   aOut[1] = s2;
47245 }
47246
47247 static void walShmBarrier(Wal *pWal){
47248   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
47249     sqlite3OsShmBarrier(pWal->pDbFd);
47250   }
47251 }
47252
47253 /*
47254 ** Write the header information in pWal->hdr into the wal-index.
47255 **
47256 ** The checksum on pWal->hdr is updated before it is written.
47257 */
47258 static void walIndexWriteHdr(Wal *pWal){
47259   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
47260   const int nCksum = offsetof(WalIndexHdr, aCksum);
47261
47262   assert( pWal->writeLock );
47263   pWal->hdr.isInit = 1;
47264   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
47265   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
47266   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
47267   walShmBarrier(pWal);
47268   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
47269 }
47270
47271 /*
47272 ** This function encodes a single frame header and writes it to a buffer
47273 ** supplied by the caller. A frame-header is made up of a series of
47274 ** 4-byte big-endian integers, as follows:
47275 **
47276 **     0: Page number.
47277 **     4: For commit records, the size of the database image in pages
47278 **        after the commit. For all other records, zero.
47279 **     8: Salt-1 (copied from the wal-header)
47280 **    12: Salt-2 (copied from the wal-header)
47281 **    16: Checksum-1.
47282 **    20: Checksum-2.
47283 */
47284 static void walEncodeFrame(
47285   Wal *pWal,                      /* The write-ahead log */
47286   u32 iPage,                      /* Database page number for frame */
47287   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
47288   u8 *aData,                      /* Pointer to page data */
47289   u8 *aFrame                      /* OUT: Write encoded frame here */
47290 ){
47291   int nativeCksum;                /* True for native byte-order checksums */
47292   u32 *aCksum = pWal->hdr.aFrameCksum;
47293   assert( WAL_FRAME_HDRSIZE==24 );
47294   sqlite3Put4byte(&aFrame[0], iPage);
47295   sqlite3Put4byte(&aFrame[4], nTruncate);
47296   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
47297
47298   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
47299   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
47300   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
47301
47302   sqlite3Put4byte(&aFrame[16], aCksum[0]);
47303   sqlite3Put4byte(&aFrame[20], aCksum[1]);
47304 }
47305
47306 /*
47307 ** Check to see if the frame with header in aFrame[] and content
47308 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
47309 ** *pnTruncate and return true.  Return if the frame is not valid.
47310 */
47311 static int walDecodeFrame(
47312   Wal *pWal,                      /* The write-ahead log */
47313   u32 *piPage,                    /* OUT: Database page number for frame */
47314   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
47315   u8 *aData,                      /* Pointer to page data (for checksum) */
47316   u8 *aFrame                      /* Frame data */
47317 ){
47318   int nativeCksum;                /* True for native byte-order checksums */
47319   u32 *aCksum = pWal->hdr.aFrameCksum;
47320   u32 pgno;                       /* Page number of the frame */
47321   assert( WAL_FRAME_HDRSIZE==24 );
47322
47323   /* A frame is only valid if the salt values in the frame-header
47324   ** match the salt values in the wal-header.
47325   */
47326   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
47327     return 0;
47328   }
47329
47330   /* A frame is only valid if the page number is creater than zero.
47331   */
47332   pgno = sqlite3Get4byte(&aFrame[0]);
47333   if( pgno==0 ){
47334     return 0;
47335   }
47336
47337   /* A frame is only valid if a checksum of the WAL header,
47338   ** all prior frams, the first 16 bytes of this frame-header,
47339   ** and the frame-data matches the checksum in the last 8
47340   ** bytes of this frame-header.
47341   */
47342   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
47343   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
47344   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
47345   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
47346    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
47347   ){
47348     /* Checksum failed. */
47349     return 0;
47350   }
47351
47352   /* If we reach this point, the frame is valid.  Return the page number
47353   ** and the new database size.
47354   */
47355   *piPage = pgno;
47356   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
47357   return 1;
47358 }
47359
47360
47361 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
47362 /*
47363 ** Names of locks.  This routine is used to provide debugging output and is not
47364 ** a part of an ordinary build.
47365 */
47366 static const char *walLockName(int lockIdx){
47367   if( lockIdx==WAL_WRITE_LOCK ){
47368     return "WRITE-LOCK";
47369   }else if( lockIdx==WAL_CKPT_LOCK ){
47370     return "CKPT-LOCK";
47371   }else if( lockIdx==WAL_RECOVER_LOCK ){
47372     return "RECOVER-LOCK";
47373   }else{
47374     static char zName[15];
47375     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
47376                      lockIdx-WAL_READ_LOCK(0));
47377     return zName;
47378   }
47379 }
47380 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
47381
47382
47383 /*
47384 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
47385 ** A lock cannot be moved directly between shared and exclusive - it must go
47386 ** through the unlocked state first.
47387 **
47388 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
47389 */
47390 static int walLockShared(Wal *pWal, int lockIdx){
47391   int rc;
47392   if( pWal->exclusiveMode ) return SQLITE_OK;
47393   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
47394                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
47395   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
47396             walLockName(lockIdx), rc ? "failed" : "ok"));
47397   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
47398   return rc;
47399 }
47400 static void walUnlockShared(Wal *pWal, int lockIdx){
47401   if( pWal->exclusiveMode ) return;
47402   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
47403                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
47404   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
47405 }
47406 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
47407   int rc;
47408   if( pWal->exclusiveMode ) return SQLITE_OK;
47409   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
47410                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
47411   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
47412             walLockName(lockIdx), n, rc ? "failed" : "ok"));
47413   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
47414   return rc;
47415 }
47416 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
47417   if( pWal->exclusiveMode ) return;
47418   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
47419                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
47420   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
47421              walLockName(lockIdx), n));
47422 }
47423
47424 /*
47425 ** Compute a hash on a page number.  The resulting hash value must land
47426 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
47427 ** the hash to the next value in the event of a collision.
47428 */
47429 static int walHash(u32 iPage){
47430   assert( iPage>0 );
47431   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
47432   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
47433 }
47434 static int walNextHash(int iPriorHash){
47435   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
47436 }
47437
47438 /*
47439 ** Return pointers to the hash table and page number array stored on
47440 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
47441 ** numbered starting from 0.
47442 **
47443 ** Set output variable *paHash to point to the start of the hash table
47444 ** in the wal-index file. Set *piZero to one less than the frame
47445 ** number of the first frame indexed by this hash table. If a
47446 ** slot in the hash table is set to N, it refers to frame number
47447 ** (*piZero+N) in the log.
47448 **
47449 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
47450 ** first frame indexed by the hash table, frame (*piZero+1).
47451 */
47452 static int walHashGet(
47453   Wal *pWal,                      /* WAL handle */
47454   int iHash,                      /* Find the iHash'th table */
47455   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
47456   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
47457   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
47458 ){
47459   int rc;                         /* Return code */
47460   volatile u32 *aPgno;
47461
47462   rc = walIndexPage(pWal, iHash, &aPgno);
47463   assert( rc==SQLITE_OK || iHash>0 );
47464
47465   if( rc==SQLITE_OK ){
47466     u32 iZero;
47467     volatile ht_slot *aHash;
47468
47469     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
47470     if( iHash==0 ){
47471       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
47472       iZero = 0;
47473     }else{
47474       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
47475     }
47476
47477     *paPgno = &aPgno[-1];
47478     *paHash = aHash;
47479     *piZero = iZero;
47480   }
47481   return rc;
47482 }
47483
47484 /*
47485 ** Return the number of the wal-index page that contains the hash-table
47486 ** and page-number array that contain entries corresponding to WAL frame
47487 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
47488 ** are numbered starting from 0.
47489 */
47490 static int walFramePage(u32 iFrame){
47491   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
47492   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
47493        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
47494        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
47495        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
47496        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
47497   );
47498   return iHash;
47499 }
47500
47501 /*
47502 ** Return the page number associated with frame iFrame in this WAL.
47503 */
47504 static u32 walFramePgno(Wal *pWal, u32 iFrame){
47505   int iHash = walFramePage(iFrame);
47506   if( iHash==0 ){
47507     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
47508   }
47509   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
47510 }
47511
47512 /*
47513 ** Remove entries from the hash table that point to WAL slots greater
47514 ** than pWal->hdr.mxFrame.
47515 **
47516 ** This function is called whenever pWal->hdr.mxFrame is decreased due
47517 ** to a rollback or savepoint.
47518 **
47519 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
47520 ** updated.  Any later hash tables will be automatically cleared when
47521 ** pWal->hdr.mxFrame advances to the point where those hash tables are
47522 ** actually needed.
47523 */
47524 static void walCleanupHash(Wal *pWal){
47525   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
47526   volatile u32 *aPgno = 0;        /* Page number array for hash table */
47527   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
47528   int iLimit = 0;                 /* Zero values greater than this */
47529   int nByte;                      /* Number of bytes to zero in aPgno[] */
47530   int i;                          /* Used to iterate through aHash[] */
47531
47532   assert( pWal->writeLock );
47533   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
47534   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
47535   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
47536
47537   if( pWal->hdr.mxFrame==0 ) return;
47538
47539   /* Obtain pointers to the hash-table and page-number array containing
47540   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
47541   ** that the page said hash-table and array reside on is already mapped.
47542   */
47543   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
47544   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
47545   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
47546
47547   /* Zero all hash-table entries that correspond to frame numbers greater
47548   ** than pWal->hdr.mxFrame.
47549   */
47550   iLimit = pWal->hdr.mxFrame - iZero;
47551   assert( iLimit>0 );
47552   for(i=0; i<HASHTABLE_NSLOT; i++){
47553     if( aHash[i]>iLimit ){
47554       aHash[i] = 0;
47555     }
47556   }
47557
47558   /* Zero the entries in the aPgno array that correspond to frames with
47559   ** frame numbers greater than pWal->hdr.mxFrame.
47560   */
47561   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
47562   memset((void *)&aPgno[iLimit+1], 0, nByte);
47563
47564 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47565   /* Verify that the every entry in the mapping region is still reachable
47566   ** via the hash table even after the cleanup.
47567   */
47568   if( iLimit ){
47569     int i;           /* Loop counter */
47570     int iKey;        /* Hash key */
47571     for(i=1; i<=iLimit; i++){
47572       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47573         if( aHash[iKey]==i ) break;
47574       }
47575       assert( aHash[iKey]==i );
47576     }
47577   }
47578 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
47579 }
47580
47581
47582 /*
47583 ** Set an entry in the wal-index that will map database page number
47584 ** pPage into WAL frame iFrame.
47585 */
47586 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
47587   int rc;                         /* Return code */
47588   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
47589   volatile u32 *aPgno = 0;        /* Page number array */
47590   volatile ht_slot *aHash = 0;    /* Hash table */
47591
47592   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
47593
47594   /* Assuming the wal-index file was successfully mapped, populate the
47595   ** page number array and hash table entry.
47596   */
47597   if( rc==SQLITE_OK ){
47598     int iKey;                     /* Hash table key */
47599     int idx;                      /* Value to write to hash-table slot */
47600     int nCollide;                 /* Number of hash collisions */
47601
47602     idx = iFrame - iZero;
47603     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
47604
47605     /* If this is the first entry to be added to this hash-table, zero the
47606     ** entire hash table and aPgno[] array before proceding.
47607     */
47608     if( idx==1 ){
47609       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
47610       memset((void*)&aPgno[1], 0, nByte);
47611     }
47612
47613     /* If the entry in aPgno[] is already set, then the previous writer
47614     ** must have exited unexpectedly in the middle of a transaction (after
47615     ** writing one or more dirty pages to the WAL to free up memory).
47616     ** Remove the remnants of that writers uncommitted transaction from
47617     ** the hash-table before writing any new entries.
47618     */
47619     if( aPgno[idx] ){
47620       walCleanupHash(pWal);
47621       assert( !aPgno[idx] );
47622     }
47623
47624     /* Write the aPgno[] array entry and the hash-table slot. */
47625     nCollide = idx;
47626     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
47627       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
47628     }
47629     aPgno[idx] = iPage;
47630     aHash[iKey] = (ht_slot)idx;
47631
47632 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47633     /* Verify that the number of entries in the hash table exactly equals
47634     ** the number of entries in the mapping region.
47635     */
47636     {
47637       int i;           /* Loop counter */
47638       int nEntry = 0;  /* Number of entries in the hash table */
47639       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
47640       assert( nEntry==idx );
47641     }
47642
47643     /* Verify that the every entry in the mapping region is reachable
47644     ** via the hash table.  This turns out to be a really, really expensive
47645     ** thing to check, so only do this occasionally - not on every
47646     ** iteration.
47647     */
47648     if( (idx&0x3ff)==0 ){
47649       int i;           /* Loop counter */
47650       for(i=1; i<=idx; i++){
47651         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47652           if( aHash[iKey]==i ) break;
47653         }
47654         assert( aHash[iKey]==i );
47655       }
47656     }
47657 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
47658   }
47659
47660
47661   return rc;
47662 }
47663
47664
47665 /*
47666 ** Recover the wal-index by reading the write-ahead log file.
47667 **
47668 ** This routine first tries to establish an exclusive lock on the
47669 ** wal-index to prevent other threads/processes from doing anything
47670 ** with the WAL or wal-index while recovery is running.  The
47671 ** WAL_RECOVER_LOCK is also held so that other threads will know
47672 ** that this thread is running recovery.  If unable to establish
47673 ** the necessary locks, this routine returns SQLITE_BUSY.
47674 */
47675 static int walIndexRecover(Wal *pWal){
47676   int rc;                         /* Return Code */
47677   i64 nSize;                      /* Size of log file */
47678   u32 aFrameCksum[2] = {0, 0};
47679   int iLock;                      /* Lock offset to lock for checkpoint */
47680   int nLock;                      /* Number of locks to hold */
47681
47682   /* Obtain an exclusive lock on all byte in the locking range not already
47683   ** locked by the caller. The caller is guaranteed to have locked the
47684   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
47685   ** If successful, the same bytes that are locked here are unlocked before
47686   ** this function returns.
47687   */
47688   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
47689   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
47690   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
47691   assert( pWal->writeLock );
47692   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
47693   nLock = SQLITE_SHM_NLOCK - iLock;
47694   rc = walLockExclusive(pWal, iLock, nLock);
47695   if( rc ){
47696     return rc;
47697   }
47698   WALTRACE(("WAL%p: recovery begin...\n", pWal));
47699
47700   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47701
47702   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
47703   if( rc!=SQLITE_OK ){
47704     goto recovery_error;
47705   }
47706
47707   if( nSize>WAL_HDRSIZE ){
47708     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
47709     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
47710     int szFrame;                  /* Number of bytes in buffer aFrame[] */
47711     u8 *aData;                    /* Pointer to data part of aFrame buffer */
47712     int iFrame;                   /* Index of last frame read */
47713     i64 iOffset;                  /* Next offset to read from log file */
47714     int szPage;                   /* Page size according to the log */
47715     u32 magic;                    /* Magic value read from WAL header */
47716     u32 version;                  /* Magic value read from WAL header */
47717     int isValid;                  /* True if this frame is valid */
47718
47719     /* Read in the WAL header. */
47720     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
47721     if( rc!=SQLITE_OK ){
47722       goto recovery_error;
47723     }
47724
47725     /* If the database page size is not a power of two, or is greater than
47726     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
47727     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
47728     ** WAL file.
47729     */
47730     magic = sqlite3Get4byte(&aBuf[0]);
47731     szPage = sqlite3Get4byte(&aBuf[8]);
47732     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
47733      || szPage&(szPage-1)
47734      || szPage>SQLITE_MAX_PAGE_SIZE
47735      || szPage<512
47736     ){
47737       goto finished;
47738     }
47739     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
47740     pWal->szPage = szPage;
47741     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
47742     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
47743
47744     /* Verify that the WAL header checksum is correct */
47745     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
47746         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
47747     );
47748     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
47749      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
47750     ){
47751       goto finished;
47752     }
47753
47754     /* Verify that the version number on the WAL format is one that
47755     ** are able to understand */
47756     version = sqlite3Get4byte(&aBuf[4]);
47757     if( version!=WAL_MAX_VERSION ){
47758       rc = SQLITE_CANTOPEN_BKPT;
47759       goto finished;
47760     }
47761
47762     /* Malloc a buffer to read frames into. */
47763     szFrame = szPage + WAL_FRAME_HDRSIZE;
47764     aFrame = (u8 *)sqlite3_malloc(szFrame);
47765     if( !aFrame ){
47766       rc = SQLITE_NOMEM;
47767       goto recovery_error;
47768     }
47769     aData = &aFrame[WAL_FRAME_HDRSIZE];
47770
47771     /* Read all frames from the log file. */
47772     iFrame = 0;
47773     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
47774       u32 pgno;                   /* Database page number for frame */
47775       u32 nTruncate;              /* dbsize field from frame header */
47776
47777       /* Read and decode the next log frame. */
47778       iFrame++;
47779       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
47780       if( rc!=SQLITE_OK ) break;
47781       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
47782       if( !isValid ) break;
47783       rc = walIndexAppend(pWal, iFrame, pgno);
47784       if( rc!=SQLITE_OK ) break;
47785
47786       /* If nTruncate is non-zero, this is a commit record. */
47787       if( nTruncate ){
47788         pWal->hdr.mxFrame = iFrame;
47789         pWal->hdr.nPage = nTruncate;
47790         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47791         testcase( szPage<=32768 );
47792         testcase( szPage>=65536 );
47793         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
47794         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
47795       }
47796     }
47797
47798     sqlite3_free(aFrame);
47799   }
47800
47801 finished:
47802   if( rc==SQLITE_OK ){
47803     volatile WalCkptInfo *pInfo;
47804     int i;
47805     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
47806     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
47807     walIndexWriteHdr(pWal);
47808
47809     /* Reset the checkpoint-header. This is safe because this thread is
47810     ** currently holding locks that exclude all other readers, writers and
47811     ** checkpointers.
47812     */
47813     pInfo = walCkptInfo(pWal);
47814     pInfo->nBackfill = 0;
47815     pInfo->aReadMark[0] = 0;
47816     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
47817     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
47818
47819     /* If more than one frame was recovered from the log file, report an
47820     ** event via sqlite3_log(). This is to help with identifying performance
47821     ** problems caused by applications routinely shutting down without
47822     ** checkpointing the log file.
47823     */
47824     if( pWal->hdr.nPage ){
47825       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
47826           pWal->hdr.nPage, pWal->zWalName
47827       );
47828     }
47829   }
47830
47831 recovery_error:
47832   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
47833   walUnlockExclusive(pWal, iLock, nLock);
47834   return rc;
47835 }
47836
47837 /*
47838 ** Close an open wal-index.
47839 */
47840 static void walIndexClose(Wal *pWal, int isDelete){
47841   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47842     int i;
47843     for(i=0; i<pWal->nWiData; i++){
47844       sqlite3_free((void *)pWal->apWiData[i]);
47845       pWal->apWiData[i] = 0;
47846     }
47847   }else{
47848     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
47849   }
47850 }
47851
47852 /*
47853 ** Open a connection to the WAL file zWalName. The database file must
47854 ** already be opened on connection pDbFd. The buffer that zWalName points
47855 ** to must remain valid for the lifetime of the returned Wal* handle.
47856 **
47857 ** A SHARED lock should be held on the database file when this function
47858 ** is called. The purpose of this SHARED lock is to prevent any other
47859 ** client from unlinking the WAL or wal-index file. If another process
47860 ** were to do this just after this client opened one of these files, the
47861 ** system would be badly broken.
47862 **
47863 ** If the log file is successfully opened, SQLITE_OK is returned and
47864 ** *ppWal is set to point to a new WAL handle. If an error occurs,
47865 ** an SQLite error code is returned and *ppWal is left unmodified.
47866 */
47867 SQLITE_PRIVATE int sqlite3WalOpen(
47868   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
47869   sqlite3_file *pDbFd,            /* The open database file */
47870   const char *zWalName,           /* Name of the WAL file */
47871   int bNoShm,                     /* True to run in heap-memory mode */
47872   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
47873   Wal **ppWal                     /* OUT: Allocated Wal handle */
47874 ){
47875   int rc;                         /* Return Code */
47876   Wal *pRet;                      /* Object to allocate and return */
47877   int flags;                      /* Flags passed to OsOpen() */
47878
47879   assert( zWalName && zWalName[0] );
47880   assert( pDbFd );
47881
47882   /* In the amalgamation, the os_unix.c and os_win.c source files come before
47883   ** this source file.  Verify that the #defines of the locking byte offsets
47884   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
47885   */
47886 #ifdef WIN_SHM_BASE
47887   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
47888 #endif
47889 #ifdef UNIX_SHM_BASE
47890   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
47891 #endif
47892
47893
47894   /* Allocate an instance of struct Wal to return. */
47895   *ppWal = 0;
47896   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
47897   if( !pRet ){
47898     return SQLITE_NOMEM;
47899   }
47900
47901   pRet->pVfs = pVfs;
47902   pRet->pWalFd = (sqlite3_file *)&pRet[1];
47903   pRet->pDbFd = pDbFd;
47904   pRet->readLock = -1;
47905   pRet->mxWalSize = mxWalSize;
47906   pRet->zWalName = zWalName;
47907   pRet->syncHeader = 1;
47908   pRet->padToSectorBoundary = 1;
47909   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
47910
47911   /* Open file handle on the write-ahead log file. */
47912   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
47913   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
47914   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
47915     pRet->readOnly = WAL_RDONLY;
47916   }
47917
47918   if( rc!=SQLITE_OK ){
47919     walIndexClose(pRet, 0);
47920     sqlite3OsClose(pRet->pWalFd);
47921     sqlite3_free(pRet);
47922   }else{
47923     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
47924     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
47925     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
47926       pRet->padToSectorBoundary = 0;
47927     }
47928     *ppWal = pRet;
47929     WALTRACE(("WAL%d: opened\n", pRet));
47930   }
47931   return rc;
47932 }
47933
47934 /*
47935 ** Change the size to which the WAL file is trucated on each reset.
47936 */
47937 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
47938   if( pWal ) pWal->mxWalSize = iLimit;
47939 }
47940
47941 /*
47942 ** Find the smallest page number out of all pages held in the WAL that
47943 ** has not been returned by any prior invocation of this method on the
47944 ** same WalIterator object.   Write into *piFrame the frame index where
47945 ** that page was last written into the WAL.  Write into *piPage the page
47946 ** number.
47947 **
47948 ** Return 0 on success.  If there are no pages in the WAL with a page
47949 ** number larger than *piPage, then return 1.
47950 */
47951 static int walIteratorNext(
47952   WalIterator *p,               /* Iterator */
47953   u32 *piPage,                  /* OUT: The page number of the next page */
47954   u32 *piFrame                  /* OUT: Wal frame index of next page */
47955 ){
47956   u32 iMin;                     /* Result pgno must be greater than iMin */
47957   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
47958   int i;                        /* For looping through segments */
47959
47960   iMin = p->iPrior;
47961   assert( iMin<0xffffffff );
47962   for(i=p->nSegment-1; i>=0; i--){
47963     struct WalSegment *pSegment = &p->aSegment[i];
47964     while( pSegment->iNext<pSegment->nEntry ){
47965       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
47966       if( iPg>iMin ){
47967         if( iPg<iRet ){
47968           iRet = iPg;
47969           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
47970         }
47971         break;
47972       }
47973       pSegment->iNext++;
47974     }
47975   }
47976
47977   *piPage = p->iPrior = iRet;
47978   return (iRet==0xFFFFFFFF);
47979 }
47980
47981 /*
47982 ** This function merges two sorted lists into a single sorted list.
47983 **
47984 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
47985 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
47986 ** is guaranteed for all J<K:
47987 **
47988 **        aContent[aLeft[J]] < aContent[aLeft[K]]
47989 **        aContent[aRight[J]] < aContent[aRight[K]]
47990 **
47991 ** This routine overwrites aRight[] with a new (probably longer) sequence
47992 ** of indices such that the aRight[] contains every index that appears in
47993 ** either aLeft[] or the old aRight[] and such that the second condition
47994 ** above is still met.
47995 **
47996 ** The aContent[aLeft[X]] values will be unique for all X.  And the
47997 ** aContent[aRight[X]] values will be unique too.  But there might be
47998 ** one or more combinations of X and Y such that
47999 **
48000 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
48001 **
48002 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
48003 */
48004 static void walMerge(
48005   const u32 *aContent,            /* Pages in wal - keys for the sort */
48006   ht_slot *aLeft,                 /* IN: Left hand input list */
48007   int nLeft,                      /* IN: Elements in array *paLeft */
48008   ht_slot **paRight,              /* IN/OUT: Right hand input list */
48009   int *pnRight,                   /* IN/OUT: Elements in *paRight */
48010   ht_slot *aTmp                   /* Temporary buffer */
48011 ){
48012   int iLeft = 0;                  /* Current index in aLeft */
48013   int iRight = 0;                 /* Current index in aRight */
48014   int iOut = 0;                   /* Current index in output buffer */
48015   int nRight = *pnRight;
48016   ht_slot *aRight = *paRight;
48017
48018   assert( nLeft>0 && nRight>0 );
48019   while( iRight<nRight || iLeft<nLeft ){
48020     ht_slot logpage;
48021     Pgno dbpage;
48022
48023     if( (iLeft<nLeft)
48024      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
48025     ){
48026       logpage = aLeft[iLeft++];
48027     }else{
48028       logpage = aRight[iRight++];
48029     }
48030     dbpage = aContent[logpage];
48031
48032     aTmp[iOut++] = logpage;
48033     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
48034
48035     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
48036     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
48037   }
48038
48039   *paRight = aLeft;
48040   *pnRight = iOut;
48041   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
48042 }
48043
48044 /*
48045 ** Sort the elements in list aList using aContent[] as the sort key.
48046 ** Remove elements with duplicate keys, preferring to keep the
48047 ** larger aList[] values.
48048 **
48049 ** The aList[] entries are indices into aContent[].  The values in
48050 ** aList[] are to be sorted so that for all J<K:
48051 **
48052 **      aContent[aList[J]] < aContent[aList[K]]
48053 **
48054 ** For any X and Y such that
48055 **
48056 **      aContent[aList[X]] == aContent[aList[Y]]
48057 **
48058 ** Keep the larger of the two values aList[X] and aList[Y] and discard
48059 ** the smaller.
48060 */
48061 static void walMergesort(
48062   const u32 *aContent,            /* Pages in wal */
48063   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
48064   ht_slot *aList,                 /* IN/OUT: List to sort */
48065   int *pnList                     /* IN/OUT: Number of elements in aList[] */
48066 ){
48067   struct Sublist {
48068     int nList;                    /* Number of elements in aList */
48069     ht_slot *aList;               /* Pointer to sub-list content */
48070   };
48071
48072   const int nList = *pnList;      /* Size of input list */
48073   int nMerge = 0;                 /* Number of elements in list aMerge */
48074   ht_slot *aMerge = 0;            /* List to be merged */
48075   int iList;                      /* Index into input list */
48076   int iSub = 0;                   /* Index into aSub array */
48077   struct Sublist aSub[13];        /* Array of sub-lists */
48078
48079   memset(aSub, 0, sizeof(aSub));
48080   assert( nList<=HASHTABLE_NPAGE && nList>0 );
48081   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
48082
48083   for(iList=0; iList<nList; iList++){
48084     nMerge = 1;
48085     aMerge = &aList[iList];
48086     for(iSub=0; iList & (1<<iSub); iSub++){
48087       struct Sublist *p = &aSub[iSub];
48088       assert( p->aList && p->nList<=(1<<iSub) );
48089       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
48090       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
48091     }
48092     aSub[iSub].aList = aMerge;
48093     aSub[iSub].nList = nMerge;
48094   }
48095
48096   for(iSub++; iSub<ArraySize(aSub); iSub++){
48097     if( nList & (1<<iSub) ){
48098       struct Sublist *p = &aSub[iSub];
48099       assert( p->nList<=(1<<iSub) );
48100       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
48101       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
48102     }
48103   }
48104   assert( aMerge==aList );
48105   *pnList = nMerge;
48106
48107 #ifdef SQLITE_DEBUG
48108   {
48109     int i;
48110     for(i=1; i<*pnList; i++){
48111       assert( aContent[aList[i]] > aContent[aList[i-1]] );
48112     }
48113   }
48114 #endif
48115 }
48116
48117 /*
48118 ** Free an iterator allocated by walIteratorInit().
48119 */
48120 static void walIteratorFree(WalIterator *p){
48121   sqlite3ScratchFree(p);
48122 }
48123
48124 /*
48125 ** Construct a WalInterator object that can be used to loop over all
48126 ** pages in the WAL in ascending order. The caller must hold the checkpoint
48127 ** lock.
48128 **
48129 ** On success, make *pp point to the newly allocated WalInterator object
48130 ** return SQLITE_OK. Otherwise, return an error code. If this routine
48131 ** returns an error, the value of *pp is undefined.
48132 **
48133 ** The calling routine should invoke walIteratorFree() to destroy the
48134 ** WalIterator object when it has finished with it.
48135 */
48136 static int walIteratorInit(Wal *pWal, WalIterator **pp){
48137   WalIterator *p;                 /* Return value */
48138   int nSegment;                   /* Number of segments to merge */
48139   u32 iLast;                      /* Last frame in log */
48140   int nByte;                      /* Number of bytes to allocate */
48141   int i;                          /* Iterator variable */
48142   ht_slot *aTmp;                  /* Temp space used by merge-sort */
48143   int rc = SQLITE_OK;             /* Return Code */
48144
48145   /* This routine only runs while holding the checkpoint lock. And
48146   ** it only runs if there is actually content in the log (mxFrame>0).
48147   */
48148   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
48149   iLast = pWal->hdr.mxFrame;
48150
48151   /* Allocate space for the WalIterator object. */
48152   nSegment = walFramePage(iLast) + 1;
48153   nByte = sizeof(WalIterator)
48154         + (nSegment-1)*sizeof(struct WalSegment)
48155         + iLast*sizeof(ht_slot);
48156   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
48157   if( !p ){
48158     return SQLITE_NOMEM;
48159   }
48160   memset(p, 0, nByte);
48161   p->nSegment = nSegment;
48162
48163   /* Allocate temporary space used by the merge-sort routine. This block
48164   ** of memory will be freed before this function returns.
48165   */
48166   aTmp = (ht_slot *)sqlite3ScratchMalloc(
48167       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
48168   );
48169   if( !aTmp ){
48170     rc = SQLITE_NOMEM;
48171   }
48172
48173   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
48174     volatile ht_slot *aHash;
48175     u32 iZero;
48176     volatile u32 *aPgno;
48177
48178     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
48179     if( rc==SQLITE_OK ){
48180       int j;                      /* Counter variable */
48181       int nEntry;                 /* Number of entries in this segment */
48182       ht_slot *aIndex;            /* Sorted index for this segment */
48183
48184       aPgno++;
48185       if( (i+1)==nSegment ){
48186         nEntry = (int)(iLast - iZero);
48187       }else{
48188         nEntry = (int)((u32*)aHash - (u32*)aPgno);
48189       }
48190       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
48191       iZero++;
48192
48193       for(j=0; j<nEntry; j++){
48194         aIndex[j] = (ht_slot)j;
48195       }
48196       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
48197       p->aSegment[i].iZero = iZero;
48198       p->aSegment[i].nEntry = nEntry;
48199       p->aSegment[i].aIndex = aIndex;
48200       p->aSegment[i].aPgno = (u32 *)aPgno;
48201     }
48202   }
48203   sqlite3ScratchFree(aTmp);
48204
48205   if( rc!=SQLITE_OK ){
48206     walIteratorFree(p);
48207   }
48208   *pp = p;
48209   return rc;
48210 }
48211
48212 /*
48213 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
48214 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
48215 ** busy-handler function. Invoke it and retry the lock until either the
48216 ** lock is successfully obtained or the busy-handler returns 0.
48217 */
48218 static int walBusyLock(
48219   Wal *pWal,                      /* WAL connection */
48220   int (*xBusy)(void*),            /* Function to call when busy */
48221   void *pBusyArg,                 /* Context argument for xBusyHandler */
48222   int lockIdx,                    /* Offset of first byte to lock */
48223   int n                           /* Number of bytes to lock */
48224 ){
48225   int rc;
48226   do {
48227     rc = walLockExclusive(pWal, lockIdx, n);
48228   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
48229   return rc;
48230 }
48231
48232 /*
48233 ** The cache of the wal-index header must be valid to call this function.
48234 ** Return the page-size in bytes used by the database.
48235 */
48236 static int walPagesize(Wal *pWal){
48237   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48238 }
48239
48240 /*
48241 ** Copy as much content as we can from the WAL back into the database file
48242 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
48243 **
48244 ** The amount of information copies from WAL to database might be limited
48245 ** by active readers.  This routine will never overwrite a database page
48246 ** that a concurrent reader might be using.
48247 **
48248 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
48249 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
48250 ** checkpoints are always run by a background thread or background
48251 ** process, foreground threads will never block on a lengthy fsync call.
48252 **
48253 ** Fsync is called on the WAL before writing content out of the WAL and
48254 ** into the database.  This ensures that if the new content is persistent
48255 ** in the WAL and can be recovered following a power-loss or hard reset.
48256 **
48257 ** Fsync is also called on the database file if (and only if) the entire
48258 ** WAL content is copied into the database file.  This second fsync makes
48259 ** it safe to delete the WAL since the new content will persist in the
48260 ** database file.
48261 **
48262 ** This routine uses and updates the nBackfill field of the wal-index header.
48263 ** This is the only routine tha will increase the value of nBackfill.
48264 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
48265 ** its value.)
48266 **
48267 ** The caller must be holding sufficient locks to ensure that no other
48268 ** checkpoint is running (in any other thread or process) at the same
48269 ** time.
48270 */
48271 static int walCheckpoint(
48272   Wal *pWal,                      /* Wal connection */
48273   int eMode,                      /* One of PASSIVE, FULL or RESTART */
48274   int (*xBusyCall)(void*),        /* Function to call when busy */
48275   void *pBusyArg,                 /* Context argument for xBusyHandler */
48276   int sync_flags,                 /* Flags for OsSync() (or 0) */
48277   u8 *zBuf                        /* Temporary buffer to use */
48278 ){
48279   int rc;                         /* Return code */
48280   int szPage;                     /* Database page-size */
48281   WalIterator *pIter = 0;         /* Wal iterator context */
48282   u32 iDbpage = 0;                /* Next database page to write */
48283   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
48284   u32 mxSafeFrame;                /* Max frame that can be backfilled */
48285   u32 mxPage;                     /* Max database page to write */
48286   int i;                          /* Loop counter */
48287   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
48288   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
48289
48290   szPage = walPagesize(pWal);
48291   testcase( szPage<=32768 );
48292   testcase( szPage>=65536 );
48293   pInfo = walCkptInfo(pWal);
48294   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
48295
48296   /* Allocate the iterator */
48297   rc = walIteratorInit(pWal, &pIter);
48298   if( rc!=SQLITE_OK ){
48299     return rc;
48300   }
48301   assert( pIter );
48302
48303   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
48304
48305   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
48306   ** safe to write into the database.  Frames beyond mxSafeFrame might
48307   ** overwrite database pages that are in use by active readers and thus
48308   ** cannot be backfilled from the WAL.
48309   */
48310   mxSafeFrame = pWal->hdr.mxFrame;
48311   mxPage = pWal->hdr.nPage;
48312   for(i=1; i<WAL_NREADER; i++){
48313     u32 y = pInfo->aReadMark[i];
48314     if( mxSafeFrame>y ){
48315       assert( y<=pWal->hdr.mxFrame );
48316       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
48317       if( rc==SQLITE_OK ){
48318         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
48319         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48320       }else if( rc==SQLITE_BUSY ){
48321         mxSafeFrame = y;
48322         xBusy = 0;
48323       }else{
48324         goto walcheckpoint_out;
48325       }
48326     }
48327   }
48328
48329   if( pInfo->nBackfill<mxSafeFrame
48330    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
48331   ){
48332     i64 nSize;                    /* Current size of database file */
48333     u32 nBackfill = pInfo->nBackfill;
48334
48335     /* Sync the WAL to disk */
48336     if( sync_flags ){
48337       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
48338     }
48339
48340     /* If the database file may grow as a result of this checkpoint, hint
48341     ** about the eventual size of the db file to the VFS layer.
48342     */
48343     if( rc==SQLITE_OK ){
48344       i64 nReq = ((i64)mxPage * szPage);
48345       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
48346       if( rc==SQLITE_OK && nSize<nReq ){
48347         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
48348       }
48349     }
48350
48351     /* Iterate through the contents of the WAL, copying data to the db file. */
48352     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
48353       i64 iOffset;
48354       assert( walFramePgno(pWal, iFrame)==iDbpage );
48355       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
48356       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
48357       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
48358       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
48359       if( rc!=SQLITE_OK ) break;
48360       iOffset = (iDbpage-1)*(i64)szPage;
48361       testcase( IS_BIG_INT(iOffset) );
48362       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
48363       if( rc!=SQLITE_OK ) break;
48364     }
48365
48366     /* If work was actually accomplished... */
48367     if( rc==SQLITE_OK ){
48368       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
48369         i64 szDb = pWal->hdr.nPage*(i64)szPage;
48370         testcase( IS_BIG_INT(szDb) );
48371         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
48372         if( rc==SQLITE_OK && sync_flags ){
48373           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
48374         }
48375       }
48376       if( rc==SQLITE_OK ){
48377         pInfo->nBackfill = mxSafeFrame;
48378       }
48379     }
48380
48381     /* Release the reader lock held while backfilling */
48382     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
48383   }
48384
48385   if( rc==SQLITE_BUSY ){
48386     /* Reset the return code so as not to report a checkpoint failure
48387     ** just because there are active readers.  */
48388     rc = SQLITE_OK;
48389   }
48390
48391   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
48392   ** file has been copied into the database file, then block until all
48393   ** readers have finished using the wal file. This ensures that the next
48394   ** process to write to the database restarts the wal file.
48395   */
48396   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48397     assert( pWal->writeLock );
48398     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
48399       rc = SQLITE_BUSY;
48400     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
48401       assert( mxSafeFrame==pWal->hdr.mxFrame );
48402       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
48403       if( rc==SQLITE_OK ){
48404         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48405       }
48406     }
48407   }
48408
48409  walcheckpoint_out:
48410   walIteratorFree(pIter);
48411   return rc;
48412 }
48413
48414 /*
48415 ** If the WAL file is currently larger than nMax bytes in size, truncate
48416 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
48417 */
48418 static void walLimitSize(Wal *pWal, i64 nMax){
48419   i64 sz;
48420   int rx;
48421   sqlite3BeginBenignMalloc();
48422   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
48423   if( rx==SQLITE_OK && (sz > nMax ) ){
48424     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
48425   }
48426   sqlite3EndBenignMalloc();
48427   if( rx ){
48428     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
48429   }
48430 }
48431
48432 /*
48433 ** Close a connection to a log file.
48434 */
48435 SQLITE_PRIVATE int sqlite3WalClose(
48436   Wal *pWal,                      /* Wal to close */
48437   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
48438   int nBuf,
48439   u8 *zBuf                        /* Buffer of at least nBuf bytes */
48440 ){
48441   int rc = SQLITE_OK;
48442   if( pWal ){
48443     int isDelete = 0;             /* True to unlink wal and wal-index files */
48444
48445     /* If an EXCLUSIVE lock can be obtained on the database file (using the
48446     ** ordinary, rollback-mode locking methods, this guarantees that the
48447     ** connection associated with this log file is the only connection to
48448     ** the database. In this case checkpoint the database and unlink both
48449     ** the wal and wal-index files.
48450     **
48451     ** The EXCLUSIVE lock is not released before returning.
48452     */
48453     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
48454     if( rc==SQLITE_OK ){
48455       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
48456         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
48457       }
48458       rc = sqlite3WalCheckpoint(
48459           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
48460       );
48461       if( rc==SQLITE_OK ){
48462         int bPersist = -1;
48463         sqlite3OsFileControlHint(
48464             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
48465         );
48466         if( bPersist!=1 ){
48467           /* Try to delete the WAL file if the checkpoint completed and
48468           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
48469           ** mode (!bPersist) */
48470           isDelete = 1;
48471         }else if( pWal->mxWalSize>=0 ){
48472           /* Try to truncate the WAL file to zero bytes if the checkpoint
48473           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
48474           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
48475           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
48476           ** to zero bytes as truncating to the journal_size_limit might
48477           ** leave a corrupt WAL file on disk. */
48478           walLimitSize(pWal, 0);
48479         }
48480       }
48481     }
48482
48483     walIndexClose(pWal, isDelete);
48484     sqlite3OsClose(pWal->pWalFd);
48485     if( isDelete ){
48486       sqlite3BeginBenignMalloc();
48487       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
48488       sqlite3EndBenignMalloc();
48489     }
48490     WALTRACE(("WAL%p: closed\n", pWal));
48491     sqlite3_free((void *)pWal->apWiData);
48492     sqlite3_free(pWal);
48493   }
48494   return rc;
48495 }
48496
48497 /*
48498 ** Try to read the wal-index header.  Return 0 on success and 1 if
48499 ** there is a problem.
48500 **
48501 ** The wal-index is in shared memory.  Another thread or process might
48502 ** be writing the header at the same time this procedure is trying to
48503 ** read it, which might result in inconsistency.  A dirty read is detected
48504 ** by verifying that both copies of the header are the same and also by
48505 ** a checksum on the header.
48506 **
48507 ** If and only if the read is consistent and the header is different from
48508 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
48509 ** and *pChanged is set to 1.
48510 **
48511 ** If the checksum cannot be verified return non-zero. If the header
48512 ** is read successfully and the checksum verified, return zero.
48513 */
48514 static int walIndexTryHdr(Wal *pWal, int *pChanged){
48515   u32 aCksum[2];                  /* Checksum on the header content */
48516   WalIndexHdr h1, h2;             /* Two copies of the header content */
48517   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
48518
48519   /* The first page of the wal-index must be mapped at this point. */
48520   assert( pWal->nWiData>0 && pWal->apWiData[0] );
48521
48522   /* Read the header. This might happen concurrently with a write to the
48523   ** same area of shared memory on a different CPU in a SMP,
48524   ** meaning it is possible that an inconsistent snapshot is read
48525   ** from the file. If this happens, return non-zero.
48526   **
48527   ** There are two copies of the header at the beginning of the wal-index.
48528   ** When reading, read [0] first then [1].  Writes are in the reverse order.
48529   ** Memory barriers are used to prevent the compiler or the hardware from
48530   ** reordering the reads and writes.
48531   */
48532   aHdr = walIndexHdr(pWal);
48533   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
48534   walShmBarrier(pWal);
48535   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
48536
48537   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
48538     return 1;   /* Dirty read */
48539   }
48540   if( h1.isInit==0 ){
48541     return 1;   /* Malformed header - probably all zeros */
48542   }
48543   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
48544   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
48545     return 1;   /* Checksum does not match */
48546   }
48547
48548   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
48549     *pChanged = 1;
48550     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
48551     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48552     testcase( pWal->szPage<=32768 );
48553     testcase( pWal->szPage>=65536 );
48554   }
48555
48556   /* The header was successfully read. Return zero. */
48557   return 0;
48558 }
48559
48560 /*
48561 ** Read the wal-index header from the wal-index and into pWal->hdr.
48562 ** If the wal-header appears to be corrupt, try to reconstruct the
48563 ** wal-index from the WAL before returning.
48564 **
48565 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
48566 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
48567 ** to 0.
48568 **
48569 ** If the wal-index header is successfully read, return SQLITE_OK.
48570 ** Otherwise an SQLite error code.
48571 */
48572 static int walIndexReadHdr(Wal *pWal, int *pChanged){
48573   int rc;                         /* Return code */
48574   int badHdr;                     /* True if a header read failed */
48575   volatile u32 *page0;            /* Chunk of wal-index containing header */
48576
48577   /* Ensure that page 0 of the wal-index (the page that contains the
48578   ** wal-index header) is mapped. Return early if an error occurs here.
48579   */
48580   assert( pChanged );
48581   rc = walIndexPage(pWal, 0, &page0);
48582   if( rc!=SQLITE_OK ){
48583     return rc;
48584   };
48585   assert( page0 || pWal->writeLock==0 );
48586
48587   /* If the first page of the wal-index has been mapped, try to read the
48588   ** wal-index header immediately, without holding any lock. This usually
48589   ** works, but may fail if the wal-index header is corrupt or currently
48590   ** being modified by another thread or process.
48591   */
48592   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
48593
48594   /* If the first attempt failed, it might have been due to a race
48595   ** with a writer.  So get a WRITE lock and try again.
48596   */
48597   assert( badHdr==0 || pWal->writeLock==0 );
48598   if( badHdr ){
48599     if( pWal->readOnly & WAL_SHM_RDONLY ){
48600       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
48601         walUnlockShared(pWal, WAL_WRITE_LOCK);
48602         rc = SQLITE_READONLY_RECOVERY;
48603       }
48604     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
48605       pWal->writeLock = 1;
48606       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
48607         badHdr = walIndexTryHdr(pWal, pChanged);
48608         if( badHdr ){
48609           /* If the wal-index header is still malformed even while holding
48610           ** a WRITE lock, it can only mean that the header is corrupted and
48611           ** needs to be reconstructed.  So run recovery to do exactly that.
48612           */
48613           rc = walIndexRecover(pWal);
48614           *pChanged = 1;
48615         }
48616       }
48617       pWal->writeLock = 0;
48618       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48619     }
48620   }
48621
48622   /* If the header is read successfully, check the version number to make
48623   ** sure the wal-index was not constructed with some future format that
48624   ** this version of SQLite cannot understand.
48625   */
48626   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
48627     rc = SQLITE_CANTOPEN_BKPT;
48628   }
48629
48630   return rc;
48631 }
48632
48633 /*
48634 ** This is the value that walTryBeginRead returns when it needs to
48635 ** be retried.
48636 */
48637 #define WAL_RETRY  (-1)
48638
48639 /*
48640 ** Attempt to start a read transaction.  This might fail due to a race or
48641 ** other transient condition.  When that happens, it returns WAL_RETRY to
48642 ** indicate to the caller that it is safe to retry immediately.
48643 **
48644 ** On success return SQLITE_OK.  On a permanent failure (such an
48645 ** I/O error or an SQLITE_BUSY because another process is running
48646 ** recovery) return a positive error code.
48647 **
48648 ** The useWal parameter is true to force the use of the WAL and disable
48649 ** the case where the WAL is bypassed because it has been completely
48650 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
48651 ** to make a copy of the wal-index header into pWal->hdr.  If the
48652 ** wal-index header has changed, *pChanged is set to 1 (as an indication
48653 ** to the caller that the local paget cache is obsolete and needs to be
48654 ** flushed.)  When useWal==1, the wal-index header is assumed to already
48655 ** be loaded and the pChanged parameter is unused.
48656 **
48657 ** The caller must set the cnt parameter to the number of prior calls to
48658 ** this routine during the current read attempt that returned WAL_RETRY.
48659 ** This routine will start taking more aggressive measures to clear the
48660 ** race conditions after multiple WAL_RETRY returns, and after an excessive
48661 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
48662 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
48663 ** and is not honoring the locking protocol.  There is a vanishingly small
48664 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
48665 ** bad luck when there is lots of contention for the wal-index, but that
48666 ** possibility is so small that it can be safely neglected, we believe.
48667 **
48668 ** On success, this routine obtains a read lock on
48669 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
48670 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
48671 ** that means the Wal does not hold any read lock.  The reader must not
48672 ** access any database page that is modified by a WAL frame up to and
48673 ** including frame number aReadMark[pWal->readLock].  The reader will
48674 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
48675 ** Or if pWal->readLock==0, then the reader will ignore the WAL
48676 ** completely and get all content directly from the database file.
48677 ** If the useWal parameter is 1 then the WAL will never be ignored and
48678 ** this routine will always set pWal->readLock>0 on success.
48679 ** When the read transaction is completed, the caller must release the
48680 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
48681 **
48682 ** This routine uses the nBackfill and aReadMark[] fields of the header
48683 ** to select a particular WAL_READ_LOCK() that strives to let the
48684 ** checkpoint process do as much work as possible.  This routine might
48685 ** update values of the aReadMark[] array in the header, but if it does
48686 ** so it takes care to hold an exclusive lock on the corresponding
48687 ** WAL_READ_LOCK() while changing values.
48688 */
48689 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
48690   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
48691   u32 mxReadMark;                 /* Largest aReadMark[] value */
48692   int mxI;                        /* Index of largest aReadMark[] value */
48693   int i;                          /* Loop counter */
48694   int rc = SQLITE_OK;             /* Return code  */
48695
48696   assert( pWal->readLock<0 );     /* Not currently locked */
48697
48698   /* Take steps to avoid spinning forever if there is a protocol error.
48699   **
48700   ** Circumstances that cause a RETRY should only last for the briefest
48701   ** instances of time.  No I/O or other system calls are done while the
48702   ** locks are held, so the locks should not be held for very long. But
48703   ** if we are unlucky, another process that is holding a lock might get
48704   ** paged out or take a page-fault that is time-consuming to resolve,
48705   ** during the few nanoseconds that it is holding the lock.  In that case,
48706   ** it might take longer than normal for the lock to free.
48707   **
48708   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
48709   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
48710   ** is more of a scheduler yield than an actual delay.  But on the 10th
48711   ** an subsequent retries, the delays start becoming longer and longer,
48712   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
48713   ** The total delay time before giving up is less than 1 second.
48714   */
48715   if( cnt>5 ){
48716     int nDelay = 1;                      /* Pause time in microseconds */
48717     if( cnt>100 ){
48718       VVA_ONLY( pWal->lockError = 1; )
48719       return SQLITE_PROTOCOL;
48720     }
48721     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
48722     sqlite3OsSleep(pWal->pVfs, nDelay);
48723   }
48724
48725   if( !useWal ){
48726     rc = walIndexReadHdr(pWal, pChanged);
48727     if( rc==SQLITE_BUSY ){
48728       /* If there is not a recovery running in another thread or process
48729       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
48730       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
48731       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
48732       ** would be technically correct.  But the race is benign since with
48733       ** WAL_RETRY this routine will be called again and will probably be
48734       ** right on the second iteration.
48735       */
48736       if( pWal->apWiData[0]==0 ){
48737         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
48738         ** We assume this is a transient condition, so return WAL_RETRY. The
48739         ** xShmMap() implementation used by the default unix and win32 VFS
48740         ** modules may return SQLITE_BUSY due to a race condition in the
48741         ** code that determines whether or not the shared-memory region
48742         ** must be zeroed before the requested page is returned.
48743         */
48744         rc = WAL_RETRY;
48745       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
48746         walUnlockShared(pWal, WAL_RECOVER_LOCK);
48747         rc = WAL_RETRY;
48748       }else if( rc==SQLITE_BUSY ){
48749         rc = SQLITE_BUSY_RECOVERY;
48750       }
48751     }
48752     if( rc!=SQLITE_OK ){
48753       return rc;
48754     }
48755   }
48756
48757   pInfo = walCkptInfo(pWal);
48758   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
48759     /* The WAL has been completely backfilled (or it is empty).
48760     ** and can be safely ignored.
48761     */
48762     rc = walLockShared(pWal, WAL_READ_LOCK(0));
48763     walShmBarrier(pWal);
48764     if( rc==SQLITE_OK ){
48765       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
48766         /* It is not safe to allow the reader to continue here if frames
48767         ** may have been appended to the log before READ_LOCK(0) was obtained.
48768         ** When holding READ_LOCK(0), the reader ignores the entire log file,
48769         ** which implies that the database file contains a trustworthy
48770         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
48771         ** happening, this is usually correct.
48772         **
48773         ** However, if frames have been appended to the log (or if the log
48774         ** is wrapped and written for that matter) before the READ_LOCK(0)
48775         ** is obtained, that is not necessarily true. A checkpointer may
48776         ** have started to backfill the appended frames but crashed before
48777         ** it finished. Leaving a corrupt image in the database file.
48778         */
48779         walUnlockShared(pWal, WAL_READ_LOCK(0));
48780         return WAL_RETRY;
48781       }
48782       pWal->readLock = 0;
48783       return SQLITE_OK;
48784     }else if( rc!=SQLITE_BUSY ){
48785       return rc;
48786     }
48787   }
48788
48789   /* If we get this far, it means that the reader will want to use
48790   ** the WAL to get at content from recent commits.  The job now is
48791   ** to select one of the aReadMark[] entries that is closest to
48792   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
48793   */
48794   mxReadMark = 0;
48795   mxI = 0;
48796   for(i=1; i<WAL_NREADER; i++){
48797     u32 thisMark = pInfo->aReadMark[i];
48798     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
48799       assert( thisMark!=READMARK_NOT_USED );
48800       mxReadMark = thisMark;
48801       mxI = i;
48802     }
48803   }
48804   /* There was once an "if" here. The extra "{" is to preserve indentation. */
48805   {
48806     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
48807      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
48808     ){
48809       for(i=1; i<WAL_NREADER; i++){
48810         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
48811         if( rc==SQLITE_OK ){
48812           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
48813           mxI = i;
48814           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48815           break;
48816         }else if( rc!=SQLITE_BUSY ){
48817           return rc;
48818         }
48819       }
48820     }
48821     if( mxI==0 ){
48822       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
48823       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
48824     }
48825
48826     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
48827     if( rc ){
48828       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
48829     }
48830     /* Now that the read-lock has been obtained, check that neither the
48831     ** value in the aReadMark[] array or the contents of the wal-index
48832     ** header have changed.
48833     **
48834     ** It is necessary to check that the wal-index header did not change
48835     ** between the time it was read and when the shared-lock was obtained
48836     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
48837     ** that the log file may have been wrapped by a writer, or that frames
48838     ** that occur later in the log than pWal->hdr.mxFrame may have been
48839     ** copied into the database by a checkpointer. If either of these things
48840     ** happened, then reading the database with the current value of
48841     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
48842     ** instead.
48843     **
48844     ** This does not guarantee that the copy of the wal-index header is up to
48845     ** date before proceeding. That would not be possible without somehow
48846     ** blocking writers. It only guarantees that a dangerous checkpoint or
48847     ** log-wrap (either of which would require an exclusive lock on
48848     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
48849     */
48850     walShmBarrier(pWal);
48851     if( pInfo->aReadMark[mxI]!=mxReadMark
48852      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
48853     ){
48854       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
48855       return WAL_RETRY;
48856     }else{
48857       assert( mxReadMark<=pWal->hdr.mxFrame );
48858       pWal->readLock = (i16)mxI;
48859     }
48860   }
48861   return rc;
48862 }
48863
48864 /*
48865 ** Begin a read transaction on the database.
48866 **
48867 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
48868 ** it takes a snapshot of the state of the WAL and wal-index for the current
48869 ** instant in time.  The current thread will continue to use this snapshot.
48870 ** Other threads might append new content to the WAL and wal-index but
48871 ** that extra content is ignored by the current thread.
48872 **
48873 ** If the database contents have changes since the previous read
48874 ** transaction, then *pChanged is set to 1 before returning.  The
48875 ** Pager layer will use this to know that is cache is stale and
48876 ** needs to be flushed.
48877 */
48878 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
48879   int rc;                         /* Return code */
48880   int cnt = 0;                    /* Number of TryBeginRead attempts */
48881
48882   do{
48883     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
48884   }while( rc==WAL_RETRY );
48885   testcase( (rc&0xff)==SQLITE_BUSY );
48886   testcase( (rc&0xff)==SQLITE_IOERR );
48887   testcase( rc==SQLITE_PROTOCOL );
48888   testcase( rc==SQLITE_OK );
48889   return rc;
48890 }
48891
48892 /*
48893 ** Finish with a read transaction.  All this does is release the
48894 ** read-lock.
48895 */
48896 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
48897   sqlite3WalEndWriteTransaction(pWal);
48898   if( pWal->readLock>=0 ){
48899     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48900     pWal->readLock = -1;
48901   }
48902 }
48903
48904 /*
48905 ** Read a page from the WAL, if it is present in the WAL and if the
48906 ** current read transaction is configured to use the WAL.
48907 **
48908 ** The *pInWal is set to 1 if the requested page is in the WAL and
48909 ** has been loaded.  Or *pInWal is set to 0 if the page was not in
48910 ** the WAL and needs to be read out of the database.
48911 */
48912 SQLITE_PRIVATE int sqlite3WalRead(
48913   Wal *pWal,                      /* WAL handle */
48914   Pgno pgno,                      /* Database page number to read data for */
48915   int *pInWal,                    /* OUT: True if data is read from WAL */
48916   int nOut,                       /* Size of buffer pOut in bytes */
48917   u8 *pOut                        /* Buffer to write page data to */
48918 ){
48919   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
48920   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
48921   int iHash;                      /* Used to loop through N hash tables */
48922
48923   /* This routine is only be called from within a read transaction. */
48924   assert( pWal->readLock>=0 || pWal->lockError );
48925
48926   /* If the "last page" field of the wal-index header snapshot is 0, then
48927   ** no data will be read from the wal under any circumstances. Return early
48928   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
48929   ** then the WAL is ignored by the reader so return early, as if the
48930   ** WAL were empty.
48931   */
48932   if( iLast==0 || pWal->readLock==0 ){
48933     *pInWal = 0;
48934     return SQLITE_OK;
48935   }
48936
48937   /* Search the hash table or tables for an entry matching page number
48938   ** pgno. Each iteration of the following for() loop searches one
48939   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
48940   **
48941   ** This code might run concurrently to the code in walIndexAppend()
48942   ** that adds entries to the wal-index (and possibly to this hash
48943   ** table). This means the value just read from the hash
48944   ** slot (aHash[iKey]) may have been added before or after the
48945   ** current read transaction was opened. Values added after the
48946   ** read transaction was opened may have been written incorrectly -
48947   ** i.e. these slots may contain garbage data. However, we assume
48948   ** that any slots written before the current read transaction was
48949   ** opened remain unmodified.
48950   **
48951   ** For the reasons above, the if(...) condition featured in the inner
48952   ** loop of the following block is more stringent that would be required
48953   ** if we had exclusive access to the hash-table:
48954   **
48955   **   (aPgno[iFrame]==pgno):
48956   **     This condition filters out normal hash-table collisions.
48957   **
48958   **   (iFrame<=iLast):
48959   **     This condition filters out entries that were added to the hash
48960   **     table after the current read-transaction had started.
48961   */
48962   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
48963     volatile ht_slot *aHash;      /* Pointer to hash table */
48964     volatile u32 *aPgno;          /* Pointer to array of page numbers */
48965     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
48966     int iKey;                     /* Hash slot index */
48967     int nCollide;                 /* Number of hash collisions remaining */
48968     int rc;                       /* Error code */
48969
48970     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
48971     if( rc!=SQLITE_OK ){
48972       return rc;
48973     }
48974     nCollide = HASHTABLE_NSLOT;
48975     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
48976       u32 iFrame = aHash[iKey] + iZero;
48977       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
48978         /* assert( iFrame>iRead ); -- not true if there is corruption */
48979         iRead = iFrame;
48980       }
48981       if( (nCollide--)==0 ){
48982         return SQLITE_CORRUPT_BKPT;
48983       }
48984     }
48985   }
48986
48987 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
48988   /* If expensive assert() statements are available, do a linear search
48989   ** of the wal-index file content. Make sure the results agree with the
48990   ** result obtained using the hash indexes above.  */
48991   {
48992     u32 iRead2 = 0;
48993     u32 iTest;
48994     for(iTest=iLast; iTest>0; iTest--){
48995       if( walFramePgno(pWal, iTest)==pgno ){
48996         iRead2 = iTest;
48997         break;
48998       }
48999     }
49000     assert( iRead==iRead2 );
49001   }
49002 #endif
49003
49004   /* If iRead is non-zero, then it is the log frame number that contains the
49005   ** required page. Read and return data from the log file.
49006   */
49007   if( iRead ){
49008     int sz;
49009     i64 iOffset;
49010     sz = pWal->hdr.szPage;
49011     sz = (sz&0xfe00) + ((sz&0x0001)<<16);
49012     testcase( sz<=32768 );
49013     testcase( sz>=65536 );
49014     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
49015     *pInWal = 1;
49016     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
49017     return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
49018   }
49019
49020   *pInWal = 0;
49021   return SQLITE_OK;
49022 }
49023
49024
49025 /*
49026 ** Return the size of the database in pages (or zero, if unknown).
49027 */
49028 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
49029   if( pWal && ALWAYS(pWal->readLock>=0) ){
49030     return pWal->hdr.nPage;
49031   }
49032   return 0;
49033 }
49034
49035
49036 /*
49037 ** This function starts a write transaction on the WAL.
49038 **
49039 ** A read transaction must have already been started by a prior call
49040 ** to sqlite3WalBeginReadTransaction().
49041 **
49042 ** If another thread or process has written into the database since
49043 ** the read transaction was started, then it is not possible for this
49044 ** thread to write as doing so would cause a fork.  So this routine
49045 ** returns SQLITE_BUSY in that case and no write transaction is started.
49046 **
49047 ** There can only be a single writer active at a time.
49048 */
49049 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
49050   int rc;
49051
49052   /* Cannot start a write transaction without first holding a read
49053   ** transaction. */
49054   assert( pWal->readLock>=0 );
49055
49056   if( pWal->readOnly ){
49057     return SQLITE_READONLY;
49058   }
49059
49060   /* Only one writer allowed at a time.  Get the write lock.  Return
49061   ** SQLITE_BUSY if unable.
49062   */
49063   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
49064   if( rc ){
49065     return rc;
49066   }
49067   pWal->writeLock = 1;
49068
49069   /* If another connection has written to the database file since the
49070   ** time the read transaction on this connection was started, then
49071   ** the write is disallowed.
49072   */
49073   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
49074     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
49075     pWal->writeLock = 0;
49076     rc = SQLITE_BUSY;
49077   }
49078
49079   return rc;
49080 }
49081
49082 /*
49083 ** End a write transaction.  The commit has already been done.  This
49084 ** routine merely releases the lock.
49085 */
49086 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
49087   if( pWal->writeLock ){
49088     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
49089     pWal->writeLock = 0;
49090     pWal->truncateOnCommit = 0;
49091   }
49092   return SQLITE_OK;
49093 }
49094
49095 /*
49096 ** If any data has been written (but not committed) to the log file, this
49097 ** function moves the write-pointer back to the start of the transaction.
49098 **
49099 ** Additionally, the callback function is invoked for each frame written
49100 ** to the WAL since the start of the transaction. If the callback returns
49101 ** other than SQLITE_OK, it is not invoked again and the error code is
49102 ** returned to the caller.
49103 **
49104 ** Otherwise, if the callback function does not return an error, this
49105 ** function returns SQLITE_OK.
49106 */
49107 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
49108   int rc = SQLITE_OK;
49109   if( ALWAYS(pWal->writeLock) ){
49110     Pgno iMax = pWal->hdr.mxFrame;
49111     Pgno iFrame;
49112
49113     /* Restore the clients cache of the wal-index header to the state it
49114     ** was in before the client began writing to the database.
49115     */
49116     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
49117
49118     for(iFrame=pWal->hdr.mxFrame+1;
49119         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
49120         iFrame++
49121     ){
49122       /* This call cannot fail. Unless the page for which the page number
49123       ** is passed as the second argument is (a) in the cache and
49124       ** (b) has an outstanding reference, then xUndo is either a no-op
49125       ** (if (a) is false) or simply expels the page from the cache (if (b)
49126       ** is false).
49127       **
49128       ** If the upper layer is doing a rollback, it is guaranteed that there
49129       ** are no outstanding references to any page other than page 1. And
49130       ** page 1 is never written to the log until the transaction is
49131       ** committed. As a result, the call to xUndo may not fail.
49132       */
49133       assert( walFramePgno(pWal, iFrame)!=1 );
49134       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
49135     }
49136     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
49137   }
49138   assert( rc==SQLITE_OK );
49139   return rc;
49140 }
49141
49142 /*
49143 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
49144 ** values. This function populates the array with values required to
49145 ** "rollback" the write position of the WAL handle back to the current
49146 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
49147 */
49148 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
49149   assert( pWal->writeLock );
49150   aWalData[0] = pWal->hdr.mxFrame;
49151   aWalData[1] = pWal->hdr.aFrameCksum[0];
49152   aWalData[2] = pWal->hdr.aFrameCksum[1];
49153   aWalData[3] = pWal->nCkpt;
49154 }
49155
49156 /*
49157 ** Move the write position of the WAL back to the point identified by
49158 ** the values in the aWalData[] array. aWalData must point to an array
49159 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
49160 ** by a call to WalSavepoint().
49161 */
49162 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
49163   int rc = SQLITE_OK;
49164
49165   assert( pWal->writeLock );
49166   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
49167
49168   if( aWalData[3]!=pWal->nCkpt ){
49169     /* This savepoint was opened immediately after the write-transaction
49170     ** was started. Right after that, the writer decided to wrap around
49171     ** to the start of the log. Update the savepoint values to match.
49172     */
49173     aWalData[0] = 0;
49174     aWalData[3] = pWal->nCkpt;
49175   }
49176
49177   if( aWalData[0]<pWal->hdr.mxFrame ){
49178     pWal->hdr.mxFrame = aWalData[0];
49179     pWal->hdr.aFrameCksum[0] = aWalData[1];
49180     pWal->hdr.aFrameCksum[1] = aWalData[2];
49181     walCleanupHash(pWal);
49182   }
49183
49184   return rc;
49185 }
49186
49187
49188 /*
49189 ** This function is called just before writing a set of frames to the log
49190 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
49191 ** to the current log file, it is possible to overwrite the start of the
49192 ** existing log file with the new frames (i.e. "reset" the log). If so,
49193 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
49194 ** unchanged.
49195 **
49196 ** SQLITE_OK is returned if no error is encountered (regardless of whether
49197 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
49198 ** if an error occurs.
49199 */
49200 static int walRestartLog(Wal *pWal){
49201   int rc = SQLITE_OK;
49202   int cnt;
49203
49204   if( pWal->readLock==0 ){
49205     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
49206     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
49207     if( pInfo->nBackfill>0 ){
49208       u32 salt1;
49209       sqlite3_randomness(4, &salt1);
49210       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
49211       if( rc==SQLITE_OK ){
49212         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
49213         ** readers are currently using the WAL), then the transactions
49214         ** frames will overwrite the start of the existing log. Update the
49215         ** wal-index header to reflect this.
49216         **
49217         ** In theory it would be Ok to update the cache of the header only
49218         ** at this point. But updating the actual wal-index header is also
49219         ** safe and means there is no special case for sqlite3WalUndo()
49220         ** to handle if this transaction is rolled back.
49221         */
49222         int i;                    /* Loop counter */
49223         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
49224
49225         pWal->nCkpt++;
49226         pWal->hdr.mxFrame = 0;
49227         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
49228         aSalt[1] = salt1;
49229         walIndexWriteHdr(pWal);
49230         pInfo->nBackfill = 0;
49231         pInfo->aReadMark[1] = 0;
49232         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
49233         assert( pInfo->aReadMark[0]==0 );
49234         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
49235       }else if( rc!=SQLITE_BUSY ){
49236         return rc;
49237       }
49238     }
49239     walUnlockShared(pWal, WAL_READ_LOCK(0));
49240     pWal->readLock = -1;
49241     cnt = 0;
49242     do{
49243       int notUsed;
49244       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
49245     }while( rc==WAL_RETRY );
49246     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
49247     testcase( (rc&0xff)==SQLITE_IOERR );
49248     testcase( rc==SQLITE_PROTOCOL );
49249     testcase( rc==SQLITE_OK );
49250   }
49251   return rc;
49252 }
49253
49254 /*
49255 ** Information about the current state of the WAL file and where
49256 ** the next fsync should occur - passed from sqlite3WalFrames() into
49257 ** walWriteToLog().
49258 */
49259 typedef struct WalWriter {
49260   Wal *pWal;                   /* The complete WAL information */
49261   sqlite3_file *pFd;           /* The WAL file to which we write */
49262   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
49263   int syncFlags;               /* Flags for the fsync */
49264   int szPage;                  /* Size of one page */
49265 } WalWriter;
49266
49267 /*
49268 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
49269 ** Do a sync when crossing the p->iSyncPoint boundary.
49270 **
49271 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
49272 ** first write the part before iSyncPoint, then sync, then write the
49273 ** rest.
49274 */
49275 static int walWriteToLog(
49276   WalWriter *p,              /* WAL to write to */
49277   void *pContent,            /* Content to be written */
49278   int iAmt,                  /* Number of bytes to write */
49279   sqlite3_int64 iOffset      /* Start writing at this offset */
49280 ){
49281   int rc;
49282   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
49283     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
49284     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
49285     if( rc ) return rc;
49286     iOffset += iFirstAmt;
49287     iAmt -= iFirstAmt;
49288     pContent = (void*)(iFirstAmt + (char*)pContent);
49289     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
49290     rc = sqlite3OsSync(p->pFd, p->syncFlags);
49291     if( iAmt==0 || rc ) return rc;
49292   }
49293   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
49294   return rc;
49295 }
49296
49297 /*
49298 ** Write out a single frame of the WAL
49299 */
49300 static int walWriteOneFrame(
49301   WalWriter *p,               /* Where to write the frame */
49302   PgHdr *pPage,               /* The page of the frame to be written */
49303   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
49304   sqlite3_int64 iOffset       /* Byte offset at which to write */
49305 ){
49306   int rc;                         /* Result code from subfunctions */
49307   void *pData;                    /* Data actually written */
49308   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
49309 #if defined(SQLITE_HAS_CODEC)
49310   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
49311 #else
49312   pData = pPage->pData;
49313 #endif
49314   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
49315   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
49316   if( rc ) return rc;
49317   /* Write the page data */
49318   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
49319   return rc;
49320 }
49321
49322 /*
49323 ** Write a set of frames to the log. The caller must hold the write-lock
49324 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
49325 */
49326 SQLITE_PRIVATE int sqlite3WalFrames(
49327   Wal *pWal,                      /* Wal handle to write to */
49328   int szPage,                     /* Database page-size in bytes */
49329   PgHdr *pList,                   /* List of dirty pages to write */
49330   Pgno nTruncate,                 /* Database size after this commit */
49331   int isCommit,                   /* True if this is a commit */
49332   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
49333 ){
49334   int rc;                         /* Used to catch return codes */
49335   u32 iFrame;                     /* Next frame address */
49336   PgHdr *p;                       /* Iterator to run through pList with. */
49337   PgHdr *pLast = 0;               /* Last frame in list */
49338   int nExtra = 0;                 /* Number of extra copies of last page */
49339   int szFrame;                    /* The size of a single frame */
49340   i64 iOffset;                    /* Next byte to write in WAL file */
49341   WalWriter w;                    /* The writer */
49342
49343   assert( pList );
49344   assert( pWal->writeLock );
49345
49346   /* If this frame set completes a transaction, then nTruncate>0.  If
49347   ** nTruncate==0 then this frame set does not complete the transaction. */
49348   assert( (isCommit!=0)==(nTruncate!=0) );
49349
49350 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49351   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
49352     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
49353               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
49354   }
49355 #endif
49356
49357   /* See if it is possible to write these frames into the start of the
49358   ** log file, instead of appending to it at pWal->hdr.mxFrame.
49359   */
49360   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
49361     return rc;
49362   }
49363
49364   /* If this is the first frame written into the log, write the WAL
49365   ** header to the start of the WAL file. See comments at the top of
49366   ** this source file for a description of the WAL header format.
49367   */
49368   iFrame = pWal->hdr.mxFrame;
49369   if( iFrame==0 ){
49370     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
49371     u32 aCksum[2];                /* Checksum for wal-header */
49372
49373     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
49374     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
49375     sqlite3Put4byte(&aWalHdr[8], szPage);
49376     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
49377     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
49378     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
49379     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
49380     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
49381     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
49382
49383     pWal->szPage = szPage;
49384     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
49385     pWal->hdr.aFrameCksum[0] = aCksum[0];
49386     pWal->hdr.aFrameCksum[1] = aCksum[1];
49387     pWal->truncateOnCommit = 1;
49388
49389     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
49390     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
49391     if( rc!=SQLITE_OK ){
49392       return rc;
49393     }
49394
49395     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
49396     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
49397     ** an out-of-order write following a WAL restart could result in
49398     ** database corruption.  See the ticket:
49399     **
49400     **     http://localhost:591/sqlite/info/ff5be73dee
49401     */
49402     if( pWal->syncHeader && sync_flags ){
49403       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
49404       if( rc ) return rc;
49405     }
49406   }
49407   assert( (int)pWal->szPage==szPage );
49408
49409   /* Setup information needed to write frames into the WAL */
49410   w.pWal = pWal;
49411   w.pFd = pWal->pWalFd;
49412   w.iSyncPoint = 0;
49413   w.syncFlags = sync_flags;
49414   w.szPage = szPage;
49415   iOffset = walFrameOffset(iFrame+1, szPage);
49416   szFrame = szPage + WAL_FRAME_HDRSIZE;
49417
49418   /* Write all frames into the log file exactly once */
49419   for(p=pList; p; p=p->pDirty){
49420     int nDbSize;   /* 0 normally.  Positive == commit flag */
49421     iFrame++;
49422     assert( iOffset==walFrameOffset(iFrame, szPage) );
49423     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
49424     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
49425     if( rc ) return rc;
49426     pLast = p;
49427     iOffset += szFrame;
49428   }
49429
49430   /* If this is the end of a transaction, then we might need to pad
49431   ** the transaction and/or sync the WAL file.
49432   **
49433   ** Padding and syncing only occur if this set of frames complete a
49434   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
49435   ** or synchonous==OFF, then no padding or syncing are needed.
49436   **
49437   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
49438   ** needed and only the sync is done.  If padding is needed, then the
49439   ** final frame is repeated (with its commit mark) until the next sector
49440   ** boundary is crossed.  Only the part of the WAL prior to the last
49441   ** sector boundary is synced; the part of the last frame that extends
49442   ** past the sector boundary is written after the sync.
49443   */
49444   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
49445     if( pWal->padToSectorBoundary ){
49446       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
49447       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
49448       while( iOffset<w.iSyncPoint ){
49449         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
49450         if( rc ) return rc;
49451         iOffset += szFrame;
49452         nExtra++;
49453       }
49454     }else{
49455       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
49456     }
49457   }
49458
49459   /* If this frame set completes the first transaction in the WAL and
49460   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
49461   ** journal size limit, if possible.
49462   */
49463   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
49464     i64 sz = pWal->mxWalSize;
49465     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
49466       sz = walFrameOffset(iFrame+nExtra+1, szPage);
49467     }
49468     walLimitSize(pWal, sz);
49469     pWal->truncateOnCommit = 0;
49470   }
49471
49472   /* Append data to the wal-index. It is not necessary to lock the
49473   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
49474   ** guarantees that there are no other writers, and no data that may
49475   ** be in use by existing readers is being overwritten.
49476   */
49477   iFrame = pWal->hdr.mxFrame;
49478   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
49479     iFrame++;
49480     rc = walIndexAppend(pWal, iFrame, p->pgno);
49481   }
49482   while( rc==SQLITE_OK && nExtra>0 ){
49483     iFrame++;
49484     nExtra--;
49485     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
49486   }
49487
49488   if( rc==SQLITE_OK ){
49489     /* Update the private copy of the header. */
49490     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49491     testcase( szPage<=32768 );
49492     testcase( szPage>=65536 );
49493     pWal->hdr.mxFrame = iFrame;
49494     if( isCommit ){
49495       pWal->hdr.iChange++;
49496       pWal->hdr.nPage = nTruncate;
49497     }
49498     /* If this is a commit, update the wal-index header too. */
49499     if( isCommit ){
49500       walIndexWriteHdr(pWal);
49501       pWal->iCallback = iFrame;
49502     }
49503   }
49504
49505   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
49506   return rc;
49507 }
49508
49509 /*
49510 ** This routine is called to implement sqlite3_wal_checkpoint() and
49511 ** related interfaces.
49512 **
49513 ** Obtain a CHECKPOINT lock and then backfill as much information as
49514 ** we can from WAL into the database.
49515 **
49516 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
49517 ** callback. In this case this function runs a blocking checkpoint.
49518 */
49519 SQLITE_PRIVATE int sqlite3WalCheckpoint(
49520   Wal *pWal,                      /* Wal connection */
49521   int eMode,                      /* PASSIVE, FULL or RESTART */
49522   int (*xBusy)(void*),            /* Function to call when busy */
49523   void *pBusyArg,                 /* Context argument for xBusyHandler */
49524   int sync_flags,                 /* Flags to sync db file with (or 0) */
49525   int nBuf,                       /* Size of temporary buffer */
49526   u8 *zBuf,                       /* Temporary buffer to use */
49527   int *pnLog,                     /* OUT: Number of frames in WAL */
49528   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
49529 ){
49530   int rc;                         /* Return code */
49531   int isChanged = 0;              /* True if a new wal-index header is loaded */
49532   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
49533
49534   assert( pWal->ckptLock==0 );
49535   assert( pWal->writeLock==0 );
49536
49537   if( pWal->readOnly ) return SQLITE_READONLY;
49538   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
49539   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
49540   if( rc ){
49541     /* Usually this is SQLITE_BUSY meaning that another thread or process
49542     ** is already running a checkpoint, or maybe a recovery.  But it might
49543     ** also be SQLITE_IOERR. */
49544     return rc;
49545   }
49546   pWal->ckptLock = 1;
49547
49548   /* If this is a blocking-checkpoint, then obtain the write-lock as well
49549   ** to prevent any writers from running while the checkpoint is underway.
49550   ** This has to be done before the call to walIndexReadHdr() below.
49551   **
49552   ** If the writer lock cannot be obtained, then a passive checkpoint is
49553   ** run instead. Since the checkpointer is not holding the writer lock,
49554   ** there is no point in blocking waiting for any readers. Assuming no
49555   ** other error occurs, this function will return SQLITE_BUSY to the caller.
49556   */
49557   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
49558     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
49559     if( rc==SQLITE_OK ){
49560       pWal->writeLock = 1;
49561     }else if( rc==SQLITE_BUSY ){
49562       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
49563       rc = SQLITE_OK;
49564     }
49565   }
49566
49567   /* Read the wal-index header. */
49568   if( rc==SQLITE_OK ){
49569     rc = walIndexReadHdr(pWal, &isChanged);
49570   }
49571
49572   /* Copy data from the log to the database file. */
49573   if( rc==SQLITE_OK ){
49574     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
49575       rc = SQLITE_CORRUPT_BKPT;
49576     }else{
49577       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
49578     }
49579
49580     /* If no error occurred, set the output variables. */
49581     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
49582       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
49583       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
49584     }
49585   }
49586
49587   if( isChanged ){
49588     /* If a new wal-index header was loaded before the checkpoint was
49589     ** performed, then the pager-cache associated with pWal is now
49590     ** out of date. So zero the cached wal-index header to ensure that
49591     ** next time the pager opens a snapshot on this database it knows that
49592     ** the cache needs to be reset.
49593     */
49594     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49595   }
49596
49597   /* Release the locks. */
49598   sqlite3WalEndWriteTransaction(pWal);
49599   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
49600   pWal->ckptLock = 0;
49601   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
49602   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
49603 }
49604
49605 /* Return the value to pass to a sqlite3_wal_hook callback, the
49606 ** number of frames in the WAL at the point of the last commit since
49607 ** sqlite3WalCallback() was called.  If no commits have occurred since
49608 ** the last call, then return 0.
49609 */
49610 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
49611   u32 ret = 0;
49612   if( pWal ){
49613     ret = pWal->iCallback;
49614     pWal->iCallback = 0;
49615   }
49616   return (int)ret;
49617 }
49618
49619 /*
49620 ** This function is called to change the WAL subsystem into or out
49621 ** of locking_mode=EXCLUSIVE.
49622 **
49623 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
49624 ** into locking_mode=NORMAL.  This means that we must acquire a lock
49625 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
49626 ** or if the acquisition of the lock fails, then return 0.  If the
49627 ** transition out of exclusive-mode is successful, return 1.  This
49628 ** operation must occur while the pager is still holding the exclusive
49629 ** lock on the main database file.
49630 **
49631 ** If op is one, then change from locking_mode=NORMAL into
49632 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
49633 ** be released.  Return 1 if the transition is made and 0 if the
49634 ** WAL is already in exclusive-locking mode - meaning that this
49635 ** routine is a no-op.  The pager must already hold the exclusive lock
49636 ** on the main database file before invoking this operation.
49637 **
49638 ** If op is negative, then do a dry-run of the op==1 case but do
49639 ** not actually change anything. The pager uses this to see if it
49640 ** should acquire the database exclusive lock prior to invoking
49641 ** the op==1 case.
49642 */
49643 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
49644   int rc;
49645   assert( pWal->writeLock==0 );
49646   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
49647
49648   /* pWal->readLock is usually set, but might be -1 if there was a
49649   ** prior error while attempting to acquire are read-lock. This cannot
49650   ** happen if the connection is actually in exclusive mode (as no xShmLock
49651   ** locks are taken in this case). Nor should the pager attempt to
49652   ** upgrade to exclusive-mode following such an error.
49653   */
49654   assert( pWal->readLock>=0 || pWal->lockError );
49655   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
49656
49657   if( op==0 ){
49658     if( pWal->exclusiveMode ){
49659       pWal->exclusiveMode = 0;
49660       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
49661         pWal->exclusiveMode = 1;
49662       }
49663       rc = pWal->exclusiveMode==0;
49664     }else{
49665       /* Already in locking_mode=NORMAL */
49666       rc = 0;
49667     }
49668   }else if( op>0 ){
49669     assert( pWal->exclusiveMode==0 );
49670     assert( pWal->readLock>=0 );
49671     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
49672     pWal->exclusiveMode = 1;
49673     rc = 1;
49674   }else{
49675     rc = pWal->exclusiveMode==0;
49676   }
49677   return rc;
49678 }
49679
49680 /*
49681 ** Return true if the argument is non-NULL and the WAL module is using
49682 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
49683 ** WAL module is using shared-memory, return false.
49684 */
49685 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
49686   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
49687 }
49688
49689 #ifdef SQLITE_ENABLE_ZIPVFS
49690 /*
49691 ** If the argument is not NULL, it points to a Wal object that holds a
49692 ** read-lock. This function returns the database page-size if it is known,
49693 ** or zero if it is not (or if pWal is NULL).
49694 */
49695 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
49696   assert( pWal==0 || pWal->readLock>=0 );
49697   return (pWal ? pWal->szPage : 0);
49698 }
49699 #endif
49700
49701 #endif /* #ifndef SQLITE_OMIT_WAL */
49702
49703 /************** End of wal.c *************************************************/
49704 /************** Begin file btmutex.c *****************************************/
49705 /*
49706 ** 2007 August 27
49707 **
49708 ** The author disclaims copyright to this source code.  In place of
49709 ** a legal notice, here is a blessing:
49710 **
49711 **    May you do good and not evil.
49712 **    May you find forgiveness for yourself and forgive others.
49713 **    May you share freely, never taking more than you give.
49714 **
49715 *************************************************************************
49716 **
49717 ** This file contains code used to implement mutexes on Btree objects.
49718 ** This code really belongs in btree.c.  But btree.c is getting too
49719 ** big and we want to break it down some.  This packaged seemed like
49720 ** a good breakout.
49721 */
49722 #ifndef SQLITE_OMIT_SHARED_CACHE
49723 #if SQLITE_THREADSAFE
49724
49725 /*
49726 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49727 ** set BtShared.db to the database handle associated with p and the
49728 ** p->locked boolean to true.
49729 */
49730 static void lockBtreeMutex(Btree *p){
49731   assert( p->locked==0 );
49732   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
49733   assert( sqlite3_mutex_held(p->db->mutex) );
49734
49735   sqlite3_mutex_enter(p->pBt->mutex);
49736   p->pBt->db = p->db;
49737   p->locked = 1;
49738 }
49739
49740 /*
49741 ** Release the BtShared mutex associated with B-Tree handle p and
49742 ** clear the p->locked boolean.
49743 */
49744 static void unlockBtreeMutex(Btree *p){
49745   BtShared *pBt = p->pBt;
49746   assert( p->locked==1 );
49747   assert( sqlite3_mutex_held(pBt->mutex) );
49748   assert( sqlite3_mutex_held(p->db->mutex) );
49749   assert( p->db==pBt->db );
49750
49751   sqlite3_mutex_leave(pBt->mutex);
49752   p->locked = 0;
49753 }
49754
49755 /*
49756 ** Enter a mutex on the given BTree object.
49757 **
49758 ** If the object is not sharable, then no mutex is ever required
49759 ** and this routine is a no-op.  The underlying mutex is non-recursive.
49760 ** But we keep a reference count in Btree.wantToLock so the behavior
49761 ** of this interface is recursive.
49762 **
49763 ** To avoid deadlocks, multiple Btrees are locked in the same order
49764 ** by all database connections.  The p->pNext is a list of other
49765 ** Btrees belonging to the same database connection as the p Btree
49766 ** which need to be locked after p.  If we cannot get a lock on
49767 ** p, then first unlock all of the others on p->pNext, then wait
49768 ** for the lock to become available on p, then relock all of the
49769 ** subsequent Btrees that desire a lock.
49770 */
49771 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49772   Btree *pLater;
49773
49774   /* Some basic sanity checking on the Btree.  The list of Btrees
49775   ** connected by pNext and pPrev should be in sorted order by
49776   ** Btree.pBt value. All elements of the list should belong to
49777   ** the same connection. Only shared Btrees are on the list. */
49778   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49779   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49780   assert( p->pNext==0 || p->pNext->db==p->db );
49781   assert( p->pPrev==0 || p->pPrev->db==p->db );
49782   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49783
49784   /* Check for locking consistency */
49785   assert( !p->locked || p->wantToLock>0 );
49786   assert( p->sharable || p->wantToLock==0 );
49787
49788   /* We should already hold a lock on the database connection */
49789   assert( sqlite3_mutex_held(p->db->mutex) );
49790
49791   /* Unless the database is sharable and unlocked, then BtShared.db
49792   ** should already be set correctly. */
49793   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49794
49795   if( !p->sharable ) return;
49796   p->wantToLock++;
49797   if( p->locked ) return;
49798
49799   /* In most cases, we should be able to acquire the lock we
49800   ** want without having to go throught the ascending lock
49801   ** procedure that follows.  Just be sure not to block.
49802   */
49803   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
49804     p->pBt->db = p->db;
49805     p->locked = 1;
49806     return;
49807   }
49808
49809   /* To avoid deadlock, first release all locks with a larger
49810   ** BtShared address.  Then acquire our lock.  Then reacquire
49811   ** the other BtShared locks that we used to hold in ascending
49812   ** order.
49813   */
49814   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49815     assert( pLater->sharable );
49816     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49817     assert( !pLater->locked || pLater->wantToLock>0 );
49818     if( pLater->locked ){
49819       unlockBtreeMutex(pLater);
49820     }
49821   }
49822   lockBtreeMutex(p);
49823   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49824     if( pLater->wantToLock ){
49825       lockBtreeMutex(pLater);
49826     }
49827   }
49828 }
49829
49830 /*
49831 ** Exit the recursive mutex on a Btree.
49832 */
49833 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
49834   if( p->sharable ){
49835     assert( p->wantToLock>0 );
49836     p->wantToLock--;
49837     if( p->wantToLock==0 ){
49838       unlockBtreeMutex(p);
49839     }
49840   }
49841 }
49842
49843 #ifndef NDEBUG
49844 /*
49845 ** Return true if the BtShared mutex is held on the btree, or if the
49846 ** B-Tree is not marked as sharable.
49847 **
49848 ** This routine is used only from within assert() statements.
49849 */
49850 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
49851   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49852   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49853   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
49854   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
49855
49856   return (p->sharable==0 || p->locked);
49857 }
49858 #endif
49859
49860
49861 #ifndef SQLITE_OMIT_INCRBLOB
49862 /*
49863 ** Enter and leave a mutex on a Btree given a cursor owned by that
49864 ** Btree.  These entry points are used by incremental I/O and can be
49865 ** omitted if that module is not used.
49866 */
49867 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
49868   sqlite3BtreeEnter(pCur->pBtree);
49869 }
49870 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
49871   sqlite3BtreeLeave(pCur->pBtree);
49872 }
49873 #endif /* SQLITE_OMIT_INCRBLOB */
49874
49875
49876 /*
49877 ** Enter the mutex on every Btree associated with a database
49878 ** connection.  This is needed (for example) prior to parsing
49879 ** a statement since we will be comparing table and column names
49880 ** against all schemas and we do not want those schemas being
49881 ** reset out from under us.
49882 **
49883 ** There is a corresponding leave-all procedures.
49884 **
49885 ** Enter the mutexes in accending order by BtShared pointer address
49886 ** to avoid the possibility of deadlock when two threads with
49887 ** two or more btrees in common both try to lock all their btrees
49888 ** at the same instant.
49889 */
49890 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49891   int i;
49892   Btree *p;
49893   assert( sqlite3_mutex_held(db->mutex) );
49894   for(i=0; i<db->nDb; i++){
49895     p = db->aDb[i].pBt;
49896     if( p ) sqlite3BtreeEnter(p);
49897   }
49898 }
49899 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
49900   int i;
49901   Btree *p;
49902   assert( sqlite3_mutex_held(db->mutex) );
49903   for(i=0; i<db->nDb; i++){
49904     p = db->aDb[i].pBt;
49905     if( p ) sqlite3BtreeLeave(p);
49906   }
49907 }
49908
49909 /*
49910 ** Return true if a particular Btree requires a lock.  Return FALSE if
49911 ** no lock is ever required since it is not sharable.
49912 */
49913 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
49914   return p->sharable;
49915 }
49916
49917 #ifndef NDEBUG
49918 /*
49919 ** Return true if the current thread holds the database connection
49920 ** mutex and all required BtShared mutexes.
49921 **
49922 ** This routine is used inside assert() statements only.
49923 */
49924 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
49925   int i;
49926   if( !sqlite3_mutex_held(db->mutex) ){
49927     return 0;
49928   }
49929   for(i=0; i<db->nDb; i++){
49930     Btree *p;
49931     p = db->aDb[i].pBt;
49932     if( p && p->sharable &&
49933          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
49934       return 0;
49935     }
49936   }
49937   return 1;
49938 }
49939 #endif /* NDEBUG */
49940
49941 #ifndef NDEBUG
49942 /*
49943 ** Return true if the correct mutexes are held for accessing the
49944 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
49945 ** access are:
49946 **
49947 **   (1) The mutex on db
49948 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49949 **
49950 ** If pSchema is not NULL, then iDb is computed from pSchema and
49951 ** db using sqlite3SchemaToIndex().
49952 */
49953 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
49954   Btree *p;
49955   assert( db!=0 );
49956   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
49957   assert( iDb>=0 && iDb<db->nDb );
49958   if( !sqlite3_mutex_held(db->mutex) ) return 0;
49959   if( iDb==1 ) return 1;
49960   p = db->aDb[iDb].pBt;
49961   assert( p!=0 );
49962   return p->sharable==0 || p->locked==1;
49963 }
49964 #endif /* NDEBUG */
49965
49966 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
49967 /*
49968 ** The following are special cases for mutex enter routines for use
49969 ** in single threaded applications that use shared cache.  Except for
49970 ** these two routines, all mutex operations are no-ops in that case and
49971 ** are null #defines in btree.h.
49972 **
49973 ** If shared cache is disabled, then all btree mutex routines, including
49974 ** the ones below, are no-ops and are null #defines in btree.h.
49975 */
49976
49977 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49978   p->pBt->db = p->db;
49979 }
49980 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49981   int i;
49982   for(i=0; i<db->nDb; i++){
49983     Btree *p = db->aDb[i].pBt;
49984     if( p ){
49985       p->pBt->db = p->db;
49986     }
49987   }
49988 }
49989 #endif /* if SQLITE_THREADSAFE */
49990 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
49991
49992 /************** End of btmutex.c *********************************************/
49993 /************** Begin file btree.c *******************************************/
49994 /*
49995 ** 2004 April 6
49996 **
49997 ** The author disclaims copyright to this source code.  In place of
49998 ** a legal notice, here is a blessing:
49999 **
50000 **    May you do good and not evil.
50001 **    May you find forgiveness for yourself and forgive others.
50002 **    May you share freely, never taking more than you give.
50003 **
50004 *************************************************************************
50005 ** This file implements a external (disk-based) database using BTrees.
50006 ** See the header comment on "btreeInt.h" for additional information.
50007 ** Including a description of file format and an overview of operation.
50008 */
50009
50010 /*
50011 ** The header string that appears at the beginning of every
50012 ** SQLite database.
50013 */
50014 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
50015
50016 /*
50017 ** Set this global variable to 1 to enable tracing using the TRACE
50018 ** macro.
50019 */
50020 #if 0
50021 int sqlite3BtreeTrace=1;  /* True to enable tracing */
50022 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
50023 #else
50024 # define TRACE(X)
50025 #endif
50026
50027 /*
50028 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
50029 ** But if the value is zero, make it 65536.
50030 **
50031 ** This routine is used to extract the "offset to cell content area" value
50032 ** from the header of a btree page.  If the page size is 65536 and the page
50033 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
50034 ** This routine makes the necessary adjustment to 65536.
50035 */
50036 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
50037
50038 #ifndef SQLITE_OMIT_SHARED_CACHE
50039 /*
50040 ** A list of BtShared objects that are eligible for participation
50041 ** in shared cache.  This variable has file scope during normal builds,
50042 ** but the test harness needs to access it so we make it global for
50043 ** test builds.
50044 **
50045 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
50046 */
50047 #ifdef SQLITE_TEST
50048 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
50049 #else
50050 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
50051 #endif
50052 #endif /* SQLITE_OMIT_SHARED_CACHE */
50053
50054 #ifndef SQLITE_OMIT_SHARED_CACHE
50055 /*
50056 ** Enable or disable the shared pager and schema features.
50057 **
50058 ** This routine has no effect on existing database connections.
50059 ** The shared cache setting effects only future calls to
50060 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
50061 */
50062 SQLITE_API int sqlite3_enable_shared_cache(int enable){
50063   sqlite3GlobalConfig.sharedCacheEnabled = enable;
50064   return SQLITE_OK;
50065 }
50066 #endif
50067
50068
50069
50070 #ifdef SQLITE_OMIT_SHARED_CACHE
50071   /*
50072   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
50073   ** and clearAllSharedCacheTableLocks()
50074   ** manipulate entries in the BtShared.pLock linked list used to store
50075   ** shared-cache table level locks. If the library is compiled with the
50076   ** shared-cache feature disabled, then there is only ever one user
50077   ** of each BtShared structure and so this locking is not necessary.
50078   ** So define the lock related functions as no-ops.
50079   */
50080   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
50081   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
50082   #define clearAllSharedCacheTableLocks(a)
50083   #define downgradeAllSharedCacheTableLocks(a)
50084   #define hasSharedCacheTableLock(a,b,c,d) 1
50085   #define hasReadConflicts(a, b) 0
50086 #endif
50087
50088 #ifndef SQLITE_OMIT_SHARED_CACHE
50089
50090 #ifdef SQLITE_DEBUG
50091 /*
50092 **** This function is only used as part of an assert() statement. ***
50093 **
50094 ** Check to see if pBtree holds the required locks to read or write to the
50095 ** table with root page iRoot.   Return 1 if it does and 0 if not.
50096 **
50097 ** For example, when writing to a table with root-page iRoot via
50098 ** Btree connection pBtree:
50099 **
50100 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
50101 **
50102 ** When writing to an index that resides in a sharable database, the
50103 ** caller should have first obtained a lock specifying the root page of
50104 ** the corresponding table. This makes things a bit more complicated,
50105 ** as this module treats each table as a separate structure. To determine
50106 ** the table corresponding to the index being written, this
50107 ** function has to search through the database schema.
50108 **
50109 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
50110 ** hold a write-lock on the schema table (root page 1). This is also
50111 ** acceptable.
50112 */
50113 static int hasSharedCacheTableLock(
50114   Btree *pBtree,         /* Handle that must hold lock */
50115   Pgno iRoot,            /* Root page of b-tree */
50116   int isIndex,           /* True if iRoot is the root of an index b-tree */
50117   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
50118 ){
50119   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
50120   Pgno iTab = 0;
50121   BtLock *pLock;
50122
50123   /* If this database is not shareable, or if the client is reading
50124   ** and has the read-uncommitted flag set, then no lock is required.
50125   ** Return true immediately.
50126   */
50127   if( (pBtree->sharable==0)
50128    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
50129   ){
50130     return 1;
50131   }
50132
50133   /* If the client is reading  or writing an index and the schema is
50134   ** not loaded, then it is too difficult to actually check to see if
50135   ** the correct locks are held.  So do not bother - just return true.
50136   ** This case does not come up very often anyhow.
50137   */
50138   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
50139     return 1;
50140   }
50141
50142   /* Figure out the root-page that the lock should be held on. For table
50143   ** b-trees, this is just the root page of the b-tree being read or
50144   ** written. For index b-trees, it is the root page of the associated
50145   ** table.  */
50146   if( isIndex ){
50147     HashElem *p;
50148     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
50149       Index *pIdx = (Index *)sqliteHashData(p);
50150       if( pIdx->tnum==(int)iRoot ){
50151         iTab = pIdx->pTable->tnum;
50152       }
50153     }
50154   }else{
50155     iTab = iRoot;
50156   }
50157
50158   /* Search for the required lock. Either a write-lock on root-page iTab, a
50159   ** write-lock on the schema table, or (if the client is reading) a
50160   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
50161   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
50162     if( pLock->pBtree==pBtree
50163      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
50164      && pLock->eLock>=eLockType
50165     ){
50166       return 1;
50167     }
50168   }
50169
50170   /* Failed to find the required lock. */
50171   return 0;
50172 }
50173 #endif /* SQLITE_DEBUG */
50174
50175 #ifdef SQLITE_DEBUG
50176 /*
50177 **** This function may be used as part of assert() statements only. ****
50178 **
50179 ** Return true if it would be illegal for pBtree to write into the
50180 ** table or index rooted at iRoot because other shared connections are
50181 ** simultaneously reading that same table or index.
50182 **
50183 ** It is illegal for pBtree to write if some other Btree object that
50184 ** shares the same BtShared object is currently reading or writing
50185 ** the iRoot table.  Except, if the other Btree object has the
50186 ** read-uncommitted flag set, then it is OK for the other object to
50187 ** have a read cursor.
50188 **
50189 ** For example, before writing to any part of the table or index
50190 ** rooted at page iRoot, one should call:
50191 **
50192 **    assert( !hasReadConflicts(pBtree, iRoot) );
50193 */
50194 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
50195   BtCursor *p;
50196   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50197     if( p->pgnoRoot==iRoot
50198      && p->pBtree!=pBtree
50199      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
50200     ){
50201       return 1;
50202     }
50203   }
50204   return 0;
50205 }
50206 #endif    /* #ifdef SQLITE_DEBUG */
50207
50208 /*
50209 ** Query to see if Btree handle p may obtain a lock of type eLock
50210 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
50211 ** SQLITE_OK if the lock may be obtained (by calling
50212 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
50213 */
50214 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
50215   BtShared *pBt = p->pBt;
50216   BtLock *pIter;
50217
50218   assert( sqlite3BtreeHoldsMutex(p) );
50219   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
50220   assert( p->db!=0 );
50221   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
50222
50223   /* If requesting a write-lock, then the Btree must have an open write
50224   ** transaction on this file. And, obviously, for this to be so there
50225   ** must be an open write transaction on the file itself.
50226   */
50227   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
50228   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
50229
50230   /* This routine is a no-op if the shared-cache is not enabled */
50231   if( !p->sharable ){
50232     return SQLITE_OK;
50233   }
50234
50235   /* If some other connection is holding an exclusive lock, the
50236   ** requested lock may not be obtained.
50237   */
50238   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
50239     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
50240     return SQLITE_LOCKED_SHAREDCACHE;
50241   }
50242
50243   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50244     /* The condition (pIter->eLock!=eLock) in the following if(...)
50245     ** statement is a simplification of:
50246     **
50247     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
50248     **
50249     ** since we know that if eLock==WRITE_LOCK, then no other connection
50250     ** may hold a WRITE_LOCK on any table in this file (since there can
50251     ** only be a single writer).
50252     */
50253     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
50254     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
50255     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
50256       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
50257       if( eLock==WRITE_LOCK ){
50258         assert( p==pBt->pWriter );
50259         pBt->btsFlags |= BTS_PENDING;
50260       }
50261       return SQLITE_LOCKED_SHAREDCACHE;
50262     }
50263   }
50264   return SQLITE_OK;
50265 }
50266 #endif /* !SQLITE_OMIT_SHARED_CACHE */
50267
50268 #ifndef SQLITE_OMIT_SHARED_CACHE
50269 /*
50270 ** Add a lock on the table with root-page iTable to the shared-btree used
50271 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
50272 ** WRITE_LOCK.
50273 **
50274 ** This function assumes the following:
50275 **
50276 **   (a) The specified Btree object p is connected to a sharable
50277 **       database (one with the BtShared.sharable flag set), and
50278 **
50279 **   (b) No other Btree objects hold a lock that conflicts
50280 **       with the requested lock (i.e. querySharedCacheTableLock() has
50281 **       already been called and returned SQLITE_OK).
50282 **
50283 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
50284 ** is returned if a malloc attempt fails.
50285 */
50286 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
50287   BtShared *pBt = p->pBt;
50288   BtLock *pLock = 0;
50289   BtLock *pIter;
50290
50291   assert( sqlite3BtreeHoldsMutex(p) );
50292   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
50293   assert( p->db!=0 );
50294
50295   /* A connection with the read-uncommitted flag set will never try to
50296   ** obtain a read-lock using this function. The only read-lock obtained
50297   ** by a connection in read-uncommitted mode is on the sqlite_master
50298   ** table, and that lock is obtained in BtreeBeginTrans().  */
50299   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
50300
50301   /* This function should only be called on a sharable b-tree after it
50302   ** has been determined that no other b-tree holds a conflicting lock.  */
50303   assert( p->sharable );
50304   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
50305
50306   /* First search the list for an existing lock on this table. */
50307   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50308     if( pIter->iTable==iTable && pIter->pBtree==p ){
50309       pLock = pIter;
50310       break;
50311     }
50312   }
50313
50314   /* If the above search did not find a BtLock struct associating Btree p
50315   ** with table iTable, allocate one and link it into the list.
50316   */
50317   if( !pLock ){
50318     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
50319     if( !pLock ){
50320       return SQLITE_NOMEM;
50321     }
50322     pLock->iTable = iTable;
50323     pLock->pBtree = p;
50324     pLock->pNext = pBt->pLock;
50325     pBt->pLock = pLock;
50326   }
50327
50328   /* Set the BtLock.eLock variable to the maximum of the current lock
50329   ** and the requested lock. This means if a write-lock was already held
50330   ** and a read-lock requested, we don't incorrectly downgrade the lock.
50331   */
50332   assert( WRITE_LOCK>READ_LOCK );
50333   if( eLock>pLock->eLock ){
50334     pLock->eLock = eLock;
50335   }
50336
50337   return SQLITE_OK;
50338 }
50339 #endif /* !SQLITE_OMIT_SHARED_CACHE */
50340
50341 #ifndef SQLITE_OMIT_SHARED_CACHE
50342 /*
50343 ** Release all the table locks (locks obtained via calls to
50344 ** the setSharedCacheTableLock() procedure) held by Btree object p.
50345 **
50346 ** This function assumes that Btree p has an open read or write
50347 ** transaction. If it does not, then the BTS_PENDING flag
50348 ** may be incorrectly cleared.
50349 */
50350 static void clearAllSharedCacheTableLocks(Btree *p){
50351   BtShared *pBt = p->pBt;
50352   BtLock **ppIter = &pBt->pLock;
50353
50354   assert( sqlite3BtreeHoldsMutex(p) );
50355   assert( p->sharable || 0==*ppIter );
50356   assert( p->inTrans>0 );
50357
50358   while( *ppIter ){
50359     BtLock *pLock = *ppIter;
50360     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
50361     assert( pLock->pBtree->inTrans>=pLock->eLock );
50362     if( pLock->pBtree==p ){
50363       *ppIter = pLock->pNext;
50364       assert( pLock->iTable!=1 || pLock==&p->lock );
50365       if( pLock->iTable!=1 ){
50366         sqlite3_free(pLock);
50367       }
50368     }else{
50369       ppIter = &pLock->pNext;
50370     }
50371   }
50372
50373   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
50374   if( pBt->pWriter==p ){
50375     pBt->pWriter = 0;
50376     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
50377   }else if( pBt->nTransaction==2 ){
50378     /* This function is called when Btree p is concluding its
50379     ** transaction. If there currently exists a writer, and p is not
50380     ** that writer, then the number of locks held by connections other
50381     ** than the writer must be about to drop to zero. In this case
50382     ** set the BTS_PENDING flag to 0.
50383     **
50384     ** If there is not currently a writer, then BTS_PENDING must
50385     ** be zero already. So this next line is harmless in that case.
50386     */
50387     pBt->btsFlags &= ~BTS_PENDING;
50388   }
50389 }
50390
50391 /*
50392 ** This function changes all write-locks held by Btree p into read-locks.
50393 */
50394 static void downgradeAllSharedCacheTableLocks(Btree *p){
50395   BtShared *pBt = p->pBt;
50396   if( pBt->pWriter==p ){
50397     BtLock *pLock;
50398     pBt->pWriter = 0;
50399     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
50400     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
50401       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
50402       pLock->eLock = READ_LOCK;
50403     }
50404   }
50405 }
50406
50407 #endif /* SQLITE_OMIT_SHARED_CACHE */
50408
50409 static void releasePage(MemPage *pPage);  /* Forward reference */
50410
50411 /*
50412 ***** This routine is used inside of assert() only ****
50413 **
50414 ** Verify that the cursor holds the mutex on its BtShared
50415 */
50416 #ifdef SQLITE_DEBUG
50417 static int cursorHoldsMutex(BtCursor *p){
50418   return sqlite3_mutex_held(p->pBt->mutex);
50419 }
50420 #endif
50421
50422
50423 #ifndef SQLITE_OMIT_INCRBLOB
50424 /*
50425 ** Invalidate the overflow page-list cache for cursor pCur, if any.
50426 */
50427 static void invalidateOverflowCache(BtCursor *pCur){
50428   assert( cursorHoldsMutex(pCur) );
50429   sqlite3_free(pCur->aOverflow);
50430   pCur->aOverflow = 0;
50431 }
50432
50433 /*
50434 ** Invalidate the overflow page-list cache for all cursors opened
50435 ** on the shared btree structure pBt.
50436 */
50437 static void invalidateAllOverflowCache(BtShared *pBt){
50438   BtCursor *p;
50439   assert( sqlite3_mutex_held(pBt->mutex) );
50440   for(p=pBt->pCursor; p; p=p->pNext){
50441     invalidateOverflowCache(p);
50442   }
50443 }
50444
50445 /*
50446 ** This function is called before modifying the contents of a table
50447 ** to invalidate any incrblob cursors that are open on the
50448 ** row or one of the rows being modified.
50449 **
50450 ** If argument isClearTable is true, then the entire contents of the
50451 ** table is about to be deleted. In this case invalidate all incrblob
50452 ** cursors open on any row within the table with root-page pgnoRoot.
50453 **
50454 ** Otherwise, if argument isClearTable is false, then the row with
50455 ** rowid iRow is being replaced or deleted. In this case invalidate
50456 ** only those incrblob cursors open on that specific row.
50457 */
50458 static void invalidateIncrblobCursors(
50459   Btree *pBtree,          /* The database file to check */
50460   i64 iRow,               /* The rowid that might be changing */
50461   int isClearTable        /* True if all rows are being deleted */
50462 ){
50463   BtCursor *p;
50464   BtShared *pBt = pBtree->pBt;
50465   assert( sqlite3BtreeHoldsMutex(pBtree) );
50466   for(p=pBt->pCursor; p; p=p->pNext){
50467     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
50468       p->eState = CURSOR_INVALID;
50469     }
50470   }
50471 }
50472
50473 #else
50474   /* Stub functions when INCRBLOB is omitted */
50475   #define invalidateOverflowCache(x)
50476   #define invalidateAllOverflowCache(x)
50477   #define invalidateIncrblobCursors(x,y,z)
50478 #endif /* SQLITE_OMIT_INCRBLOB */
50479
50480 /*
50481 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
50482 ** when a page that previously contained data becomes a free-list leaf
50483 ** page.
50484 **
50485 ** The BtShared.pHasContent bitvec exists to work around an obscure
50486 ** bug caused by the interaction of two useful IO optimizations surrounding
50487 ** free-list leaf pages:
50488 **
50489 **   1) When all data is deleted from a page and the page becomes
50490 **      a free-list leaf page, the page is not written to the database
50491 **      (as free-list leaf pages contain no meaningful data). Sometimes
50492 **      such a page is not even journalled (as it will not be modified,
50493 **      why bother journalling it?).
50494 **
50495 **   2) When a free-list leaf page is reused, its content is not read
50496 **      from the database or written to the journal file (why should it
50497 **      be, if it is not at all meaningful?).
50498 **
50499 ** By themselves, these optimizations work fine and provide a handy
50500 ** performance boost to bulk delete or insert operations. However, if
50501 ** a page is moved to the free-list and then reused within the same
50502 ** transaction, a problem comes up. If the page is not journalled when
50503 ** it is moved to the free-list and it is also not journalled when it
50504 ** is extracted from the free-list and reused, then the original data
50505 ** may be lost. In the event of a rollback, it may not be possible
50506 ** to restore the database to its original configuration.
50507 **
50508 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
50509 ** moved to become a free-list leaf page, the corresponding bit is
50510 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
50511 ** optimization 2 above is omitted if the corresponding bit is already
50512 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
50513 ** at the end of every transaction.
50514 */
50515 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
50516   int rc = SQLITE_OK;
50517   if( !pBt->pHasContent ){
50518     assert( pgno<=pBt->nPage );
50519     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
50520     if( !pBt->pHasContent ){
50521       rc = SQLITE_NOMEM;
50522     }
50523   }
50524   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
50525     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
50526   }
50527   return rc;
50528 }
50529
50530 /*
50531 ** Query the BtShared.pHasContent vector.
50532 **
50533 ** This function is called when a free-list leaf page is removed from the
50534 ** free-list for reuse. It returns false if it is safe to retrieve the
50535 ** page from the pager layer with the 'no-content' flag set. True otherwise.
50536 */
50537 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
50538   Bitvec *p = pBt->pHasContent;
50539   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
50540 }
50541
50542 /*
50543 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
50544 ** invoked at the conclusion of each write-transaction.
50545 */
50546 static void btreeClearHasContent(BtShared *pBt){
50547   sqlite3BitvecDestroy(pBt->pHasContent);
50548   pBt->pHasContent = 0;
50549 }
50550
50551 /*
50552 ** Save the current cursor position in the variables BtCursor.nKey
50553 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
50554 **
50555 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
50556 ** prior to calling this routine.
50557 */
50558 static int saveCursorPosition(BtCursor *pCur){
50559   int rc;
50560
50561   assert( CURSOR_VALID==pCur->eState );
50562   assert( 0==pCur->pKey );
50563   assert( cursorHoldsMutex(pCur) );
50564
50565   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
50566   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
50567
50568   /* If this is an intKey table, then the above call to BtreeKeySize()
50569   ** stores the integer key in pCur->nKey. In this case this value is
50570   ** all that is required. Otherwise, if pCur is not open on an intKey
50571   ** table, then malloc space for and store the pCur->nKey bytes of key
50572   ** data.
50573   */
50574   if( 0==pCur->apPage[0]->intKey ){
50575     void *pKey = sqlite3Malloc( (int)pCur->nKey );
50576     if( pKey ){
50577       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
50578       if( rc==SQLITE_OK ){
50579         pCur->pKey = pKey;
50580       }else{
50581         sqlite3_free(pKey);
50582       }
50583     }else{
50584       rc = SQLITE_NOMEM;
50585     }
50586   }
50587   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
50588
50589   if( rc==SQLITE_OK ){
50590     int i;
50591     for(i=0; i<=pCur->iPage; i++){
50592       releasePage(pCur->apPage[i]);
50593       pCur->apPage[i] = 0;
50594     }
50595     pCur->iPage = -1;
50596     pCur->eState = CURSOR_REQUIRESEEK;
50597   }
50598
50599   invalidateOverflowCache(pCur);
50600   return rc;
50601 }
50602
50603 /*
50604 ** Save the positions of all cursors (except pExcept) that are open on
50605 ** the table  with root-page iRoot. Usually, this is called just before cursor
50606 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
50607 */
50608 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
50609   BtCursor *p;
50610   assert( sqlite3_mutex_held(pBt->mutex) );
50611   assert( pExcept==0 || pExcept->pBt==pBt );
50612   for(p=pBt->pCursor; p; p=p->pNext){
50613     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
50614         p->eState==CURSOR_VALID ){
50615       int rc = saveCursorPosition(p);
50616       if( SQLITE_OK!=rc ){
50617         return rc;
50618       }
50619     }
50620   }
50621   return SQLITE_OK;
50622 }
50623
50624 /*
50625 ** Clear the current cursor position.
50626 */
50627 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
50628   assert( cursorHoldsMutex(pCur) );
50629   sqlite3_free(pCur->pKey);
50630   pCur->pKey = 0;
50631   pCur->eState = CURSOR_INVALID;
50632 }
50633
50634 /*
50635 ** In this version of BtreeMoveto, pKey is a packed index record
50636 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
50637 ** record and then call BtreeMovetoUnpacked() to do the work.
50638 */
50639 static int btreeMoveto(
50640   BtCursor *pCur,     /* Cursor open on the btree to be searched */
50641   const void *pKey,   /* Packed key if the btree is an index */
50642   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50643   int bias,           /* Bias search to the high end */
50644   int *pRes           /* Write search results here */
50645 ){
50646   int rc;                    /* Status code */
50647   UnpackedRecord *pIdxKey;   /* Unpacked index key */
50648   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50649   char *pFree = 0;
50650
50651   if( pKey ){
50652     assert( nKey==(i64)(int)nKey );
50653     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
50654         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50655     );
50656     if( pIdxKey==0 ) return SQLITE_NOMEM;
50657     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50658   }else{
50659     pIdxKey = 0;
50660   }
50661   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50662   if( pFree ){
50663     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
50664   }
50665   return rc;
50666 }
50667
50668 /*
50669 ** Restore the cursor to the position it was in (or as close to as possible)
50670 ** when saveCursorPosition() was called. Note that this call deletes the
50671 ** saved position info stored by saveCursorPosition(), so there can be
50672 ** at most one effective restoreCursorPosition() call after each
50673 ** saveCursorPosition().
50674 */
50675 static int btreeRestoreCursorPosition(BtCursor *pCur){
50676   int rc;
50677   assert( cursorHoldsMutex(pCur) );
50678   assert( pCur->eState>=CURSOR_REQUIRESEEK );
50679   if( pCur->eState==CURSOR_FAULT ){
50680     return pCur->skipNext;
50681   }
50682   pCur->eState = CURSOR_INVALID;
50683   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50684   if( rc==SQLITE_OK ){
50685     sqlite3_free(pCur->pKey);
50686     pCur->pKey = 0;
50687     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50688   }
50689   return rc;
50690 }
50691
50692 #define restoreCursorPosition(p) \
50693   (p->eState>=CURSOR_REQUIRESEEK ? \
50694          btreeRestoreCursorPosition(p) : \
50695          SQLITE_OK)
50696
50697 /*
50698 ** Determine whether or not a cursor has moved from the position it
50699 ** was last placed at.  Cursors can move when the row they are pointing
50700 ** at is deleted out from under them.
50701 **
50702 ** This routine returns an error code if something goes wrong.  The
50703 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50704 */
50705 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50706   int rc;
50707
50708   rc = restoreCursorPosition(pCur);
50709   if( rc ){
50710     *pHasMoved = 1;
50711     return rc;
50712   }
50713   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50714     *pHasMoved = 1;
50715   }else{
50716     *pHasMoved = 0;
50717   }
50718   return SQLITE_OK;
50719 }
50720
50721 #ifndef SQLITE_OMIT_AUTOVACUUM
50722 /*
50723 ** Given a page number of a regular database page, return the page
50724 ** number for the pointer-map page that contains the entry for the
50725 ** input page number.
50726 **
50727 ** Return 0 (not a valid page) for pgno==1 since there is
50728 ** no pointer map associated with page 1.  The integrity_check logic
50729 ** requires that ptrmapPageno(*,1)!=1.
50730 */
50731 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50732   int nPagesPerMapPage;
50733   Pgno iPtrMap, ret;
50734   assert( sqlite3_mutex_held(pBt->mutex) );
50735   if( pgno<2 ) return 0;
50736   nPagesPerMapPage = (pBt->usableSize/5)+1;
50737   iPtrMap = (pgno-2)/nPagesPerMapPage;
50738   ret = (iPtrMap*nPagesPerMapPage) + 2;
50739   if( ret==PENDING_BYTE_PAGE(pBt) ){
50740     ret++;
50741   }
50742   return ret;
50743 }
50744
50745 /*
50746 ** Write an entry into the pointer map.
50747 **
50748 ** This routine updates the pointer map entry for page number 'key'
50749 ** so that it maps to type 'eType' and parent page number 'pgno'.
50750 **
50751 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
50752 ** a no-op.  If an error occurs, the appropriate error code is written
50753 ** into *pRC.
50754 */
50755 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50756   DbPage *pDbPage;  /* The pointer map page */
50757   u8 *pPtrmap;      /* The pointer map data */
50758   Pgno iPtrmap;     /* The pointer map page number */
50759   int offset;       /* Offset in pointer map page */
50760   int rc;           /* Return code from subfunctions */
50761
50762   if( *pRC ) return;
50763
50764   assert( sqlite3_mutex_held(pBt->mutex) );
50765   /* The master-journal page number must never be used as a pointer map page */
50766   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50767
50768   assert( pBt->autoVacuum );
50769   if( key==0 ){
50770     *pRC = SQLITE_CORRUPT_BKPT;
50771     return;
50772   }
50773   iPtrmap = PTRMAP_PAGENO(pBt, key);
50774   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50775   if( rc!=SQLITE_OK ){
50776     *pRC = rc;
50777     return;
50778   }
50779   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50780   if( offset<0 ){
50781     *pRC = SQLITE_CORRUPT_BKPT;
50782     goto ptrmap_exit;
50783   }
50784   assert( offset <= (int)pBt->usableSize-5 );
50785   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50786
50787   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50788     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50789     *pRC= rc = sqlite3PagerWrite(pDbPage);
50790     if( rc==SQLITE_OK ){
50791       pPtrmap[offset] = eType;
50792       put4byte(&pPtrmap[offset+1], parent);
50793     }
50794   }
50795
50796 ptrmap_exit:
50797   sqlite3PagerUnref(pDbPage);
50798 }
50799
50800 /*
50801 ** Read an entry from the pointer map.
50802 **
50803 ** This routine retrieves the pointer map entry for page 'key', writing
50804 ** the type and parent page number to *pEType and *pPgno respectively.
50805 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
50806 */
50807 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50808   DbPage *pDbPage;   /* The pointer map page */
50809   int iPtrmap;       /* Pointer map page index */
50810   u8 *pPtrmap;       /* Pointer map page data */
50811   int offset;        /* Offset of entry in pointer map */
50812   int rc;
50813
50814   assert( sqlite3_mutex_held(pBt->mutex) );
50815
50816   iPtrmap = PTRMAP_PAGENO(pBt, key);
50817   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50818   if( rc!=0 ){
50819     return rc;
50820   }
50821   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50822
50823   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50824   if( offset<0 ){
50825     sqlite3PagerUnref(pDbPage);
50826     return SQLITE_CORRUPT_BKPT;
50827   }
50828   assert( offset <= (int)pBt->usableSize-5 );
50829   assert( pEType!=0 );
50830   *pEType = pPtrmap[offset];
50831   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50832
50833   sqlite3PagerUnref(pDbPage);
50834   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
50835   return SQLITE_OK;
50836 }
50837
50838 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
50839   #define ptrmapPut(w,x,y,z,rc)
50840   #define ptrmapGet(w,x,y,z) SQLITE_OK
50841   #define ptrmapPutOvflPtr(x, y, rc)
50842 #endif
50843
50844 /*
50845 ** Given a btree page and a cell index (0 means the first cell on
50846 ** the page, 1 means the second cell, and so forth) return a pointer
50847 ** to the cell content.
50848 **
50849 ** This routine works only for pages that do not contain overflow cells.
50850 */
50851 #define findCell(P,I) \
50852   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
50853 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50854
50855
50856 /*
50857 ** This a more complex version of findCell() that works for
50858 ** pages that do contain overflow cells.
50859 */
50860 static u8 *findOverflowCell(MemPage *pPage, int iCell){
50861   int i;
50862   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50863   for(i=pPage->nOverflow-1; i>=0; i--){
50864     int k;
50865     k = pPage->aiOvfl[i];
50866     if( k<=iCell ){
50867       if( k==iCell ){
50868         return pPage->apOvfl[i];
50869       }
50870       iCell--;
50871     }
50872   }
50873   return findCell(pPage, iCell);
50874 }
50875
50876 /*
50877 ** Parse a cell content block and fill in the CellInfo structure.  There
50878 ** are two versions of this function.  btreeParseCell() takes a
50879 ** cell index as the second argument and btreeParseCellPtr()
50880 ** takes a pointer to the body of the cell as its second argument.
50881 **
50882 ** Within this file, the parseCell() macro can be called instead of
50883 ** btreeParseCellPtr(). Using some compilers, this will be faster.
50884 */
50885 static void btreeParseCellPtr(
50886   MemPage *pPage,         /* Page containing the cell */
50887   u8 *pCell,              /* Pointer to the cell text. */
50888   CellInfo *pInfo         /* Fill in this structure */
50889 ){
50890   u16 n;                  /* Number bytes in cell content header */
50891   u32 nPayload;           /* Number of bytes of cell payload */
50892
50893   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50894
50895   pInfo->pCell = pCell;
50896   assert( pPage->leaf==0 || pPage->leaf==1 );
50897   n = pPage->childPtrSize;
50898   assert( n==4-4*pPage->leaf );
50899   if( pPage->intKey ){
50900     if( pPage->hasData ){
50901       n += getVarint32(&pCell[n], nPayload);
50902     }else{
50903       nPayload = 0;
50904     }
50905     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50906     pInfo->nData = nPayload;
50907   }else{
50908     pInfo->nData = 0;
50909     n += getVarint32(&pCell[n], nPayload);
50910     pInfo->nKey = nPayload;
50911   }
50912   pInfo->nPayload = nPayload;
50913   pInfo->nHeader = n;
50914   testcase( nPayload==pPage->maxLocal );
50915   testcase( nPayload==pPage->maxLocal+1 );
50916   if( likely(nPayload<=pPage->maxLocal) ){
50917     /* This is the (easy) common case where the entire payload fits
50918     ** on the local page.  No overflow is required.
50919     */
50920     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50921     pInfo->nLocal = (u16)nPayload;
50922     pInfo->iOverflow = 0;
50923   }else{
50924     /* If the payload will not fit completely on the local page, we have
50925     ** to decide how much to store locally and how much to spill onto
50926     ** overflow pages.  The strategy is to minimize the amount of unused
50927     ** space on overflow pages while keeping the amount of local storage
50928     ** in between minLocal and maxLocal.
50929     **
50930     ** Warning:  changing the way overflow payload is distributed in any
50931     ** way will result in an incompatible file format.
50932     */
50933     int minLocal;  /* Minimum amount of payload held locally */
50934     int maxLocal;  /* Maximum amount of payload held locally */
50935     int surplus;   /* Overflow payload available for local storage */
50936
50937     minLocal = pPage->minLocal;
50938     maxLocal = pPage->maxLocal;
50939     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50940     testcase( surplus==maxLocal );
50941     testcase( surplus==maxLocal+1 );
50942     if( surplus <= maxLocal ){
50943       pInfo->nLocal = (u16)surplus;
50944     }else{
50945       pInfo->nLocal = (u16)minLocal;
50946     }
50947     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50948     pInfo->nSize = pInfo->iOverflow + 4;
50949   }
50950 }
50951 #define parseCell(pPage, iCell, pInfo) \
50952   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50953 static void btreeParseCell(
50954   MemPage *pPage,         /* Page containing the cell */
50955   int iCell,              /* The cell index.  First cell is 0 */
50956   CellInfo *pInfo         /* Fill in this structure */
50957 ){
50958   parseCell(pPage, iCell, pInfo);
50959 }
50960
50961 /*
50962 ** Compute the total number of bytes that a Cell needs in the cell
50963 ** data area of the btree-page.  The return number includes the cell
50964 ** data header and the local payload, but not any overflow page or
50965 ** the space used by the cell pointer.
50966 */
50967 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50968   u8 *pIter = &pCell[pPage->childPtrSize];
50969   u32 nSize;
50970
50971 #ifdef SQLITE_DEBUG
50972   /* The value returned by this function should always be the same as
50973   ** the (CellInfo.nSize) value found by doing a full parse of the
50974   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
50975   ** this function verifies that this invariant is not violated. */
50976   CellInfo debuginfo;
50977   btreeParseCellPtr(pPage, pCell, &debuginfo);
50978 #endif
50979
50980   if( pPage->intKey ){
50981     u8 *pEnd;
50982     if( pPage->hasData ){
50983       pIter += getVarint32(pIter, nSize);
50984     }else{
50985       nSize = 0;
50986     }
50987
50988     /* pIter now points at the 64-bit integer key value, a variable length
50989     ** integer. The following block moves pIter to point at the first byte
50990     ** past the end of the key value. */
50991     pEnd = &pIter[9];
50992     while( (*pIter++)&0x80 && pIter<pEnd );
50993   }else{
50994     pIter += getVarint32(pIter, nSize);
50995   }
50996
50997   testcase( nSize==pPage->maxLocal );
50998   testcase( nSize==pPage->maxLocal+1 );
50999   if( nSize>pPage->maxLocal ){
51000     int minLocal = pPage->minLocal;
51001     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
51002     testcase( nSize==pPage->maxLocal );
51003     testcase( nSize==pPage->maxLocal+1 );
51004     if( nSize>pPage->maxLocal ){
51005       nSize = minLocal;
51006     }
51007     nSize += 4;
51008   }
51009   nSize += (u32)(pIter - pCell);
51010
51011   /* The minimum size of any cell is 4 bytes. */
51012   if( nSize<4 ){
51013     nSize = 4;
51014   }
51015
51016   assert( nSize==debuginfo.nSize );
51017   return (u16)nSize;
51018 }
51019
51020 #ifdef SQLITE_DEBUG
51021 /* This variation on cellSizePtr() is used inside of assert() statements
51022 ** only. */
51023 static u16 cellSize(MemPage *pPage, int iCell){
51024   return cellSizePtr(pPage, findCell(pPage, iCell));
51025 }
51026 #endif
51027
51028 #ifndef SQLITE_OMIT_AUTOVACUUM
51029 /*
51030 ** If the cell pCell, part of page pPage contains a pointer
51031 ** to an overflow page, insert an entry into the pointer-map
51032 ** for the overflow page.
51033 */
51034 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
51035   CellInfo info;
51036   if( *pRC ) return;
51037   assert( pCell!=0 );
51038   btreeParseCellPtr(pPage, pCell, &info);
51039   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
51040   if( info.iOverflow ){
51041     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
51042     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
51043   }
51044 }
51045 #endif
51046
51047
51048 /*
51049 ** Defragment the page given.  All Cells are moved to the
51050 ** end of the page and all free space is collected into one
51051 ** big FreeBlk that occurs in between the header and cell
51052 ** pointer array and the cell content area.
51053 */
51054 static int defragmentPage(MemPage *pPage){
51055   int i;                     /* Loop counter */
51056   int pc;                    /* Address of a i-th cell */
51057   int hdr;                   /* Offset to the page header */
51058   int size;                  /* Size of a cell */
51059   int usableSize;            /* Number of usable bytes on a page */
51060   int cellOffset;            /* Offset to the cell pointer array */
51061   int cbrk;                  /* Offset to the cell content area */
51062   int nCell;                 /* Number of cells on the page */
51063   unsigned char *data;       /* The page data */
51064   unsigned char *temp;       /* Temp area for cell content */
51065   int iCellFirst;            /* First allowable cell index */
51066   int iCellLast;             /* Last possible cell index */
51067
51068
51069   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51070   assert( pPage->pBt!=0 );
51071   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
51072   assert( pPage->nOverflow==0 );
51073   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51074   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
51075   data = pPage->aData;
51076   hdr = pPage->hdrOffset;
51077   cellOffset = pPage->cellOffset;
51078   nCell = pPage->nCell;
51079   assert( nCell==get2byte(&data[hdr+3]) );
51080   usableSize = pPage->pBt->usableSize;
51081   cbrk = get2byte(&data[hdr+5]);
51082   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
51083   cbrk = usableSize;
51084   iCellFirst = cellOffset + 2*nCell;
51085   iCellLast = usableSize - 4;
51086   for(i=0; i<nCell; i++){
51087     u8 *pAddr;     /* The i-th cell pointer */
51088     pAddr = &data[cellOffset + i*2];
51089     pc = get2byte(pAddr);
51090     testcase( pc==iCellFirst );
51091     testcase( pc==iCellLast );
51092 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51093     /* These conditions have already been verified in btreeInitPage()
51094     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
51095     */
51096     if( pc<iCellFirst || pc>iCellLast ){
51097       return SQLITE_CORRUPT_BKPT;
51098     }
51099 #endif
51100     assert( pc>=iCellFirst && pc<=iCellLast );
51101     size = cellSizePtr(pPage, &temp[pc]);
51102     cbrk -= size;
51103 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51104     if( cbrk<iCellFirst ){
51105       return SQLITE_CORRUPT_BKPT;
51106     }
51107 #else
51108     if( cbrk<iCellFirst || pc+size>usableSize ){
51109       return SQLITE_CORRUPT_BKPT;
51110     }
51111 #endif
51112     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
51113     testcase( cbrk+size==usableSize );
51114     testcase( pc+size==usableSize );
51115     memcpy(&data[cbrk], &temp[pc], size);
51116     put2byte(pAddr, cbrk);
51117   }
51118   assert( cbrk>=iCellFirst );
51119   put2byte(&data[hdr+5], cbrk);
51120   data[hdr+1] = 0;
51121   data[hdr+2] = 0;
51122   data[hdr+7] = 0;
51123   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
51124   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51125   if( cbrk-iCellFirst!=pPage->nFree ){
51126     return SQLITE_CORRUPT_BKPT;
51127   }
51128   return SQLITE_OK;
51129 }
51130
51131 /*
51132 ** Allocate nByte bytes of space from within the B-Tree page passed
51133 ** as the first argument. Write into *pIdx the index into pPage->aData[]
51134 ** of the first byte of allocated space. Return either SQLITE_OK or
51135 ** an error code (usually SQLITE_CORRUPT).
51136 **
51137 ** The caller guarantees that there is sufficient space to make the
51138 ** allocation.  This routine might need to defragment in order to bring
51139 ** all the space together, however.  This routine will avoid using
51140 ** the first two bytes past the cell pointer area since presumably this
51141 ** allocation is being made in order to insert a new cell, so we will
51142 ** also end up needing a new cell pointer.
51143 */
51144 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
51145   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
51146   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
51147   int nFrag;                           /* Number of fragmented bytes on pPage */
51148   int top;                             /* First byte of cell content area */
51149   int gap;        /* First byte of gap between cell pointers and cell content */
51150   int rc;         /* Integer return code */
51151   int usableSize; /* Usable size of the page */
51152
51153   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51154   assert( pPage->pBt );
51155   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51156   assert( nByte>=0 );  /* Minimum cell size is 4 */
51157   assert( pPage->nFree>=nByte );
51158   assert( pPage->nOverflow==0 );
51159   usableSize = pPage->pBt->usableSize;
51160   assert( nByte < usableSize-8 );
51161
51162   nFrag = data[hdr+7];
51163   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
51164   gap = pPage->cellOffset + 2*pPage->nCell;
51165   top = get2byteNotZero(&data[hdr+5]);
51166   if( gap>top ) return SQLITE_CORRUPT_BKPT;
51167   testcase( gap+2==top );
51168   testcase( gap+1==top );
51169   testcase( gap==top );
51170
51171   if( nFrag>=60 ){
51172     /* Always defragment highly fragmented pages */
51173     rc = defragmentPage(pPage);
51174     if( rc ) return rc;
51175     top = get2byteNotZero(&data[hdr+5]);
51176   }else if( gap+2<=top ){
51177     /* Search the freelist looking for a free slot big enough to satisfy
51178     ** the request. The allocation is made from the first free slot in
51179     ** the list that is large enough to accomadate it.
51180     */
51181     int pc, addr;
51182     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
51183       int size;            /* Size of the free slot */
51184       if( pc>usableSize-4 || pc<addr+4 ){
51185         return SQLITE_CORRUPT_BKPT;
51186       }
51187       size = get2byte(&data[pc+2]);
51188       if( size>=nByte ){
51189         int x = size - nByte;
51190         testcase( x==4 );
51191         testcase( x==3 );
51192         if( x<4 ){
51193           /* Remove the slot from the free-list. Update the number of
51194           ** fragmented bytes within the page. */
51195           memcpy(&data[addr], &data[pc], 2);
51196           data[hdr+7] = (u8)(nFrag + x);
51197         }else if( size+pc > usableSize ){
51198           return SQLITE_CORRUPT_BKPT;
51199         }else{
51200           /* The slot remains on the free-list. Reduce its size to account
51201           ** for the portion used by the new allocation. */
51202           put2byte(&data[pc+2], x);
51203         }
51204         *pIdx = pc + x;
51205         return SQLITE_OK;
51206       }
51207     }
51208   }
51209
51210   /* Check to make sure there is enough space in the gap to satisfy
51211   ** the allocation.  If not, defragment.
51212   */
51213   testcase( gap+2+nByte==top );
51214   if( gap+2+nByte>top ){
51215     rc = defragmentPage(pPage);
51216     if( rc ) return rc;
51217     top = get2byteNotZero(&data[hdr+5]);
51218     assert( gap+nByte<=top );
51219   }
51220
51221
51222   /* Allocate memory from the gap in between the cell pointer array
51223   ** and the cell content area.  The btreeInitPage() call has already
51224   ** validated the freelist.  Given that the freelist is valid, there
51225   ** is no way that the allocation can extend off the end of the page.
51226   ** The assert() below verifies the previous sentence.
51227   */
51228   top -= nByte;
51229   put2byte(&data[hdr+5], top);
51230   assert( top+nByte <= (int)pPage->pBt->usableSize );
51231   *pIdx = top;
51232   return SQLITE_OK;
51233 }
51234
51235 /*
51236 ** Return a section of the pPage->aData to the freelist.
51237 ** The first byte of the new free block is pPage->aDisk[start]
51238 ** and the size of the block is "size" bytes.
51239 **
51240 ** Most of the effort here is involved in coalesing adjacent
51241 ** free blocks into a single big free block.
51242 */
51243 static int freeSpace(MemPage *pPage, int start, int size){
51244   int addr, pbegin, hdr;
51245   int iLast;                        /* Largest possible freeblock offset */
51246   unsigned char *data = pPage->aData;
51247
51248   assert( pPage->pBt!=0 );
51249   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51250   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
51251   assert( (start + size) <= (int)pPage->pBt->usableSize );
51252   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51253   assert( size>=0 );   /* Minimum cell size is 4 */
51254
51255   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
51256     /* Overwrite deleted information with zeros when the secure_delete
51257     ** option is enabled */
51258     memset(&data[start], 0, size);
51259   }
51260
51261   /* Add the space back into the linked list of freeblocks.  Note that
51262   ** even though the freeblock list was checked by btreeInitPage(),
51263   ** btreeInitPage() did not detect overlapping cells or
51264   ** freeblocks that overlapped cells.   Nor does it detect when the
51265   ** cell content area exceeds the value in the page header.  If these
51266   ** situations arise, then subsequent insert operations might corrupt
51267   ** the freelist.  So we do need to check for corruption while scanning
51268   ** the freelist.
51269   */
51270   hdr = pPage->hdrOffset;
51271   addr = hdr + 1;
51272   iLast = pPage->pBt->usableSize - 4;
51273   assert( start<=iLast );
51274   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
51275     if( pbegin<addr+4 ){
51276       return SQLITE_CORRUPT_BKPT;
51277     }
51278     addr = pbegin;
51279   }
51280   if( pbegin>iLast ){
51281     return SQLITE_CORRUPT_BKPT;
51282   }
51283   assert( pbegin>addr || pbegin==0 );
51284   put2byte(&data[addr], start);
51285   put2byte(&data[start], pbegin);
51286   put2byte(&data[start+2], size);
51287   pPage->nFree = pPage->nFree + (u16)size;
51288
51289   /* Coalesce adjacent free blocks */
51290   addr = hdr + 1;
51291   while( (pbegin = get2byte(&data[addr]))>0 ){
51292     int pnext, psize, x;
51293     assert( pbegin>addr );
51294     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
51295     pnext = get2byte(&data[pbegin]);
51296     psize = get2byte(&data[pbegin+2]);
51297     if( pbegin + psize + 3 >= pnext && pnext>0 ){
51298       int frag = pnext - (pbegin+psize);
51299       if( (frag<0) || (frag>(int)data[hdr+7]) ){
51300         return SQLITE_CORRUPT_BKPT;
51301       }
51302       data[hdr+7] -= (u8)frag;
51303       x = get2byte(&data[pnext]);
51304       put2byte(&data[pbegin], x);
51305       x = pnext + get2byte(&data[pnext+2]) - pbegin;
51306       put2byte(&data[pbegin+2], x);
51307     }else{
51308       addr = pbegin;
51309     }
51310   }
51311
51312   /* If the cell content area begins with a freeblock, remove it. */
51313   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
51314     int top;
51315     pbegin = get2byte(&data[hdr+1]);
51316     memcpy(&data[hdr+1], &data[pbegin], 2);
51317     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
51318     put2byte(&data[hdr+5], top);
51319   }
51320   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51321   return SQLITE_OK;
51322 }
51323
51324 /*
51325 ** Decode the flags byte (the first byte of the header) for a page
51326 ** and initialize fields of the MemPage structure accordingly.
51327 **
51328 ** Only the following combinations are supported.  Anything different
51329 ** indicates a corrupt database files:
51330 **
51331 **         PTF_ZERODATA
51332 **         PTF_ZERODATA | PTF_LEAF
51333 **         PTF_LEAFDATA | PTF_INTKEY
51334 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
51335 */
51336 static int decodeFlags(MemPage *pPage, int flagByte){
51337   BtShared *pBt;     /* A copy of pPage->pBt */
51338
51339   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
51340   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51341   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
51342   flagByte &= ~PTF_LEAF;
51343   pPage->childPtrSize = 4-4*pPage->leaf;
51344   pBt = pPage->pBt;
51345   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
51346     pPage->intKey = 1;
51347     pPage->hasData = pPage->leaf;
51348     pPage->maxLocal = pBt->maxLeaf;
51349     pPage->minLocal = pBt->minLeaf;
51350   }else if( flagByte==PTF_ZERODATA ){
51351     pPage->intKey = 0;
51352     pPage->hasData = 0;
51353     pPage->maxLocal = pBt->maxLocal;
51354     pPage->minLocal = pBt->minLocal;
51355   }else{
51356     return SQLITE_CORRUPT_BKPT;
51357   }
51358   pPage->max1bytePayload = pBt->max1bytePayload;
51359   return SQLITE_OK;
51360 }
51361
51362 /*
51363 ** Initialize the auxiliary information for a disk block.
51364 **
51365 ** Return SQLITE_OK on success.  If we see that the page does
51366 ** not contain a well-formed database page, then return
51367 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
51368 ** guarantee that the page is well-formed.  It only shows that
51369 ** we failed to detect any corruption.
51370 */
51371 static int btreeInitPage(MemPage *pPage){
51372
51373   assert( pPage->pBt!=0 );
51374   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51375   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
51376   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
51377   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
51378
51379   if( !pPage->isInit ){
51380     u16 pc;            /* Address of a freeblock within pPage->aData[] */
51381     u8 hdr;            /* Offset to beginning of page header */
51382     u8 *data;          /* Equal to pPage->aData */
51383     BtShared *pBt;        /* The main btree structure */
51384     int usableSize;    /* Amount of usable space on each page */
51385     u16 cellOffset;    /* Offset from start of page to first cell pointer */
51386     int nFree;         /* Number of unused bytes on the page */
51387     int top;           /* First byte of the cell content area */
51388     int iCellFirst;    /* First allowable cell or freeblock offset */
51389     int iCellLast;     /* Last possible cell or freeblock offset */
51390
51391     pBt = pPage->pBt;
51392
51393     hdr = pPage->hdrOffset;
51394     data = pPage->aData;
51395     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
51396     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51397     pPage->maskPage = (u16)(pBt->pageSize - 1);
51398     pPage->nOverflow = 0;
51399     usableSize = pBt->usableSize;
51400     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
51401     pPage->aDataEnd = &data[usableSize];
51402     pPage->aCellIdx = &data[cellOffset];
51403     top = get2byteNotZero(&data[hdr+5]);
51404     pPage->nCell = get2byte(&data[hdr+3]);
51405     if( pPage->nCell>MX_CELL(pBt) ){
51406       /* To many cells for a single page.  The page must be corrupt */
51407       return SQLITE_CORRUPT_BKPT;
51408     }
51409     testcase( pPage->nCell==MX_CELL(pBt) );
51410
51411     /* A malformed database page might cause us to read past the end
51412     ** of page when parsing a cell.
51413     **
51414     ** The following block of code checks early to see if a cell extends
51415     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
51416     ** returned if it does.
51417     */
51418     iCellFirst = cellOffset + 2*pPage->nCell;
51419     iCellLast = usableSize - 4;
51420 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51421     {
51422       int i;            /* Index into the cell pointer array */
51423       int sz;           /* Size of a cell */
51424
51425       if( !pPage->leaf ) iCellLast--;
51426       for(i=0; i<pPage->nCell; i++){
51427         pc = get2byte(&data[cellOffset+i*2]);
51428         testcase( pc==iCellFirst );
51429         testcase( pc==iCellLast );
51430         if( pc<iCellFirst || pc>iCellLast ){
51431           return SQLITE_CORRUPT_BKPT;
51432         }
51433         sz = cellSizePtr(pPage, &data[pc]);
51434         testcase( pc+sz==usableSize );
51435         if( pc+sz>usableSize ){
51436           return SQLITE_CORRUPT_BKPT;
51437         }
51438       }
51439       if( !pPage->leaf ) iCellLast++;
51440     }
51441 #endif
51442
51443     /* Compute the total free space on the page */
51444     pc = get2byte(&data[hdr+1]);
51445     nFree = data[hdr+7] + top;
51446     while( pc>0 ){
51447       u16 next, size;
51448       if( pc<iCellFirst || pc>iCellLast ){
51449         /* Start of free block is off the page */
51450         return SQLITE_CORRUPT_BKPT;
51451       }
51452       next = get2byte(&data[pc]);
51453       size = get2byte(&data[pc+2]);
51454       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
51455         /* Free blocks must be in ascending order. And the last byte of
51456         ** the free-block must lie on the database page.  */
51457         return SQLITE_CORRUPT_BKPT;
51458       }
51459       nFree = nFree + size;
51460       pc = next;
51461     }
51462
51463     /* At this point, nFree contains the sum of the offset to the start
51464     ** of the cell-content area plus the number of free bytes within
51465     ** the cell-content area. If this is greater than the usable-size
51466     ** of the page, then the page must be corrupted. This check also
51467     ** serves to verify that the offset to the start of the cell-content
51468     ** area, according to the page header, lies within the page.
51469     */
51470     if( nFree>usableSize ){
51471       return SQLITE_CORRUPT_BKPT;
51472     }
51473     pPage->nFree = (u16)(nFree - iCellFirst);
51474     pPage->isInit = 1;
51475   }
51476   return SQLITE_OK;
51477 }
51478
51479 /*
51480 ** Set up a raw page so that it looks like a database page holding
51481 ** no entries.
51482 */
51483 static void zeroPage(MemPage *pPage, int flags){
51484   unsigned char *data = pPage->aData;
51485   BtShared *pBt = pPage->pBt;
51486   u8 hdr = pPage->hdrOffset;
51487   u16 first;
51488
51489   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
51490   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51491   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
51492   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51493   assert( sqlite3_mutex_held(pBt->mutex) );
51494   if( pBt->btsFlags & BTS_SECURE_DELETE ){
51495     memset(&data[hdr], 0, pBt->usableSize - hdr);
51496   }
51497   data[hdr] = (char)flags;
51498   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
51499   memset(&data[hdr+1], 0, 4);
51500   data[hdr+7] = 0;
51501   put2byte(&data[hdr+5], pBt->usableSize);
51502   pPage->nFree = (u16)(pBt->usableSize - first);
51503   decodeFlags(pPage, flags);
51504   pPage->hdrOffset = hdr;
51505   pPage->cellOffset = first;
51506   pPage->aDataEnd = &data[pBt->usableSize];
51507   pPage->aCellIdx = &data[first];
51508   pPage->nOverflow = 0;
51509   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51510   pPage->maskPage = (u16)(pBt->pageSize - 1);
51511   pPage->nCell = 0;
51512   pPage->isInit = 1;
51513 }
51514
51515
51516 /*
51517 ** Convert a DbPage obtained from the pager into a MemPage used by
51518 ** the btree layer.
51519 */
51520 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
51521   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
51522   pPage->aData = sqlite3PagerGetData(pDbPage);
51523   pPage->pDbPage = pDbPage;
51524   pPage->pBt = pBt;
51525   pPage->pgno = pgno;
51526   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
51527   return pPage;
51528 }
51529
51530 /*
51531 ** Get a page from the pager.  Initialize the MemPage.pBt and
51532 ** MemPage.aData elements if needed.
51533 **
51534 ** If the noContent flag is set, it means that we do not care about
51535 ** the content of the page at this time.  So do not go to the disk
51536 ** to fetch the content.  Just fill in the content with zeros for now.
51537 ** If in the future we call sqlite3PagerWrite() on this page, that
51538 ** means we have started to be concerned about content and the disk
51539 ** read should occur at that point.
51540 */
51541 static int btreeGetPage(
51542   BtShared *pBt,       /* The btree */
51543   Pgno pgno,           /* Number of the page to fetch */
51544   MemPage **ppPage,    /* Return the page in this parameter */
51545   int noContent        /* Do not load page content if true */
51546 ){
51547   int rc;
51548   DbPage *pDbPage;
51549
51550   assert( sqlite3_mutex_held(pBt->mutex) );
51551   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
51552   if( rc ) return rc;
51553   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
51554   return SQLITE_OK;
51555 }
51556
51557 /*
51558 ** Retrieve a page from the pager cache. If the requested page is not
51559 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
51560 ** MemPage.aData elements if needed.
51561 */
51562 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
51563   DbPage *pDbPage;
51564   assert( sqlite3_mutex_held(pBt->mutex) );
51565   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
51566   if( pDbPage ){
51567     return btreePageFromDbPage(pDbPage, pgno, pBt);
51568   }
51569   return 0;
51570 }
51571
51572 /*
51573 ** Return the size of the database file in pages. If there is any kind of
51574 ** error, return ((unsigned int)-1).
51575 */
51576 static Pgno btreePagecount(BtShared *pBt){
51577   return pBt->nPage;
51578 }
51579 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
51580   assert( sqlite3BtreeHoldsMutex(p) );
51581   assert( ((p->pBt->nPage)&0x8000000)==0 );
51582   return (int)btreePagecount(p->pBt);
51583 }
51584
51585 /*
51586 ** Get a page from the pager and initialize it.  This routine is just a
51587 ** convenience wrapper around separate calls to btreeGetPage() and
51588 ** btreeInitPage().
51589 **
51590 ** If an error occurs, then the value *ppPage is set to is undefined. It
51591 ** may remain unchanged, or it may be set to an invalid value.
51592 */
51593 static int getAndInitPage(
51594   BtShared *pBt,          /* The database file */
51595   Pgno pgno,           /* Number of the page to get */
51596   MemPage **ppPage     /* Write the page pointer here */
51597 ){
51598   int rc;
51599   assert( sqlite3_mutex_held(pBt->mutex) );
51600
51601   if( pgno>btreePagecount(pBt) ){
51602     rc = SQLITE_CORRUPT_BKPT;
51603   }else{
51604     rc = btreeGetPage(pBt, pgno, ppPage, 0);
51605     if( rc==SQLITE_OK ){
51606       rc = btreeInitPage(*ppPage);
51607       if( rc!=SQLITE_OK ){
51608         releasePage(*ppPage);
51609       }
51610     }
51611   }
51612
51613   testcase( pgno==0 );
51614   assert( pgno!=0 || rc==SQLITE_CORRUPT );
51615   return rc;
51616 }
51617
51618 /*
51619 ** Release a MemPage.  This should be called once for each prior
51620 ** call to btreeGetPage.
51621 */
51622 static void releasePage(MemPage *pPage){
51623   if( pPage ){
51624     assert( pPage->aData );
51625     assert( pPage->pBt );
51626     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51627     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
51628     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51629     sqlite3PagerUnref(pPage->pDbPage);
51630   }
51631 }
51632
51633 /*
51634 ** During a rollback, when the pager reloads information into the cache
51635 ** so that the cache is restored to its original state at the start of
51636 ** the transaction, for each page restored this routine is called.
51637 **
51638 ** This routine needs to reset the extra data section at the end of the
51639 ** page to agree with the restored data.
51640 */
51641 static void pageReinit(DbPage *pData){
51642   MemPage *pPage;
51643   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
51644   assert( sqlite3PagerPageRefcount(pData)>0 );
51645   if( pPage->isInit ){
51646     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51647     pPage->isInit = 0;
51648     if( sqlite3PagerPageRefcount(pData)>1 ){
51649       /* pPage might not be a btree page;  it might be an overflow page
51650       ** or ptrmap page or a free page.  In those cases, the following
51651       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
51652       ** But no harm is done by this.  And it is very important that
51653       ** btreeInitPage() be called on every btree page so we make
51654       ** the call for every page that comes in for re-initing. */
51655       btreeInitPage(pPage);
51656     }
51657   }
51658 }
51659
51660 /*
51661 ** Invoke the busy handler for a btree.
51662 */
51663 static int btreeInvokeBusyHandler(void *pArg){
51664   BtShared *pBt = (BtShared*)pArg;
51665   assert( pBt->db );
51666   assert( sqlite3_mutex_held(pBt->db->mutex) );
51667   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
51668 }
51669
51670 /*
51671 ** Open a database file.
51672 **
51673 ** zFilename is the name of the database file.  If zFilename is NULL
51674 ** then an ephemeral database is created.  The ephemeral database might
51675 ** be exclusively in memory, or it might use a disk-based memory cache.
51676 ** Either way, the ephemeral database will be automatically deleted
51677 ** when sqlite3BtreeClose() is called.
51678 **
51679 ** If zFilename is ":memory:" then an in-memory database is created
51680 ** that is automatically destroyed when it is closed.
51681 **
51682 ** The "flags" parameter is a bitmask that might contain bits like
51683 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
51684 **
51685 ** If the database is already opened in the same database connection
51686 ** and we are in shared cache mode, then the open will fail with an
51687 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
51688 ** objects in the same database connection since doing so will lead
51689 ** to problems with locking.
51690 */
51691 SQLITE_PRIVATE int sqlite3BtreeOpen(
51692   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
51693   const char *zFilename,  /* Name of the file containing the BTree database */
51694   sqlite3 *db,            /* Associated database handle */
51695   Btree **ppBtree,        /* Pointer to new Btree object written here */
51696   int flags,              /* Options */
51697   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
51698 ){
51699   BtShared *pBt = 0;             /* Shared part of btree structure */
51700   Btree *p;                      /* Handle to return */
51701   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51702   int rc = SQLITE_OK;            /* Result code from this function */
51703   u8 nReserve;                   /* Byte of unused space on each page */
51704   unsigned char zDbHeader[100];  /* Database header content */
51705
51706   /* True if opening an ephemeral, temporary database */
51707   const int isTempDb = zFilename==0 || zFilename[0]==0;
51708
51709   /* Set the variable isMemdb to true for an in-memory database, or
51710   ** false for a file-based database.
51711   */
51712 #ifdef SQLITE_OMIT_MEMORYDB
51713   const int isMemdb = 0;
51714 #else
51715   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51716                        || (isTempDb && sqlite3TempInMemory(db))
51717                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
51718 #endif
51719
51720   assert( db!=0 );
51721   assert( pVfs!=0 );
51722   assert( sqlite3_mutex_held(db->mutex) );
51723   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51724
51725   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51726   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51727
51728   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51729   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51730
51731   if( isMemdb ){
51732     flags |= BTREE_MEMORY;
51733   }
51734   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51735     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
51736   }
51737   p = sqlite3MallocZero(sizeof(Btree));
51738   if( !p ){
51739     return SQLITE_NOMEM;
51740   }
51741   p->inTrans = TRANS_NONE;
51742   p->db = db;
51743 #ifndef SQLITE_OMIT_SHARED_CACHE
51744   p->lock.pBtree = p;
51745   p->lock.iTable = 1;
51746 #endif
51747
51748 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51749   /*
51750   ** If this Btree is a candidate for shared cache, try to find an
51751   ** existing BtShared object that we can share with
51752   */
51753   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
51754     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
51755       int nFullPathname = pVfs->mxPathname+1;
51756       char *zFullPathname = sqlite3Malloc(nFullPathname);
51757       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51758       p->sharable = 1;
51759       if( !zFullPathname ){
51760         sqlite3_free(p);
51761         return SQLITE_NOMEM;
51762       }
51763       if( isMemdb ){
51764         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
51765       }else{
51766         rc = sqlite3OsFullPathname(pVfs, zFilename,
51767                                    nFullPathname, zFullPathname);
51768         if( rc ){
51769           sqlite3_free(zFullPathname);
51770           sqlite3_free(p);
51771           return rc;
51772         }
51773       }
51774 #if SQLITE_THREADSAFE
51775       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
51776       sqlite3_mutex_enter(mutexOpen);
51777       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
51778       sqlite3_mutex_enter(mutexShared);
51779 #endif
51780       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
51781         assert( pBt->nRef>0 );
51782         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
51783                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
51784           int iDb;
51785           for(iDb=db->nDb-1; iDb>=0; iDb--){
51786             Btree *pExisting = db->aDb[iDb].pBt;
51787             if( pExisting && pExisting->pBt==pBt ){
51788               sqlite3_mutex_leave(mutexShared);
51789               sqlite3_mutex_leave(mutexOpen);
51790               sqlite3_free(zFullPathname);
51791               sqlite3_free(p);
51792               return SQLITE_CONSTRAINT;
51793             }
51794           }
51795           p->pBt = pBt;
51796           pBt->nRef++;
51797           break;
51798         }
51799       }
51800       sqlite3_mutex_leave(mutexShared);
51801       sqlite3_free(zFullPathname);
51802     }
51803 #ifdef SQLITE_DEBUG
51804     else{
51805       /* In debug mode, we mark all persistent databases as sharable
51806       ** even when they are not.  This exercises the locking code and
51807       ** gives more opportunity for asserts(sqlite3_mutex_held())
51808       ** statements to find locking problems.
51809       */
51810       p->sharable = 1;
51811     }
51812 #endif
51813   }
51814 #endif
51815   if( pBt==0 ){
51816     /*
51817     ** The following asserts make sure that structures used by the btree are
51818     ** the right size.  This is to guard against size changes that result
51819     ** when compiling on a different architecture.
51820     */
51821     assert( sizeof(i64)==8 || sizeof(i64)==4 );
51822     assert( sizeof(u64)==8 || sizeof(u64)==4 );
51823     assert( sizeof(u32)==4 );
51824     assert( sizeof(u16)==2 );
51825     assert( sizeof(Pgno)==4 );
51826
51827     pBt = sqlite3MallocZero( sizeof(*pBt) );
51828     if( pBt==0 ){
51829       rc = SQLITE_NOMEM;
51830       goto btree_open_out;
51831     }
51832     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
51833                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
51834     if( rc==SQLITE_OK ){
51835       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51836     }
51837     if( rc!=SQLITE_OK ){
51838       goto btree_open_out;
51839     }
51840     pBt->openFlags = (u8)flags;
51841     pBt->db = db;
51842     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51843     p->pBt = pBt;
51844
51845     pBt->pCursor = 0;
51846     pBt->pPage1 = 0;
51847     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
51848 #ifdef SQLITE_SECURE_DELETE
51849     pBt->btsFlags |= BTS_SECURE_DELETE;
51850 #endif
51851     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51852     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
51853          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51854       pBt->pageSize = 0;
51855 #ifndef SQLITE_OMIT_AUTOVACUUM
51856       /* If the magic name ":memory:" will create an in-memory database, then
51857       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51858       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
51859       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51860       ** regular file-name. In this case the auto-vacuum applies as per normal.
51861       */
51862       if( zFilename && !isMemdb ){
51863         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
51864         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51865       }
51866 #endif
51867       nReserve = 0;
51868     }else{
51869       nReserve = zDbHeader[20];
51870       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51871 #ifndef SQLITE_OMIT_AUTOVACUUM
51872       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51873       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51874 #endif
51875     }
51876     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51877     if( rc ) goto btree_open_out;
51878     pBt->usableSize = pBt->pageSize - nReserve;
51879     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
51880
51881 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51882     /* Add the new BtShared object to the linked list sharable BtShareds.
51883     */
51884     if( p->sharable ){
51885       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51886       pBt->nRef = 1;
51887       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
51888       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
51889         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
51890         if( pBt->mutex==0 ){
51891           rc = SQLITE_NOMEM;
51892           db->mallocFailed = 0;
51893           goto btree_open_out;
51894         }
51895       }
51896       sqlite3_mutex_enter(mutexShared);
51897       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
51898       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
51899       sqlite3_mutex_leave(mutexShared);
51900     }
51901 #endif
51902   }
51903
51904 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51905   /* If the new Btree uses a sharable pBtShared, then link the new
51906   ** Btree into the list of all sharable Btrees for the same connection.
51907   ** The list is kept in ascending order by pBt address.
51908   */
51909   if( p->sharable ){
51910     int i;
51911     Btree *pSib;
51912     for(i=0; i<db->nDb; i++){
51913       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51914         while( pSib->pPrev ){ pSib = pSib->pPrev; }
51915         if( p->pBt<pSib->pBt ){
51916           p->pNext = pSib;
51917           p->pPrev = 0;
51918           pSib->pPrev = p;
51919         }else{
51920           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51921             pSib = pSib->pNext;
51922           }
51923           p->pNext = pSib->pNext;
51924           p->pPrev = pSib;
51925           if( p->pNext ){
51926             p->pNext->pPrev = p;
51927           }
51928           pSib->pNext = p;
51929         }
51930         break;
51931       }
51932     }
51933   }
51934 #endif
51935   *ppBtree = p;
51936
51937 btree_open_out:
51938   if( rc!=SQLITE_OK ){
51939     if( pBt && pBt->pPager ){
51940       sqlite3PagerClose(pBt->pPager);
51941     }
51942     sqlite3_free(pBt);
51943     sqlite3_free(p);
51944     *ppBtree = 0;
51945   }else{
51946     /* If the B-Tree was successfully opened, set the pager-cache size to the
51947     ** default value. Except, when opening on an existing shared pager-cache,
51948     ** do not change the pager-cache size.
51949     */
51950     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
51951       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
51952     }
51953   }
51954   if( mutexOpen ){
51955     assert( sqlite3_mutex_held(mutexOpen) );
51956     sqlite3_mutex_leave(mutexOpen);
51957   }
51958   return rc;
51959 }
51960
51961 /*
51962 ** Decrement the BtShared.nRef counter.  When it reaches zero,
51963 ** remove the BtShared structure from the sharing list.  Return
51964 ** true if the BtShared.nRef counter reaches zero and return
51965 ** false if it is still positive.
51966 */
51967 static int removeFromSharingList(BtShared *pBt){
51968 #ifndef SQLITE_OMIT_SHARED_CACHE
51969   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
51970   BtShared *pList;
51971   int removed = 0;
51972
51973   assert( sqlite3_mutex_notheld(pBt->mutex) );
51974   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
51975   sqlite3_mutex_enter(pMaster);
51976   pBt->nRef--;
51977   if( pBt->nRef<=0 ){
51978     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
51979       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
51980     }else{
51981       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
51982       while( ALWAYS(pList) && pList->pNext!=pBt ){
51983         pList=pList->pNext;
51984       }
51985       if( ALWAYS(pList) ){
51986         pList->pNext = pBt->pNext;
51987       }
51988     }
51989     if( SQLITE_THREADSAFE ){
51990       sqlite3_mutex_free(pBt->mutex);
51991     }
51992     removed = 1;
51993   }
51994   sqlite3_mutex_leave(pMaster);
51995   return removed;
51996 #else
51997   return 1;
51998 #endif
51999 }
52000
52001 /*
52002 ** Make sure pBt->pTmpSpace points to an allocation of
52003 ** MX_CELL_SIZE(pBt) bytes.
52004 */
52005 static void allocateTempSpace(BtShared *pBt){
52006   if( !pBt->pTmpSpace ){
52007     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
52008   }
52009 }
52010
52011 /*
52012 ** Free the pBt->pTmpSpace allocation
52013 */
52014 static void freeTempSpace(BtShared *pBt){
52015   sqlite3PageFree( pBt->pTmpSpace);
52016   pBt->pTmpSpace = 0;
52017 }
52018
52019 /*
52020 ** Close an open database and invalidate all cursors.
52021 */
52022 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
52023   BtShared *pBt = p->pBt;
52024   BtCursor *pCur;
52025
52026   /* Close all cursors opened via this handle.  */
52027   assert( sqlite3_mutex_held(p->db->mutex) );
52028   sqlite3BtreeEnter(p);
52029   pCur = pBt->pCursor;
52030   while( pCur ){
52031     BtCursor *pTmp = pCur;
52032     pCur = pCur->pNext;
52033     if( pTmp->pBtree==p ){
52034       sqlite3BtreeCloseCursor(pTmp);
52035     }
52036   }
52037
52038   /* Rollback any active transaction and free the handle structure.
52039   ** The call to sqlite3BtreeRollback() drops any table-locks held by
52040   ** this handle.
52041   */
52042   sqlite3BtreeRollback(p, SQLITE_OK);
52043   sqlite3BtreeLeave(p);
52044
52045   /* If there are still other outstanding references to the shared-btree
52046   ** structure, return now. The remainder of this procedure cleans
52047   ** up the shared-btree.
52048   */
52049   assert( p->wantToLock==0 && p->locked==0 );
52050   if( !p->sharable || removeFromSharingList(pBt) ){
52051     /* The pBt is no longer on the sharing list, so we can access
52052     ** it without having to hold the mutex.
52053     **
52054     ** Clean out and delete the BtShared object.
52055     */
52056     assert( !pBt->pCursor );
52057     sqlite3PagerClose(pBt->pPager);
52058     if( pBt->xFreeSchema && pBt->pSchema ){
52059       pBt->xFreeSchema(pBt->pSchema);
52060     }
52061     sqlite3DbFree(0, pBt->pSchema);
52062     freeTempSpace(pBt);
52063     sqlite3_free(pBt);
52064   }
52065
52066 #ifndef SQLITE_OMIT_SHARED_CACHE
52067   assert( p->wantToLock==0 );
52068   assert( p->locked==0 );
52069   if( p->pPrev ) p->pPrev->pNext = p->pNext;
52070   if( p->pNext ) p->pNext->pPrev = p->pPrev;
52071 #endif
52072
52073   sqlite3_free(p);
52074   return SQLITE_OK;
52075 }
52076
52077 /*
52078 ** Change the limit on the number of pages allowed in the cache.
52079 **
52080 ** The maximum number of cache pages is set to the absolute
52081 ** value of mxPage.  If mxPage is negative, the pager will
52082 ** operate asynchronously - it will not stop to do fsync()s
52083 ** to insure data is written to the disk surface before
52084 ** continuing.  Transactions still work if synchronous is off,
52085 ** and the database cannot be corrupted if this program
52086 ** crashes.  But if the operating system crashes or there is
52087 ** an abrupt power failure when synchronous is off, the database
52088 ** could be left in an inconsistent and unrecoverable state.
52089 ** Synchronous is on by default so database corruption is not
52090 ** normally a worry.
52091 */
52092 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
52093   BtShared *pBt = p->pBt;
52094   assert( sqlite3_mutex_held(p->db->mutex) );
52095   sqlite3BtreeEnter(p);
52096   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
52097   sqlite3BtreeLeave(p);
52098   return SQLITE_OK;
52099 }
52100
52101 /*
52102 ** Change the way data is synced to disk in order to increase or decrease
52103 ** how well the database resists damage due to OS crashes and power
52104 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
52105 ** there is a high probability of damage)  Level 2 is the default.  There
52106 ** is a very low but non-zero probability of damage.  Level 3 reduces the
52107 ** probability of damage to near zero but with a write performance reduction.
52108 */
52109 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
52110 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
52111   Btree *p,              /* The btree to set the safety level on */
52112   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
52113   int fullSync,          /* PRAGMA fullfsync. */
52114   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
52115 ){
52116   BtShared *pBt = p->pBt;
52117   assert( sqlite3_mutex_held(p->db->mutex) );
52118   assert( level>=1 && level<=3 );
52119   sqlite3BtreeEnter(p);
52120   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
52121   sqlite3BtreeLeave(p);
52122   return SQLITE_OK;
52123 }
52124 #endif
52125
52126 /*
52127 ** Return TRUE if the given btree is set to safety level 1.  In other
52128 ** words, return TRUE if no sync() occurs on the disk files.
52129 */
52130 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
52131   BtShared *pBt = p->pBt;
52132   int rc;
52133   assert( sqlite3_mutex_held(p->db->mutex) );
52134   sqlite3BtreeEnter(p);
52135   assert( pBt && pBt->pPager );
52136   rc = sqlite3PagerNosync(pBt->pPager);
52137   sqlite3BtreeLeave(p);
52138   return rc;
52139 }
52140
52141 /*
52142 ** Change the default pages size and the number of reserved bytes per page.
52143 ** Or, if the page size has already been fixed, return SQLITE_READONLY
52144 ** without changing anything.
52145 **
52146 ** The page size must be a power of 2 between 512 and 65536.  If the page
52147 ** size supplied does not meet this constraint then the page size is not
52148 ** changed.
52149 **
52150 ** Page sizes are constrained to be a power of two so that the region
52151 ** of the database file used for locking (beginning at PENDING_BYTE,
52152 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
52153 ** at the beginning of a page.
52154 **
52155 ** If parameter nReserve is less than zero, then the number of reserved
52156 ** bytes per page is left unchanged.
52157 **
52158 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
52159 ** and autovacuum mode can no longer be changed.
52160 */
52161 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
52162   int rc = SQLITE_OK;
52163   BtShared *pBt = p->pBt;
52164   assert( nReserve>=-1 && nReserve<=255 );
52165   sqlite3BtreeEnter(p);
52166   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
52167     sqlite3BtreeLeave(p);
52168     return SQLITE_READONLY;
52169   }
52170   if( nReserve<0 ){
52171     nReserve = pBt->pageSize - pBt->usableSize;
52172   }
52173   assert( nReserve>=0 && nReserve<=255 );
52174   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
52175         ((pageSize-1)&pageSize)==0 ){
52176     assert( (pageSize & 7)==0 );
52177     assert( !pBt->pPage1 && !pBt->pCursor );
52178     pBt->pageSize = (u32)pageSize;
52179     freeTempSpace(pBt);
52180   }
52181   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
52182   pBt->usableSize = pBt->pageSize - (u16)nReserve;
52183   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52184   sqlite3BtreeLeave(p);
52185   return rc;
52186 }
52187
52188 /*
52189 ** Return the currently defined page size
52190 */
52191 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
52192   return p->pBt->pageSize;
52193 }
52194
52195 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
52196 /*
52197 ** This function is similar to sqlite3BtreeGetReserve(), except that it
52198 ** may only be called if it is guaranteed that the b-tree mutex is already
52199 ** held.
52200 **
52201 ** This is useful in one special case in the backup API code where it is
52202 ** known that the shared b-tree mutex is held, but the mutex on the
52203 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
52204 ** were to be called, it might collide with some other operation on the
52205 ** database handle that owns *p, causing undefined behaviour.
52206 */
52207 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
52208   assert( sqlite3_mutex_held(p->pBt->mutex) );
52209   return p->pBt->pageSize - p->pBt->usableSize;
52210 }
52211 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
52212
52213 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
52214 /*
52215 ** Return the number of bytes of space at the end of every page that
52216 ** are intentually left unused.  This is the "reserved" space that is
52217 ** sometimes used by extensions.
52218 */
52219 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
52220   int n;
52221   sqlite3BtreeEnter(p);
52222   n = p->pBt->pageSize - p->pBt->usableSize;
52223   sqlite3BtreeLeave(p);
52224   return n;
52225 }
52226
52227 /*
52228 ** Set the maximum page count for a database if mxPage is positive.
52229 ** No changes are made if mxPage is 0 or negative.
52230 ** Regardless of the value of mxPage, return the maximum page count.
52231 */
52232 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
52233   int n;
52234   sqlite3BtreeEnter(p);
52235   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
52236   sqlite3BtreeLeave(p);
52237   return n;
52238 }
52239
52240 /*
52241 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
52242 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
52243 ** setting after the change.
52244 */
52245 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
52246   int b;
52247   if( p==0 ) return 0;
52248   sqlite3BtreeEnter(p);
52249   if( newFlag>=0 ){
52250     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
52251     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
52252   }
52253   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
52254   sqlite3BtreeLeave(p);
52255   return b;
52256 }
52257 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
52258
52259 /*
52260 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
52261 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
52262 ** is disabled. The default value for the auto-vacuum property is
52263 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
52264 */
52265 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
52266 #ifdef SQLITE_OMIT_AUTOVACUUM
52267   return SQLITE_READONLY;
52268 #else
52269   BtShared *pBt = p->pBt;
52270   int rc = SQLITE_OK;
52271   u8 av = (u8)autoVacuum;
52272
52273   sqlite3BtreeEnter(p);
52274   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
52275     rc = SQLITE_READONLY;
52276   }else{
52277     pBt->autoVacuum = av ?1:0;
52278     pBt->incrVacuum = av==2 ?1:0;
52279   }
52280   sqlite3BtreeLeave(p);
52281   return rc;
52282 #endif
52283 }
52284
52285 /*
52286 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
52287 ** enabled 1 is returned. Otherwise 0.
52288 */
52289 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
52290 #ifdef SQLITE_OMIT_AUTOVACUUM
52291   return BTREE_AUTOVACUUM_NONE;
52292 #else
52293   int rc;
52294   sqlite3BtreeEnter(p);
52295   rc = (
52296     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
52297     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
52298     BTREE_AUTOVACUUM_INCR
52299   );
52300   sqlite3BtreeLeave(p);
52301   return rc;
52302 #endif
52303 }
52304
52305
52306 /*
52307 ** Get a reference to pPage1 of the database file.  This will
52308 ** also acquire a readlock on that file.
52309 **
52310 ** SQLITE_OK is returned on success.  If the file is not a
52311 ** well-formed database file, then SQLITE_CORRUPT is returned.
52312 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
52313 ** is returned if we run out of memory.
52314 */
52315 static int lockBtree(BtShared *pBt){
52316   int rc;              /* Result code from subfunctions */
52317   MemPage *pPage1;     /* Page 1 of the database file */
52318   int nPage;           /* Number of pages in the database */
52319   int nPageFile = 0;   /* Number of pages in the database file */
52320   int nPageHeader;     /* Number of pages in the database according to hdr */
52321
52322   assert( sqlite3_mutex_held(pBt->mutex) );
52323   assert( pBt->pPage1==0 );
52324   rc = sqlite3PagerSharedLock(pBt->pPager);
52325   if( rc!=SQLITE_OK ) return rc;
52326   rc = btreeGetPage(pBt, 1, &pPage1, 0);
52327   if( rc!=SQLITE_OK ) return rc;
52328
52329   /* Do some checking to help insure the file we opened really is
52330   ** a valid database file.
52331   */
52332   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
52333   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
52334   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
52335     nPage = nPageFile;
52336   }
52337   if( nPage>0 ){
52338     u32 pageSize;
52339     u32 usableSize;
52340     u8 *page1 = pPage1->aData;
52341     rc = SQLITE_NOTADB;
52342     if( memcmp(page1, zMagicHeader, 16)!=0 ){
52343       goto page1_init_failed;
52344     }
52345
52346 #ifdef SQLITE_OMIT_WAL
52347     if( page1[18]>1 ){
52348       pBt->btsFlags |= BTS_READ_ONLY;
52349     }
52350     if( page1[19]>1 ){
52351       goto page1_init_failed;
52352     }
52353 #else
52354     if( page1[18]>2 ){
52355       pBt->btsFlags |= BTS_READ_ONLY;
52356     }
52357     if( page1[19]>2 ){
52358       goto page1_init_failed;
52359     }
52360
52361     /* If the write version is set to 2, this database should be accessed
52362     ** in WAL mode. If the log is not already open, open it now. Then
52363     ** return SQLITE_OK and return without populating BtShared.pPage1.
52364     ** The caller detects this and calls this function again. This is
52365     ** required as the version of page 1 currently in the page1 buffer
52366     ** may not be the latest version - there may be a newer one in the log
52367     ** file.
52368     */
52369     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
52370       int isOpen = 0;
52371       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
52372       if( rc!=SQLITE_OK ){
52373         goto page1_init_failed;
52374       }else if( isOpen==0 ){
52375         releasePage(pPage1);
52376         return SQLITE_OK;
52377       }
52378       rc = SQLITE_NOTADB;
52379     }
52380 #endif
52381
52382     /* The maximum embedded fraction must be exactly 25%.  And the minimum
52383     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
52384     ** The original design allowed these amounts to vary, but as of
52385     ** version 3.6.0, we require them to be fixed.
52386     */
52387     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
52388       goto page1_init_failed;
52389     }
52390     pageSize = (page1[16]<<8) | (page1[17]<<16);
52391     if( ((pageSize-1)&pageSize)!=0
52392      || pageSize>SQLITE_MAX_PAGE_SIZE
52393      || pageSize<=256
52394     ){
52395       goto page1_init_failed;
52396     }
52397     assert( (pageSize & 7)==0 );
52398     usableSize = pageSize - page1[20];
52399     if( (u32)pageSize!=pBt->pageSize ){
52400       /* After reading the first page of the database assuming a page size
52401       ** of BtShared.pageSize, we have discovered that the page-size is
52402       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
52403       ** zero and return SQLITE_OK. The caller will call this function
52404       ** again with the correct page-size.
52405       */
52406       releasePage(pPage1);
52407       pBt->usableSize = usableSize;
52408       pBt->pageSize = pageSize;
52409       freeTempSpace(pBt);
52410       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
52411                                    pageSize-usableSize);
52412       return rc;
52413     }
52414     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
52415       rc = SQLITE_CORRUPT_BKPT;
52416       goto page1_init_failed;
52417     }
52418     if( usableSize<480 ){
52419       goto page1_init_failed;
52420     }
52421     pBt->pageSize = pageSize;
52422     pBt->usableSize = usableSize;
52423 #ifndef SQLITE_OMIT_AUTOVACUUM
52424     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
52425     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
52426 #endif
52427   }
52428
52429   /* maxLocal is the maximum amount of payload to store locally for
52430   ** a cell.  Make sure it is small enough so that at least minFanout
52431   ** cells can will fit on one page.  We assume a 10-byte page header.
52432   ** Besides the payload, the cell must store:
52433   **     2-byte pointer to the cell
52434   **     4-byte child pointer
52435   **     9-byte nKey value
52436   **     4-byte nData value
52437   **     4-byte overflow page pointer
52438   ** So a cell consists of a 2-byte pointer, a header which is as much as
52439   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
52440   ** page pointer.
52441   */
52442   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
52443   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
52444   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
52445   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
52446   if( pBt->maxLocal>127 ){
52447     pBt->max1bytePayload = 127;
52448   }else{
52449     pBt->max1bytePayload = (u8)pBt->maxLocal;
52450   }
52451   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
52452   pBt->pPage1 = pPage1;
52453   pBt->nPage = nPage;
52454   return SQLITE_OK;
52455
52456 page1_init_failed:
52457   releasePage(pPage1);
52458   pBt->pPage1 = 0;
52459   return rc;
52460 }
52461
52462 /*
52463 ** If there are no outstanding cursors and we are not in the middle
52464 ** of a transaction but there is a read lock on the database, then
52465 ** this routine unrefs the first page of the database file which
52466 ** has the effect of releasing the read lock.
52467 **
52468 ** If there is a transaction in progress, this routine is a no-op.
52469 */
52470 static void unlockBtreeIfUnused(BtShared *pBt){
52471   assert( sqlite3_mutex_held(pBt->mutex) );
52472   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
52473   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
52474     assert( pBt->pPage1->aData );
52475     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
52476     assert( pBt->pPage1->aData );
52477     releasePage(pBt->pPage1);
52478     pBt->pPage1 = 0;
52479   }
52480 }
52481
52482 /*
52483 ** If pBt points to an empty file then convert that empty file
52484 ** into a new empty database by initializing the first page of
52485 ** the database.
52486 */
52487 static int newDatabase(BtShared *pBt){
52488   MemPage *pP1;
52489   unsigned char *data;
52490   int rc;
52491
52492   assert( sqlite3_mutex_held(pBt->mutex) );
52493   if( pBt->nPage>0 ){
52494     return SQLITE_OK;
52495   }
52496   pP1 = pBt->pPage1;
52497   assert( pP1!=0 );
52498   data = pP1->aData;
52499   rc = sqlite3PagerWrite(pP1->pDbPage);
52500   if( rc ) return rc;
52501   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
52502   assert( sizeof(zMagicHeader)==16 );
52503   data[16] = (u8)((pBt->pageSize>>8)&0xff);
52504   data[17] = (u8)((pBt->pageSize>>16)&0xff);
52505   data[18] = 1;
52506   data[19] = 1;
52507   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
52508   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
52509   data[21] = 64;
52510   data[22] = 32;
52511   data[23] = 32;
52512   memset(&data[24], 0, 100-24);
52513   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
52514   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52515 #ifndef SQLITE_OMIT_AUTOVACUUM
52516   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
52517   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
52518   put4byte(&data[36 + 4*4], pBt->autoVacuum);
52519   put4byte(&data[36 + 7*4], pBt->incrVacuum);
52520 #endif
52521   pBt->nPage = 1;
52522   data[31] = 1;
52523   return SQLITE_OK;
52524 }
52525
52526 /*
52527 ** Initialize the first page of the database file (creating a database
52528 ** consisting of a single page and no schema objects). Return SQLITE_OK
52529 ** if successful, or an SQLite error code otherwise.
52530 */
52531 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
52532   int rc;
52533   sqlite3BtreeEnter(p);
52534   p->pBt->nPage = 0;
52535   rc = newDatabase(p->pBt);
52536   sqlite3BtreeLeave(p);
52537   return rc;
52538 }
52539
52540 /*
52541 ** Attempt to start a new transaction. A write-transaction
52542 ** is started if the second argument is nonzero, otherwise a read-
52543 ** transaction.  If the second argument is 2 or more and exclusive
52544 ** transaction is started, meaning that no other process is allowed
52545 ** to access the database.  A preexisting transaction may not be
52546 ** upgraded to exclusive by calling this routine a second time - the
52547 ** exclusivity flag only works for a new transaction.
52548 **
52549 ** A write-transaction must be started before attempting any
52550 ** changes to the database.  None of the following routines
52551 ** will work unless a transaction is started first:
52552 **
52553 **      sqlite3BtreeCreateTable()
52554 **      sqlite3BtreeCreateIndex()
52555 **      sqlite3BtreeClearTable()
52556 **      sqlite3BtreeDropTable()
52557 **      sqlite3BtreeInsert()
52558 **      sqlite3BtreeDelete()
52559 **      sqlite3BtreeUpdateMeta()
52560 **
52561 ** If an initial attempt to acquire the lock fails because of lock contention
52562 ** and the database was previously unlocked, then invoke the busy handler
52563 ** if there is one.  But if there was previously a read-lock, do not
52564 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
52565 ** returned when there is already a read-lock in order to avoid a deadlock.
52566 **
52567 ** Suppose there are two processes A and B.  A has a read lock and B has
52568 ** a reserved lock.  B tries to promote to exclusive but is blocked because
52569 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
52570 ** One or the other of the two processes must give way or there can be
52571 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
52572 ** when A already has a read lock, we encourage A to give up and let B
52573 ** proceed.
52574 */
52575 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
52576   sqlite3 *pBlock = 0;
52577   BtShared *pBt = p->pBt;
52578   int rc = SQLITE_OK;
52579
52580   sqlite3BtreeEnter(p);
52581   btreeIntegrity(p);
52582
52583   /* If the btree is already in a write-transaction, or it
52584   ** is already in a read-transaction and a read-transaction
52585   ** is requested, this is a no-op.
52586   */
52587   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
52588     goto trans_begun;
52589   }
52590
52591   /* Write transactions are not possible on a read-only database */
52592   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
52593     rc = SQLITE_READONLY;
52594     goto trans_begun;
52595   }
52596
52597 #ifndef SQLITE_OMIT_SHARED_CACHE
52598   /* If another database handle has already opened a write transaction
52599   ** on this shared-btree structure and a second write transaction is
52600   ** requested, return SQLITE_LOCKED.
52601   */
52602   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
52603    || (pBt->btsFlags & BTS_PENDING)!=0
52604   ){
52605     pBlock = pBt->pWriter->db;
52606   }else if( wrflag>1 ){
52607     BtLock *pIter;
52608     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52609       if( pIter->pBtree!=p ){
52610         pBlock = pIter->pBtree->db;
52611         break;
52612       }
52613     }
52614   }
52615   if( pBlock ){
52616     sqlite3ConnectionBlocked(p->db, pBlock);
52617     rc = SQLITE_LOCKED_SHAREDCACHE;
52618     goto trans_begun;
52619   }
52620 #endif
52621
52622   /* Any read-only or read-write transaction implies a read-lock on
52623   ** page 1. So if some other shared-cache client already has a write-lock
52624   ** on page 1, the transaction cannot be opened. */
52625   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52626   if( SQLITE_OK!=rc ) goto trans_begun;
52627
52628   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
52629   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
52630   do {
52631     /* Call lockBtree() until either pBt->pPage1 is populated or
52632     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
52633     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
52634     ** reading page 1 it discovers that the page-size of the database
52635     ** file is not pBt->pageSize. In this case lockBtree() will update
52636     ** pBt->pageSize to the page-size of the file on disk.
52637     */
52638     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
52639
52640     if( rc==SQLITE_OK && wrflag ){
52641       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
52642         rc = SQLITE_READONLY;
52643       }else{
52644         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
52645         if( rc==SQLITE_OK ){
52646           rc = newDatabase(pBt);
52647         }
52648       }
52649     }
52650
52651     if( rc!=SQLITE_OK ){
52652       unlockBtreeIfUnused(pBt);
52653     }
52654   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
52655           btreeInvokeBusyHandler(pBt) );
52656
52657   if( rc==SQLITE_OK ){
52658     if( p->inTrans==TRANS_NONE ){
52659       pBt->nTransaction++;
52660 #ifndef SQLITE_OMIT_SHARED_CACHE
52661       if( p->sharable ){
52662         assert( p->lock.pBtree==p && p->lock.iTable==1 );
52663         p->lock.eLock = READ_LOCK;
52664         p->lock.pNext = pBt->pLock;
52665         pBt->pLock = &p->lock;
52666       }
52667 #endif
52668     }
52669     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52670     if( p->inTrans>pBt->inTransaction ){
52671       pBt->inTransaction = p->inTrans;
52672     }
52673     if( wrflag ){
52674       MemPage *pPage1 = pBt->pPage1;
52675 #ifndef SQLITE_OMIT_SHARED_CACHE
52676       assert( !pBt->pWriter );
52677       pBt->pWriter = p;
52678       pBt->btsFlags &= ~BTS_EXCLUSIVE;
52679       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
52680 #endif
52681
52682       /* If the db-size header field is incorrect (as it may be if an old
52683       ** client has been writing the database file), update it now. Doing
52684       ** this sooner rather than later means the database size can safely
52685       ** re-read the database size from page 1 if a savepoint or transaction
52686       ** rollback occurs within the transaction.
52687       */
52688       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52689         rc = sqlite3PagerWrite(pPage1->pDbPage);
52690         if( rc==SQLITE_OK ){
52691           put4byte(&pPage1->aData[28], pBt->nPage);
52692         }
52693       }
52694     }
52695   }
52696
52697
52698 trans_begun:
52699   if( rc==SQLITE_OK && wrflag ){
52700     /* This call makes sure that the pager has the correct number of
52701     ** open savepoints. If the second parameter is greater than 0 and
52702     ** the sub-journal is not already open, then it will be opened here.
52703     */
52704     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52705   }
52706
52707   btreeIntegrity(p);
52708   sqlite3BtreeLeave(p);
52709   return rc;
52710 }
52711
52712 #ifndef SQLITE_OMIT_AUTOVACUUM
52713
52714 /*
52715 ** Set the pointer-map entries for all children of page pPage. Also, if
52716 ** pPage contains cells that point to overflow pages, set the pointer
52717 ** map entries for the overflow pages as well.
52718 */
52719 static int setChildPtrmaps(MemPage *pPage){
52720   int i;                             /* Counter variable */
52721   int nCell;                         /* Number of cells in page pPage */
52722   int rc;                            /* Return code */
52723   BtShared *pBt = pPage->pBt;
52724   u8 isInitOrig = pPage->isInit;
52725   Pgno pgno = pPage->pgno;
52726
52727   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52728   rc = btreeInitPage(pPage);
52729   if( rc!=SQLITE_OK ){
52730     goto set_child_ptrmaps_out;
52731   }
52732   nCell = pPage->nCell;
52733
52734   for(i=0; i<nCell; i++){
52735     u8 *pCell = findCell(pPage, i);
52736
52737     ptrmapPutOvflPtr(pPage, pCell, &rc);
52738
52739     if( !pPage->leaf ){
52740       Pgno childPgno = get4byte(pCell);
52741       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52742     }
52743   }
52744
52745   if( !pPage->leaf ){
52746     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52747     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52748   }
52749
52750 set_child_ptrmaps_out:
52751   pPage->isInit = isInitOrig;
52752   return rc;
52753 }
52754
52755 /*
52756 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52757 ** that it points to iTo. Parameter eType describes the type of pointer to
52758 ** be modified, as  follows:
52759 **
52760 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
52761 **                   page of pPage.
52762 **
52763 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52764 **                   page pointed to by one of the cells on pPage.
52765 **
52766 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52767 **                   overflow page in the list.
52768 */
52769 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52770   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52771   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52772   if( eType==PTRMAP_OVERFLOW2 ){
52773     /* The pointer is always the first 4 bytes of the page in this case.  */
52774     if( get4byte(pPage->aData)!=iFrom ){
52775       return SQLITE_CORRUPT_BKPT;
52776     }
52777     put4byte(pPage->aData, iTo);
52778   }else{
52779     u8 isInitOrig = pPage->isInit;
52780     int i;
52781     int nCell;
52782
52783     btreeInitPage(pPage);
52784     nCell = pPage->nCell;
52785
52786     for(i=0; i<nCell; i++){
52787       u8 *pCell = findCell(pPage, i);
52788       if( eType==PTRMAP_OVERFLOW1 ){
52789         CellInfo info;
52790         btreeParseCellPtr(pPage, pCell, &info);
52791         if( info.iOverflow
52792          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52793          && iFrom==get4byte(&pCell[info.iOverflow])
52794         ){
52795           put4byte(&pCell[info.iOverflow], iTo);
52796           break;
52797         }
52798       }else{
52799         if( get4byte(pCell)==iFrom ){
52800           put4byte(pCell, iTo);
52801           break;
52802         }
52803       }
52804     }
52805
52806     if( i==nCell ){
52807       if( eType!=PTRMAP_BTREE ||
52808           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52809         return SQLITE_CORRUPT_BKPT;
52810       }
52811       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52812     }
52813
52814     pPage->isInit = isInitOrig;
52815   }
52816   return SQLITE_OK;
52817 }
52818
52819
52820 /*
52821 ** Move the open database page pDbPage to location iFreePage in the
52822 ** database. The pDbPage reference remains valid.
52823 **
52824 ** The isCommit flag indicates that there is no need to remember that
52825 ** the journal needs to be sync()ed before database page pDbPage->pgno
52826 ** can be written to. The caller has already promised not to write to that
52827 ** page.
52828 */
52829 static int relocatePage(
52830   BtShared *pBt,           /* Btree */
52831   MemPage *pDbPage,        /* Open page to move */
52832   u8 eType,                /* Pointer map 'type' entry for pDbPage */
52833   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
52834   Pgno iFreePage,          /* The location to move pDbPage to */
52835   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
52836 ){
52837   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
52838   Pgno iDbPage = pDbPage->pgno;
52839   Pager *pPager = pBt->pPager;
52840   int rc;
52841
52842   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
52843       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52844   assert( sqlite3_mutex_held(pBt->mutex) );
52845   assert( pDbPage->pBt==pBt );
52846
52847   /* Move page iDbPage from its current location to page number iFreePage */
52848   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
52849       iDbPage, iFreePage, iPtrPage, eType));
52850   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52851   if( rc!=SQLITE_OK ){
52852     return rc;
52853   }
52854   pDbPage->pgno = iFreePage;
52855
52856   /* If pDbPage was a btree-page, then it may have child pages and/or cells
52857   ** that point to overflow pages. The pointer map entries for all these
52858   ** pages need to be changed.
52859   **
52860   ** If pDbPage is an overflow page, then the first 4 bytes may store a
52861   ** pointer to a subsequent overflow page. If this is the case, then
52862   ** the pointer map needs to be updated for the subsequent overflow page.
52863   */
52864   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52865     rc = setChildPtrmaps(pDbPage);
52866     if( rc!=SQLITE_OK ){
52867       return rc;
52868     }
52869   }else{
52870     Pgno nextOvfl = get4byte(pDbPage->aData);
52871     if( nextOvfl!=0 ){
52872       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52873       if( rc!=SQLITE_OK ){
52874         return rc;
52875       }
52876     }
52877   }
52878
52879   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52880   ** that it points at iFreePage. Also fix the pointer map entry for
52881   ** iPtrPage.
52882   */
52883   if( eType!=PTRMAP_ROOTPAGE ){
52884     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
52885     if( rc!=SQLITE_OK ){
52886       return rc;
52887     }
52888     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
52889     if( rc!=SQLITE_OK ){
52890       releasePage(pPtrPage);
52891       return rc;
52892     }
52893     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52894     releasePage(pPtrPage);
52895     if( rc==SQLITE_OK ){
52896       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52897     }
52898   }
52899   return rc;
52900 }
52901
52902 /* Forward declaration required by incrVacuumStep(). */
52903 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52904
52905 /*
52906 ** Perform a single step of an incremental-vacuum. If successful,
52907 ** return SQLITE_OK. If there is no work to do (and therefore no
52908 ** point in calling this function again), return SQLITE_DONE.
52909 **
52910 ** More specificly, this function attempts to re-organize the
52911 ** database so that the last page of the file currently in use
52912 ** is no longer in use.
52913 **
52914 ** If the nFin parameter is non-zero, this function assumes
52915 ** that the caller will keep calling incrVacuumStep() until
52916 ** it returns SQLITE_DONE or an error, and that nFin is the
52917 ** number of pages the database file will contain after this
52918 ** process is complete.  If nFin is zero, it is assumed that
52919 ** incrVacuumStep() will be called a finite amount of times
52920 ** which may or may not empty the freelist.  A full autovacuum
52921 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
52922 */
52923 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
52924   Pgno nFreeList;           /* Number of pages still on the free-list */
52925   int rc;
52926
52927   assert( sqlite3_mutex_held(pBt->mutex) );
52928   assert( iLastPg>nFin );
52929
52930   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52931     u8 eType;
52932     Pgno iPtrPage;
52933
52934     nFreeList = get4byte(&pBt->pPage1->aData[36]);
52935     if( nFreeList==0 ){
52936       return SQLITE_DONE;
52937     }
52938
52939     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52940     if( rc!=SQLITE_OK ){
52941       return rc;
52942     }
52943     if( eType==PTRMAP_ROOTPAGE ){
52944       return SQLITE_CORRUPT_BKPT;
52945     }
52946
52947     if( eType==PTRMAP_FREEPAGE ){
52948       if( nFin==0 ){
52949         /* Remove the page from the files free-list. This is not required
52950         ** if nFin is non-zero. In that case, the free-list will be
52951         ** truncated to zero after this function returns, so it doesn't
52952         ** matter if it still contains some garbage entries.
52953         */
52954         Pgno iFreePg;
52955         MemPage *pFreePg;
52956         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
52957         if( rc!=SQLITE_OK ){
52958           return rc;
52959         }
52960         assert( iFreePg==iLastPg );
52961         releasePage(pFreePg);
52962       }
52963     } else {
52964       Pgno iFreePg;             /* Index of free page to move pLastPg to */
52965       MemPage *pLastPg;
52966
52967       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
52968       if( rc!=SQLITE_OK ){
52969         return rc;
52970       }
52971
52972       /* If nFin is zero, this loop runs exactly once and page pLastPg
52973       ** is swapped with the first free page pulled off the free list.
52974       **
52975       ** On the other hand, if nFin is greater than zero, then keep
52976       ** looping until a free-page located within the first nFin pages
52977       ** of the file is found.
52978       */
52979       do {
52980         MemPage *pFreePg;
52981         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
52982         if( rc!=SQLITE_OK ){
52983           releasePage(pLastPg);
52984           return rc;
52985         }
52986         releasePage(pFreePg);
52987       }while( nFin!=0 && iFreePg>nFin );
52988       assert( iFreePg<iLastPg );
52989
52990       rc = sqlite3PagerWrite(pLastPg->pDbPage);
52991       if( rc==SQLITE_OK ){
52992         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
52993       }
52994       releasePage(pLastPg);
52995       if( rc!=SQLITE_OK ){
52996         return rc;
52997       }
52998     }
52999   }
53000
53001   if( nFin==0 ){
53002     iLastPg--;
53003     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
53004       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
53005         MemPage *pPg;
53006         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
53007         if( rc!=SQLITE_OK ){
53008           return rc;
53009         }
53010         rc = sqlite3PagerWrite(pPg->pDbPage);
53011         releasePage(pPg);
53012         if( rc!=SQLITE_OK ){
53013           return rc;
53014         }
53015       }
53016       iLastPg--;
53017     }
53018     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
53019     pBt->nPage = iLastPg;
53020   }
53021   return SQLITE_OK;
53022 }
53023
53024 /*
53025 ** A write-transaction must be opened before calling this function.
53026 ** It performs a single unit of work towards an incremental vacuum.
53027 **
53028 ** If the incremental vacuum is finished after this function has run,
53029 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
53030 ** SQLITE_OK is returned. Otherwise an SQLite error code.
53031 */
53032 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
53033   int rc;
53034   BtShared *pBt = p->pBt;
53035
53036   sqlite3BtreeEnter(p);
53037   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
53038   if( !pBt->autoVacuum ){
53039     rc = SQLITE_DONE;
53040   }else{
53041     invalidateAllOverflowCache(pBt);
53042     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
53043     if( rc==SQLITE_OK ){
53044       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53045       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
53046     }
53047   }
53048   sqlite3BtreeLeave(p);
53049   return rc;
53050 }
53051
53052 /*
53053 ** This routine is called prior to sqlite3PagerCommit when a transaction
53054 ** is commited for an auto-vacuum database.
53055 **
53056 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
53057 ** the database file should be truncated to during the commit process.
53058 ** i.e. the database has been reorganized so that only the first *pnTrunc
53059 ** pages are in use.
53060 */
53061 static int autoVacuumCommit(BtShared *pBt){
53062   int rc = SQLITE_OK;
53063   Pager *pPager = pBt->pPager;
53064   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
53065
53066   assert( sqlite3_mutex_held(pBt->mutex) );
53067   invalidateAllOverflowCache(pBt);
53068   assert(pBt->autoVacuum);
53069   if( !pBt->incrVacuum ){
53070     Pgno nFin;         /* Number of pages in database after autovacuuming */
53071     Pgno nFree;        /* Number of pages on the freelist initially */
53072     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
53073     Pgno iFree;        /* The next page to be freed */
53074     int nEntry;        /* Number of entries on one ptrmap page */
53075     Pgno nOrig;        /* Database size before freeing */
53076
53077     nOrig = btreePagecount(pBt);
53078     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
53079       /* It is not possible to create a database for which the final page
53080       ** is either a pointer-map page or the pending-byte page. If one
53081       ** is encountered, this indicates corruption.
53082       */
53083       return SQLITE_CORRUPT_BKPT;
53084     }
53085
53086     nFree = get4byte(&pBt->pPage1->aData[36]);
53087     nEntry = pBt->usableSize/5;
53088     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
53089     nFin = nOrig - nFree - nPtrmap;
53090     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
53091       nFin--;
53092     }
53093     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
53094       nFin--;
53095     }
53096     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
53097
53098     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
53099       rc = incrVacuumStep(pBt, nFin, iFree);
53100     }
53101     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
53102       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53103       put4byte(&pBt->pPage1->aData[32], 0);
53104       put4byte(&pBt->pPage1->aData[36], 0);
53105       put4byte(&pBt->pPage1->aData[28], nFin);
53106       sqlite3PagerTruncateImage(pBt->pPager, nFin);
53107       pBt->nPage = nFin;
53108     }
53109     if( rc!=SQLITE_OK ){
53110       sqlite3PagerRollback(pPager);
53111     }
53112   }
53113
53114   assert( nRef==sqlite3PagerRefcount(pPager) );
53115   return rc;
53116 }
53117
53118 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
53119 # define setChildPtrmaps(x) SQLITE_OK
53120 #endif
53121
53122 /*
53123 ** This routine does the first phase of a two-phase commit.  This routine
53124 ** causes a rollback journal to be created (if it does not already exist)
53125 ** and populated with enough information so that if a power loss occurs
53126 ** the database can be restored to its original state by playing back
53127 ** the journal.  Then the contents of the journal are flushed out to
53128 ** the disk.  After the journal is safely on oxide, the changes to the
53129 ** database are written into the database file and flushed to oxide.
53130 ** At the end of this call, the rollback journal still exists on the
53131 ** disk and we are still holding all locks, so the transaction has not
53132 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
53133 ** commit process.
53134 **
53135 ** This call is a no-op if no write-transaction is currently active on pBt.
53136 **
53137 ** Otherwise, sync the database file for the btree pBt. zMaster points to
53138 ** the name of a master journal file that should be written into the
53139 ** individual journal file, or is NULL, indicating no master journal file
53140 ** (single database transaction).
53141 **
53142 ** When this is called, the master journal should already have been
53143 ** created, populated with this journal pointer and synced to disk.
53144 **
53145 ** Once this is routine has returned, the only thing required to commit
53146 ** the write-transaction for this database file is to delete the journal.
53147 */
53148 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
53149   int rc = SQLITE_OK;
53150   if( p->inTrans==TRANS_WRITE ){
53151     BtShared *pBt = p->pBt;
53152     sqlite3BtreeEnter(p);
53153 #ifndef SQLITE_OMIT_AUTOVACUUM
53154     if( pBt->autoVacuum ){
53155       rc = autoVacuumCommit(pBt);
53156       if( rc!=SQLITE_OK ){
53157         sqlite3BtreeLeave(p);
53158         return rc;
53159       }
53160     }
53161 #endif
53162     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
53163     sqlite3BtreeLeave(p);
53164   }
53165   return rc;
53166 }
53167
53168 /*
53169 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
53170 ** at the conclusion of a transaction.
53171 */
53172 static void btreeEndTransaction(Btree *p){
53173   BtShared *pBt = p->pBt;
53174   assert( sqlite3BtreeHoldsMutex(p) );
53175
53176   btreeClearHasContent(pBt);
53177   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
53178     /* If there are other active statements that belong to this database
53179     ** handle, downgrade to a read-only transaction. The other statements
53180     ** may still be reading from the database.  */
53181     downgradeAllSharedCacheTableLocks(p);
53182     p->inTrans = TRANS_READ;
53183   }else{
53184     /* If the handle had any kind of transaction open, decrement the
53185     ** transaction count of the shared btree. If the transaction count
53186     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
53187     ** call below will unlock the pager.  */
53188     if( p->inTrans!=TRANS_NONE ){
53189       clearAllSharedCacheTableLocks(p);
53190       pBt->nTransaction--;
53191       if( 0==pBt->nTransaction ){
53192         pBt->inTransaction = TRANS_NONE;
53193       }
53194     }
53195
53196     /* Set the current transaction state to TRANS_NONE and unlock the
53197     ** pager if this call closed the only read or write transaction.  */
53198     p->inTrans = TRANS_NONE;
53199     unlockBtreeIfUnused(pBt);
53200   }
53201
53202   btreeIntegrity(p);
53203 }
53204
53205 /*
53206 ** Commit the transaction currently in progress.
53207 **
53208 ** This routine implements the second phase of a 2-phase commit.  The
53209 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
53210 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
53211 ** routine did all the work of writing information out to disk and flushing the
53212 ** contents so that they are written onto the disk platter.  All this
53213 ** routine has to do is delete or truncate or zero the header in the
53214 ** the rollback journal (which causes the transaction to commit) and
53215 ** drop locks.
53216 **
53217 ** Normally, if an error occurs while the pager layer is attempting to
53218 ** finalize the underlying journal file, this function returns an error and
53219 ** the upper layer will attempt a rollback. However, if the second argument
53220 ** is non-zero then this b-tree transaction is part of a multi-file
53221 ** transaction. In this case, the transaction has already been committed
53222 ** (by deleting a master journal file) and the caller will ignore this
53223 ** functions return code. So, even if an error occurs in the pager layer,
53224 ** reset the b-tree objects internal state to indicate that the write
53225 ** transaction has been closed. This is quite safe, as the pager will have
53226 ** transitioned to the error state.
53227 **
53228 ** This will release the write lock on the database file.  If there
53229 ** are no active cursors, it also releases the read lock.
53230 */
53231 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
53232
53233   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
53234   sqlite3BtreeEnter(p);
53235   btreeIntegrity(p);
53236
53237   /* If the handle has a write-transaction open, commit the shared-btrees
53238   ** transaction and set the shared state to TRANS_READ.
53239   */
53240   if( p->inTrans==TRANS_WRITE ){
53241     int rc;
53242     BtShared *pBt = p->pBt;
53243     assert( pBt->inTransaction==TRANS_WRITE );
53244     assert( pBt->nTransaction>0 );
53245     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
53246     if( rc!=SQLITE_OK && bCleanup==0 ){
53247       sqlite3BtreeLeave(p);
53248       return rc;
53249     }
53250     pBt->inTransaction = TRANS_READ;
53251   }
53252
53253   btreeEndTransaction(p);
53254   sqlite3BtreeLeave(p);
53255   return SQLITE_OK;
53256 }
53257
53258 /*
53259 ** Do both phases of a commit.
53260 */
53261 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
53262   int rc;
53263   sqlite3BtreeEnter(p);
53264   rc = sqlite3BtreeCommitPhaseOne(p, 0);
53265   if( rc==SQLITE_OK ){
53266     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
53267   }
53268   sqlite3BtreeLeave(p);
53269   return rc;
53270 }
53271
53272 #ifndef NDEBUG
53273 /*
53274 ** Return the number of write-cursors open on this handle. This is for use
53275 ** in assert() expressions, so it is only compiled if NDEBUG is not
53276 ** defined.
53277 **
53278 ** For the purposes of this routine, a write-cursor is any cursor that
53279 ** is capable of writing to the databse.  That means the cursor was
53280 ** originally opened for writing and the cursor has not be disabled
53281 ** by having its state changed to CURSOR_FAULT.
53282 */
53283 static int countWriteCursors(BtShared *pBt){
53284   BtCursor *pCur;
53285   int r = 0;
53286   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
53287     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
53288   }
53289   return r;
53290 }
53291 #endif
53292
53293 /*
53294 ** This routine sets the state to CURSOR_FAULT and the error
53295 ** code to errCode for every cursor on BtShared that pBtree
53296 ** references.
53297 **
53298 ** Every cursor is tripped, including cursors that belong
53299 ** to other database connections that happen to be sharing
53300 ** the cache with pBtree.
53301 **
53302 ** This routine gets called when a rollback occurs.
53303 ** All cursors using the same cache must be tripped
53304 ** to prevent them from trying to use the btree after
53305 ** the rollback.  The rollback may have deleted tables
53306 ** or moved root pages, so it is not sufficient to
53307 ** save the state of the cursor.  The cursor must be
53308 ** invalidated.
53309 */
53310 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
53311   BtCursor *p;
53312   if( pBtree==0 ) return;
53313   sqlite3BtreeEnter(pBtree);
53314   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
53315     int i;
53316     sqlite3BtreeClearCursor(p);
53317     p->eState = CURSOR_FAULT;
53318     p->skipNext = errCode;
53319     for(i=0; i<=p->iPage; i++){
53320       releasePage(p->apPage[i]);
53321       p->apPage[i] = 0;
53322     }
53323   }
53324   sqlite3BtreeLeave(pBtree);
53325 }
53326
53327 /*
53328 ** Rollback the transaction in progress.  All cursors will be
53329 ** invalided by this operation.  Any attempt to use a cursor
53330 ** that was open at the beginning of this operation will result
53331 ** in an error.
53332 **
53333 ** This will release the write lock on the database file.  If there
53334 ** are no active cursors, it also releases the read lock.
53335 */
53336 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
53337   int rc;
53338   BtShared *pBt = p->pBt;
53339   MemPage *pPage1;
53340
53341   sqlite3BtreeEnter(p);
53342   if( tripCode==SQLITE_OK ){
53343     rc = tripCode = saveAllCursors(pBt, 0, 0);
53344   }else{
53345     rc = SQLITE_OK;
53346   }
53347   if( tripCode ){
53348     sqlite3BtreeTripAllCursors(p, tripCode);
53349   }
53350   btreeIntegrity(p);
53351
53352   if( p->inTrans==TRANS_WRITE ){
53353     int rc2;
53354
53355     assert( TRANS_WRITE==pBt->inTransaction );
53356     rc2 = sqlite3PagerRollback(pBt->pPager);
53357     if( rc2!=SQLITE_OK ){
53358       rc = rc2;
53359     }
53360
53361     /* The rollback may have destroyed the pPage1->aData value.  So
53362     ** call btreeGetPage() on page 1 again to make
53363     ** sure pPage1->aData is set correctly. */
53364     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
53365       int nPage = get4byte(28+(u8*)pPage1->aData);
53366       testcase( nPage==0 );
53367       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
53368       testcase( pBt->nPage!=nPage );
53369       pBt->nPage = nPage;
53370       releasePage(pPage1);
53371     }
53372     assert( countWriteCursors(pBt)==0 );
53373     pBt->inTransaction = TRANS_READ;
53374   }
53375
53376   btreeEndTransaction(p);
53377   sqlite3BtreeLeave(p);
53378   return rc;
53379 }
53380
53381 /*
53382 ** Start a statement subtransaction. The subtransaction can can be rolled
53383 ** back independently of the main transaction. You must start a transaction
53384 ** before starting a subtransaction. The subtransaction is ended automatically
53385 ** if the main transaction commits or rolls back.
53386 **
53387 ** Statement subtransactions are used around individual SQL statements
53388 ** that are contained within a BEGIN...COMMIT block.  If a constraint
53389 ** error occurs within the statement, the effect of that one statement
53390 ** can be rolled back without having to rollback the entire transaction.
53391 **
53392 ** A statement sub-transaction is implemented as an anonymous savepoint. The
53393 ** value passed as the second parameter is the total number of savepoints,
53394 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
53395 ** are no active savepoints and no other statement-transactions open,
53396 ** iStatement is 1. This anonymous savepoint can be released or rolled back
53397 ** using the sqlite3BtreeSavepoint() function.
53398 */
53399 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
53400   int rc;
53401   BtShared *pBt = p->pBt;
53402   sqlite3BtreeEnter(p);
53403   assert( p->inTrans==TRANS_WRITE );
53404   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
53405   assert( iStatement>0 );
53406   assert( iStatement>p->db->nSavepoint );
53407   assert( pBt->inTransaction==TRANS_WRITE );
53408   /* At the pager level, a statement transaction is a savepoint with
53409   ** an index greater than all savepoints created explicitly using
53410   ** SQL statements. It is illegal to open, release or rollback any
53411   ** such savepoints while the statement transaction savepoint is active.
53412   */
53413   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
53414   sqlite3BtreeLeave(p);
53415   return rc;
53416 }
53417
53418 /*
53419 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
53420 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
53421 ** savepoint identified by parameter iSavepoint, depending on the value
53422 ** of op.
53423 **
53424 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
53425 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
53426 ** contents of the entire transaction are rolled back. This is different
53427 ** from a normal transaction rollback, as no locks are released and the
53428 ** transaction remains open.
53429 */
53430 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
53431   int rc = SQLITE_OK;
53432   if( p && p->inTrans==TRANS_WRITE ){
53433     BtShared *pBt = p->pBt;
53434     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53435     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
53436     sqlite3BtreeEnter(p);
53437     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
53438     if( rc==SQLITE_OK ){
53439       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
53440         pBt->nPage = 0;
53441       }
53442       rc = newDatabase(pBt);
53443       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
53444
53445       /* The database size was written into the offset 28 of the header
53446       ** when the transaction started, so we know that the value at offset
53447       ** 28 is nonzero. */
53448       assert( pBt->nPage>0 );
53449     }
53450     sqlite3BtreeLeave(p);
53451   }
53452   return rc;
53453 }
53454
53455 /*
53456 ** Create a new cursor for the BTree whose root is on the page
53457 ** iTable. If a read-only cursor is requested, it is assumed that
53458 ** the caller already has at least a read-only transaction open
53459 ** on the database already. If a write-cursor is requested, then
53460 ** the caller is assumed to have an open write transaction.
53461 **
53462 ** If wrFlag==0, then the cursor can only be used for reading.
53463 ** If wrFlag==1, then the cursor can be used for reading or for
53464 ** writing if other conditions for writing are also met.  These
53465 ** are the conditions that must be met in order for writing to
53466 ** be allowed:
53467 **
53468 ** 1:  The cursor must have been opened with wrFlag==1
53469 **
53470 ** 2:  Other database connections that share the same pager cache
53471 **     but which are not in the READ_UNCOMMITTED state may not have
53472 **     cursors open with wrFlag==0 on the same table.  Otherwise
53473 **     the changes made by this write cursor would be visible to
53474 **     the read cursors in the other database connection.
53475 **
53476 ** 3:  The database must be writable (not on read-only media)
53477 **
53478 ** 4:  There must be an active transaction.
53479 **
53480 ** No checking is done to make sure that page iTable really is the
53481 ** root page of a b-tree.  If it is not, then the cursor acquired
53482 ** will not work correctly.
53483 **
53484 ** It is assumed that the sqlite3BtreeCursorZero() has been called
53485 ** on pCur to initialize the memory space prior to invoking this routine.
53486 */
53487 static int btreeCursor(
53488   Btree *p,                              /* The btree */
53489   int iTable,                            /* Root page of table to open */
53490   int wrFlag,                            /* 1 to write. 0 read-only */
53491   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
53492   BtCursor *pCur                         /* Space for new cursor */
53493 ){
53494   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
53495
53496   assert( sqlite3BtreeHoldsMutex(p) );
53497   assert( wrFlag==0 || wrFlag==1 );
53498
53499   /* The following assert statements verify that if this is a sharable
53500   ** b-tree database, the connection is holding the required table locks,
53501   ** and that no other connection has any open cursor that conflicts with
53502   ** this lock.  */
53503   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
53504   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
53505
53506   /* Assert that the caller has opened the required transaction. */
53507   assert( p->inTrans>TRANS_NONE );
53508   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
53509   assert( pBt->pPage1 && pBt->pPage1->aData );
53510
53511   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
53512     return SQLITE_READONLY;
53513   }
53514   if( iTable==1 && btreePagecount(pBt)==0 ){
53515     assert( wrFlag==0 );
53516     iTable = 0;
53517   }
53518
53519   /* Now that no other errors can occur, finish filling in the BtCursor
53520   ** variables and link the cursor into the BtShared list.  */
53521   pCur->pgnoRoot = (Pgno)iTable;
53522   pCur->iPage = -1;
53523   pCur->pKeyInfo = pKeyInfo;
53524   pCur->pBtree = p;
53525   pCur->pBt = pBt;
53526   pCur->wrFlag = (u8)wrFlag;
53527   pCur->pNext = pBt->pCursor;
53528   if( pCur->pNext ){
53529     pCur->pNext->pPrev = pCur;
53530   }
53531   pBt->pCursor = pCur;
53532   pCur->eState = CURSOR_INVALID;
53533   pCur->cachedRowid = 0;
53534   return SQLITE_OK;
53535 }
53536 SQLITE_PRIVATE int sqlite3BtreeCursor(
53537   Btree *p,                                   /* The btree */
53538   int iTable,                                 /* Root page of table to open */
53539   int wrFlag,                                 /* 1 to write. 0 read-only */
53540   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
53541   BtCursor *pCur                              /* Write new cursor here */
53542 ){
53543   int rc;
53544   sqlite3BtreeEnter(p);
53545   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
53546   sqlite3BtreeLeave(p);
53547   return rc;
53548 }
53549
53550 /*
53551 ** Return the size of a BtCursor object in bytes.
53552 **
53553 ** This interfaces is needed so that users of cursors can preallocate
53554 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
53555 ** to users so they cannot do the sizeof() themselves - they must call
53556 ** this routine.
53557 */
53558 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
53559   return ROUND8(sizeof(BtCursor));
53560 }
53561
53562 /*
53563 ** Initialize memory that will be converted into a BtCursor object.
53564 **
53565 ** The simple approach here would be to memset() the entire object
53566 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
53567 ** do not need to be zeroed and they are large, so we can save a lot
53568 ** of run-time by skipping the initialization of those elements.
53569 */
53570 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
53571   memset(p, 0, offsetof(BtCursor, iPage));
53572 }
53573
53574 /*
53575 ** Set the cached rowid value of every cursor in the same database file
53576 ** as pCur and having the same root page number as pCur.  The value is
53577 ** set to iRowid.
53578 **
53579 ** Only positive rowid values are considered valid for this cache.
53580 ** The cache is initialized to zero, indicating an invalid cache.
53581 ** A btree will work fine with zero or negative rowids.  We just cannot
53582 ** cache zero or negative rowids, which means tables that use zero or
53583 ** negative rowids might run a little slower.  But in practice, zero
53584 ** or negative rowids are very uncommon so this should not be a problem.
53585 */
53586 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
53587   BtCursor *p;
53588   for(p=pCur->pBt->pCursor; p; p=p->pNext){
53589     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
53590   }
53591   assert( pCur->cachedRowid==iRowid );
53592 }
53593
53594 /*
53595 ** Return the cached rowid for the given cursor.  A negative or zero
53596 ** return value indicates that the rowid cache is invalid and should be
53597 ** ignored.  If the rowid cache has never before been set, then a
53598 ** zero is returned.
53599 */
53600 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
53601   return pCur->cachedRowid;
53602 }
53603
53604 /*
53605 ** Close a cursor.  The read lock on the database file is released
53606 ** when the last cursor is closed.
53607 */
53608 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
53609   Btree *pBtree = pCur->pBtree;
53610   if( pBtree ){
53611     int i;
53612     BtShared *pBt = pCur->pBt;
53613     sqlite3BtreeEnter(pBtree);
53614     sqlite3BtreeClearCursor(pCur);
53615     if( pCur->pPrev ){
53616       pCur->pPrev->pNext = pCur->pNext;
53617     }else{
53618       pBt->pCursor = pCur->pNext;
53619     }
53620     if( pCur->pNext ){
53621       pCur->pNext->pPrev = pCur->pPrev;
53622     }
53623     for(i=0; i<=pCur->iPage; i++){
53624       releasePage(pCur->apPage[i]);
53625     }
53626     unlockBtreeIfUnused(pBt);
53627     invalidateOverflowCache(pCur);
53628     /* sqlite3_free(pCur); */
53629     sqlite3BtreeLeave(pBtree);
53630   }
53631   return SQLITE_OK;
53632 }
53633
53634 /*
53635 ** Make sure the BtCursor* given in the argument has a valid
53636 ** BtCursor.info structure.  If it is not already valid, call
53637 ** btreeParseCell() to fill it in.
53638 **
53639 ** BtCursor.info is a cache of the information in the current cell.
53640 ** Using this cache reduces the number of calls to btreeParseCell().
53641 **
53642 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
53643 ** compiler to crash when getCellInfo() is implemented as a macro.
53644 ** But there is a measureable speed advantage to using the macro on gcc
53645 ** (when less compiler optimizations like -Os or -O0 are used and the
53646 ** compiler is not doing agressive inlining.)  So we use a real function
53647 ** for MSVC and a macro for everything else.  Ticket #2457.
53648 */
53649 #ifndef NDEBUG
53650   static void assertCellInfo(BtCursor *pCur){
53651     CellInfo info;
53652     int iPage = pCur->iPage;
53653     memset(&info, 0, sizeof(info));
53654     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53655     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53656   }
53657 #else
53658   #define assertCellInfo(x)
53659 #endif
53660 #ifdef _MSC_VER
53661   /* Use a real function in MSVC to work around bugs in that compiler. */
53662   static void getCellInfo(BtCursor *pCur){
53663     if( pCur->info.nSize==0 ){
53664       int iPage = pCur->iPage;
53665       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53666       pCur->validNKey = 1;
53667     }else{
53668       assertCellInfo(pCur);
53669     }
53670   }
53671 #else /* if not _MSC_VER */
53672   /* Use a macro in all other compilers so that the function is inlined */
53673 #define getCellInfo(pCur)                                                      \
53674   if( pCur->info.nSize==0 ){                                                   \
53675     int iPage = pCur->iPage;                                                   \
53676     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53677     pCur->validNKey = 1;                                                       \
53678   }else{                                                                       \
53679     assertCellInfo(pCur);                                                      \
53680   }
53681 #endif /* _MSC_VER */
53682
53683 #ifndef NDEBUG  /* The next routine used only within assert() statements */
53684 /*
53685 ** Return true if the given BtCursor is valid.  A valid cursor is one
53686 ** that is currently pointing to a row in a (non-empty) table.
53687 ** This is a verification routine is used only within assert() statements.
53688 */
53689 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
53690   return pCur && pCur->eState==CURSOR_VALID;
53691 }
53692 #endif /* NDEBUG */
53693
53694 /*
53695 ** Set *pSize to the size of the buffer needed to hold the value of
53696 ** the key for the current entry.  If the cursor is not pointing
53697 ** to a valid entry, *pSize is set to 0.
53698 **
53699 ** For a table with the INTKEY flag set, this routine returns the key
53700 ** itself, not the number of bytes in the key.
53701 **
53702 ** The caller must position the cursor prior to invoking this routine.
53703 **
53704 ** This routine cannot fail.  It always returns SQLITE_OK.
53705 */
53706 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53707   assert( cursorHoldsMutex(pCur) );
53708   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53709   if( pCur->eState!=CURSOR_VALID ){
53710     *pSize = 0;
53711   }else{
53712     getCellInfo(pCur);
53713     *pSize = pCur->info.nKey;
53714   }
53715   return SQLITE_OK;
53716 }
53717
53718 /*
53719 ** Set *pSize to the number of bytes of data in the entry the
53720 ** cursor currently points to.
53721 **
53722 ** The caller must guarantee that the cursor is pointing to a non-NULL
53723 ** valid entry.  In other words, the calling procedure must guarantee
53724 ** that the cursor has Cursor.eState==CURSOR_VALID.
53725 **
53726 ** Failure is not possible.  This function always returns SQLITE_OK.
53727 ** It might just as well be a procedure (returning void) but we continue
53728 ** to return an integer result code for historical reasons.
53729 */
53730 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53731   assert( cursorHoldsMutex(pCur) );
53732   assert( pCur->eState==CURSOR_VALID );
53733   getCellInfo(pCur);
53734   *pSize = pCur->info.nData;
53735   return SQLITE_OK;
53736 }
53737
53738 /*
53739 ** Given the page number of an overflow page in the database (parameter
53740 ** ovfl), this function finds the page number of the next page in the
53741 ** linked list of overflow pages. If possible, it uses the auto-vacuum
53742 ** pointer-map data instead of reading the content of page ovfl to do so.
53743 **
53744 ** If an error occurs an SQLite error code is returned. Otherwise:
53745 **
53746 ** The page number of the next overflow page in the linked list is
53747 ** written to *pPgnoNext. If page ovfl is the last page in its linked
53748 ** list, *pPgnoNext is set to zero.
53749 **
53750 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
53751 ** to page number pOvfl was obtained, then *ppPage is set to point to that
53752 ** reference. It is the responsibility of the caller to call releasePage()
53753 ** on *ppPage to free the reference. In no reference was obtained (because
53754 ** the pointer-map was used to obtain the value for *pPgnoNext), then
53755 ** *ppPage is set to zero.
53756 */
53757 static int getOverflowPage(
53758   BtShared *pBt,               /* The database file */
53759   Pgno ovfl,                   /* Current overflow page number */
53760   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53761   Pgno *pPgnoNext              /* OUT: Next overflow page number */
53762 ){
53763   Pgno next = 0;
53764   MemPage *pPage = 0;
53765   int rc = SQLITE_OK;
53766
53767   assert( sqlite3_mutex_held(pBt->mutex) );
53768   assert(pPgnoNext);
53769
53770 #ifndef SQLITE_OMIT_AUTOVACUUM
53771   /* Try to find the next page in the overflow list using the
53772   ** autovacuum pointer-map pages. Guess that the next page in
53773   ** the overflow list is page number (ovfl+1). If that guess turns
53774   ** out to be wrong, fall back to loading the data of page
53775   ** number ovfl to determine the next page number.
53776   */
53777   if( pBt->autoVacuum ){
53778     Pgno pgno;
53779     Pgno iGuess = ovfl+1;
53780     u8 eType;
53781
53782     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53783       iGuess++;
53784     }
53785
53786     if( iGuess<=btreePagecount(pBt) ){
53787       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53788       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53789         next = iGuess;
53790         rc = SQLITE_DONE;
53791       }
53792     }
53793   }
53794 #endif
53795
53796   assert( next==0 || rc==SQLITE_DONE );
53797   if( rc==SQLITE_OK ){
53798     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
53799     assert( rc==SQLITE_OK || pPage==0 );
53800     if( rc==SQLITE_OK ){
53801       next = get4byte(pPage->aData);
53802     }
53803   }
53804
53805   *pPgnoNext = next;
53806   if( ppPage ){
53807     *ppPage = pPage;
53808   }else{
53809     releasePage(pPage);
53810   }
53811   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
53812 }
53813
53814 /*
53815 ** Copy data from a buffer to a page, or from a page to a buffer.
53816 **
53817 ** pPayload is a pointer to data stored on database page pDbPage.
53818 ** If argument eOp is false, then nByte bytes of data are copied
53819 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53820 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
53821 ** of data are copied from the buffer pBuf to pPayload.
53822 **
53823 ** SQLITE_OK is returned on success, otherwise an error code.
53824 */
53825 static int copyPayload(
53826   void *pPayload,           /* Pointer to page data */
53827   void *pBuf,               /* Pointer to buffer */
53828   int nByte,                /* Number of bytes to copy */
53829   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
53830   DbPage *pDbPage           /* Page containing pPayload */
53831 ){
53832   if( eOp ){
53833     /* Copy data from buffer to page (a write operation) */
53834     int rc = sqlite3PagerWrite(pDbPage);
53835     if( rc!=SQLITE_OK ){
53836       return rc;
53837     }
53838     memcpy(pPayload, pBuf, nByte);
53839   }else{
53840     /* Copy data from page to buffer (a read operation) */
53841     memcpy(pBuf, pPayload, nByte);
53842   }
53843   return SQLITE_OK;
53844 }
53845
53846 /*
53847 ** This function is used to read or overwrite payload information
53848 ** for the entry that the pCur cursor is pointing to. If the eOp
53849 ** parameter is 0, this is a read operation (data copied into
53850 ** buffer pBuf). If it is non-zero, a write (data copied from
53851 ** buffer pBuf).
53852 **
53853 ** A total of "amt" bytes are read or written beginning at "offset".
53854 ** Data is read to or from the buffer pBuf.
53855 **
53856 ** The content being read or written might appear on the main page
53857 ** or be scattered out on multiple overflow pages.
53858 **
53859 ** If the BtCursor.isIncrblobHandle flag is set, and the current
53860 ** cursor entry uses one or more overflow pages, this function
53861 ** allocates space for and lazily popluates the overflow page-list
53862 ** cache array (BtCursor.aOverflow). Subsequent calls use this
53863 ** cache to make seeking to the supplied offset more efficient.
53864 **
53865 ** Once an overflow page-list cache has been allocated, it may be
53866 ** invalidated if some other cursor writes to the same table, or if
53867 ** the cursor is moved to a different row. Additionally, in auto-vacuum
53868 ** mode, the following events may invalidate an overflow page-list cache.
53869 **
53870 **   * An incremental vacuum,
53871 **   * A commit in auto_vacuum="full" mode,
53872 **   * Creating a table (may require moving an overflow page).
53873 */
53874 static int accessPayload(
53875   BtCursor *pCur,      /* Cursor pointing to entry to read from */
53876   u32 offset,          /* Begin reading this far into payload */
53877   u32 amt,             /* Read this many bytes */
53878   unsigned char *pBuf, /* Write the bytes into this buffer */
53879   int eOp              /* zero to read. non-zero to write. */
53880 ){
53881   unsigned char *aPayload;
53882   int rc = SQLITE_OK;
53883   u32 nKey;
53884   int iIdx = 0;
53885   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53886   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
53887
53888   assert( pPage );
53889   assert( pCur->eState==CURSOR_VALID );
53890   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53891   assert( cursorHoldsMutex(pCur) );
53892
53893   getCellInfo(pCur);
53894   aPayload = pCur->info.pCell + pCur->info.nHeader;
53895   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53896
53897   if( NEVER(offset+amt > nKey+pCur->info.nData)
53898    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53899   ){
53900     /* Trying to read or write past the end of the data is an error */
53901     return SQLITE_CORRUPT_BKPT;
53902   }
53903
53904   /* Check if data must be read/written to/from the btree page itself. */
53905   if( offset<pCur->info.nLocal ){
53906     int a = amt;
53907     if( a+offset>pCur->info.nLocal ){
53908       a = pCur->info.nLocal - offset;
53909     }
53910     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53911     offset = 0;
53912     pBuf += a;
53913     amt -= a;
53914   }else{
53915     offset -= pCur->info.nLocal;
53916   }
53917
53918   if( rc==SQLITE_OK && amt>0 ){
53919     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
53920     Pgno nextPage;
53921
53922     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53923
53924 #ifndef SQLITE_OMIT_INCRBLOB
53925     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53926     ** has not been allocated, allocate it now. The array is sized at
53927     ** one entry for each overflow page in the overflow chain. The
53928     ** page number of the first overflow page is stored in aOverflow[0],
53929     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53930     ** (the cache is lazily populated).
53931     */
53932     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53933       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53934       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
53935       /* nOvfl is always positive.  If it were zero, fetchPayload would have
53936       ** been used instead of this routine. */
53937       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53938         rc = SQLITE_NOMEM;
53939       }
53940     }
53941
53942     /* If the overflow page-list cache has been allocated and the
53943     ** entry for the first required overflow page is valid, skip
53944     ** directly to it.
53945     */
53946     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53947       iIdx = (offset/ovflSize);
53948       nextPage = pCur->aOverflow[iIdx];
53949       offset = (offset%ovflSize);
53950     }
53951 #endif
53952
53953     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
53954
53955 #ifndef SQLITE_OMIT_INCRBLOB
53956       /* If required, populate the overflow page-list cache. */
53957       if( pCur->aOverflow ){
53958         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53959         pCur->aOverflow[iIdx] = nextPage;
53960       }
53961 #endif
53962
53963       if( offset>=ovflSize ){
53964         /* The only reason to read this page is to obtain the page
53965         ** number for the next page in the overflow chain. The page
53966         ** data is not required. So first try to lookup the overflow
53967         ** page-list cache, if any, then fall back to the getOverflowPage()
53968         ** function.
53969         */
53970 #ifndef SQLITE_OMIT_INCRBLOB
53971         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53972           nextPage = pCur->aOverflow[iIdx+1];
53973         } else
53974 #endif
53975           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53976         offset -= ovflSize;
53977       }else{
53978         /* Need to read this page properly. It contains some of the
53979         ** range of data that is being read (eOp==0) or written (eOp!=0).
53980         */
53981 #ifdef SQLITE_DIRECT_OVERFLOW_READ
53982         sqlite3_file *fd;
53983 #endif
53984         int a = amt;
53985         if( a + offset > ovflSize ){
53986           a = ovflSize - offset;
53987         }
53988
53989 #ifdef SQLITE_DIRECT_OVERFLOW_READ
53990         /* If all the following are true:
53991         **
53992         **   1) this is a read operation, and
53993         **   2) data is required from the start of this overflow page, and
53994         **   3) the database is file-backed, and
53995         **   4) there is no open write-transaction, and
53996         **   5) the database is not a WAL database,
53997         **
53998         ** then data can be read directly from the database file into the
53999         ** output buffer, bypassing the page-cache altogether. This speeds
54000         ** up loading large records that span many overflow pages.
54001         */
54002         if( eOp==0                                             /* (1) */
54003          && offset==0                                          /* (2) */
54004          && pBt->inTransaction==TRANS_READ                     /* (4) */
54005          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
54006          && pBt->pPage1->aData[19]==0x01                       /* (5) */
54007         ){
54008           u8 aSave[4];
54009           u8 *aWrite = &pBuf[-4];
54010           memcpy(aSave, aWrite, 4);
54011           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
54012           nextPage = get4byte(aWrite);
54013           memcpy(aWrite, aSave, 4);
54014         }else
54015 #endif
54016
54017         {
54018           DbPage *pDbPage;
54019           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
54020           if( rc==SQLITE_OK ){
54021             aPayload = sqlite3PagerGetData(pDbPage);
54022             nextPage = get4byte(aPayload);
54023             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
54024             sqlite3PagerUnref(pDbPage);
54025             offset = 0;
54026           }
54027         }
54028         amt -= a;
54029         pBuf += a;
54030       }
54031     }
54032   }
54033
54034   if( rc==SQLITE_OK && amt>0 ){
54035     return SQLITE_CORRUPT_BKPT;
54036   }
54037   return rc;
54038 }
54039
54040 /*
54041 ** Read part of the key associated with cursor pCur.  Exactly
54042 ** "amt" bytes will be transfered into pBuf[].  The transfer
54043 ** begins at "offset".
54044 **
54045 ** The caller must ensure that pCur is pointing to a valid row
54046 ** in the table.
54047 **
54048 ** Return SQLITE_OK on success or an error code if anything goes
54049 ** wrong.  An error is returned if "offset+amt" is larger than
54050 ** the available payload.
54051 */
54052 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
54053   assert( cursorHoldsMutex(pCur) );
54054   assert( pCur->eState==CURSOR_VALID );
54055   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
54056   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54057   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
54058 }
54059
54060 /*
54061 ** Read part of the data associated with cursor pCur.  Exactly
54062 ** "amt" bytes will be transfered into pBuf[].  The transfer
54063 ** begins at "offset".
54064 **
54065 ** Return SQLITE_OK on success or an error code if anything goes
54066 ** wrong.  An error is returned if "offset+amt" is larger than
54067 ** the available payload.
54068 */
54069 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
54070   int rc;
54071
54072 #ifndef SQLITE_OMIT_INCRBLOB
54073   if ( pCur->eState==CURSOR_INVALID ){
54074     return SQLITE_ABORT;
54075   }
54076 #endif
54077
54078   assert( cursorHoldsMutex(pCur) );
54079   rc = restoreCursorPosition(pCur);
54080   if( rc==SQLITE_OK ){
54081     assert( pCur->eState==CURSOR_VALID );
54082     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
54083     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54084     rc = accessPayload(pCur, offset, amt, pBuf, 0);
54085   }
54086   return rc;
54087 }
54088
54089 /*
54090 ** Return a pointer to payload information from the entry that the
54091 ** pCur cursor is pointing to.  The pointer is to the beginning of
54092 ** the key if skipKey==0 and it points to the beginning of data if
54093 ** skipKey==1.  The number of bytes of available key/data is written
54094 ** into *pAmt.  If *pAmt==0, then the value returned will not be
54095 ** a valid pointer.
54096 **
54097 ** This routine is an optimization.  It is common for the entire key
54098 ** and data to fit on the local page and for there to be no overflow
54099 ** pages.  When that is so, this routine can be used to access the
54100 ** key and data without making a copy.  If the key and/or data spills
54101 ** onto overflow pages, then accessPayload() must be used to reassemble
54102 ** the key/data and copy it into a preallocated buffer.
54103 **
54104 ** The pointer returned by this routine looks directly into the cached
54105 ** page of the database.  The data might change or move the next time
54106 ** any btree routine is called.
54107 */
54108 static const unsigned char *fetchPayload(
54109   BtCursor *pCur,      /* Cursor pointing to entry to read from */
54110   int *pAmt,           /* Write the number of available bytes here */
54111   int skipKey          /* read beginning at data if this is true */
54112 ){
54113   unsigned char *aPayload;
54114   MemPage *pPage;
54115   u32 nKey;
54116   u32 nLocal;
54117
54118   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
54119   assert( pCur->eState==CURSOR_VALID );
54120   assert( cursorHoldsMutex(pCur) );
54121   pPage = pCur->apPage[pCur->iPage];
54122   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54123   if( NEVER(pCur->info.nSize==0) ){
54124     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
54125                    &pCur->info);
54126   }
54127   aPayload = pCur->info.pCell;
54128   aPayload += pCur->info.nHeader;
54129   if( pPage->intKey ){
54130     nKey = 0;
54131   }else{
54132     nKey = (int)pCur->info.nKey;
54133   }
54134   if( skipKey ){
54135     aPayload += nKey;
54136     nLocal = pCur->info.nLocal - nKey;
54137   }else{
54138     nLocal = pCur->info.nLocal;
54139     assert( nLocal<=nKey );
54140   }
54141   *pAmt = nLocal;
54142   return aPayload;
54143 }
54144
54145
54146 /*
54147 ** For the entry that cursor pCur is point to, return as
54148 ** many bytes of the key or data as are available on the local
54149 ** b-tree page.  Write the number of available bytes into *pAmt.
54150 **
54151 ** The pointer returned is ephemeral.  The key/data may move
54152 ** or be destroyed on the next call to any Btree routine,
54153 ** including calls from other threads against the same cache.
54154 ** Hence, a mutex on the BtShared should be held prior to calling
54155 ** this routine.
54156 **
54157 ** These routines is used to get quick access to key and data
54158 ** in the common case where no overflow pages are used.
54159 */
54160 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
54161   const void *p = 0;
54162   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54163   assert( cursorHoldsMutex(pCur) );
54164   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
54165     p = (const void*)fetchPayload(pCur, pAmt, 0);
54166   }
54167   return p;
54168 }
54169 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
54170   const void *p = 0;
54171   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54172   assert( cursorHoldsMutex(pCur) );
54173   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
54174     p = (const void*)fetchPayload(pCur, pAmt, 1);
54175   }
54176   return p;
54177 }
54178
54179
54180 /*
54181 ** Move the cursor down to a new child page.  The newPgno argument is the
54182 ** page number of the child page to move to.
54183 **
54184 ** This function returns SQLITE_CORRUPT if the page-header flags field of
54185 ** the new child page does not match the flags field of the parent (i.e.
54186 ** if an intkey page appears to be the parent of a non-intkey page, or
54187 ** vice-versa).
54188 */
54189 static int moveToChild(BtCursor *pCur, u32 newPgno){
54190   int rc;
54191   int i = pCur->iPage;
54192   MemPage *pNewPage;
54193   BtShared *pBt = pCur->pBt;
54194
54195   assert( cursorHoldsMutex(pCur) );
54196   assert( pCur->eState==CURSOR_VALID );
54197   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
54198   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
54199     return SQLITE_CORRUPT_BKPT;
54200   }
54201   rc = getAndInitPage(pBt, newPgno, &pNewPage);
54202   if( rc ) return rc;
54203   pCur->apPage[i+1] = pNewPage;
54204   pCur->aiIdx[i+1] = 0;
54205   pCur->iPage++;
54206
54207   pCur->info.nSize = 0;
54208   pCur->validNKey = 0;
54209   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
54210     return SQLITE_CORRUPT_BKPT;
54211   }
54212   return SQLITE_OK;
54213 }
54214
54215 #if 0
54216 /*
54217 ** Page pParent is an internal (non-leaf) tree page. This function
54218 ** asserts that page number iChild is the left-child if the iIdx'th
54219 ** cell in page pParent. Or, if iIdx is equal to the total number of
54220 ** cells in pParent, that page number iChild is the right-child of
54221 ** the page.
54222 */
54223 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
54224   assert( iIdx<=pParent->nCell );
54225   if( iIdx==pParent->nCell ){
54226     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
54227   }else{
54228     assert( get4byte(findCell(pParent, iIdx))==iChild );
54229   }
54230 }
54231 #else
54232 #  define assertParentIndex(x,y,z)
54233 #endif
54234
54235 /*
54236 ** Move the cursor up to the parent page.
54237 **
54238 ** pCur->idx is set to the cell index that contains the pointer
54239 ** to the page we are coming from.  If we are coming from the
54240 ** right-most child page then pCur->idx is set to one more than
54241 ** the largest cell index.
54242 */
54243 static void moveToParent(BtCursor *pCur){
54244   assert( cursorHoldsMutex(pCur) );
54245   assert( pCur->eState==CURSOR_VALID );
54246   assert( pCur->iPage>0 );
54247   assert( pCur->apPage[pCur->iPage] );
54248
54249   /* UPDATE: It is actually possible for the condition tested by the assert
54250   ** below to be untrue if the database file is corrupt. This can occur if
54251   ** one cursor has modified page pParent while a reference to it is held
54252   ** by a second cursor. Which can only happen if a single page is linked
54253   ** into more than one b-tree structure in a corrupt database.  */
54254 #if 0
54255   assertParentIndex(
54256     pCur->apPage[pCur->iPage-1],
54257     pCur->aiIdx[pCur->iPage-1],
54258     pCur->apPage[pCur->iPage]->pgno
54259   );
54260 #endif
54261   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
54262
54263   releasePage(pCur->apPage[pCur->iPage]);
54264   pCur->iPage--;
54265   pCur->info.nSize = 0;
54266   pCur->validNKey = 0;
54267 }
54268
54269 /*
54270 ** Move the cursor to point to the root page of its b-tree structure.
54271 **
54272 ** If the table has a virtual root page, then the cursor is moved to point
54273 ** to the virtual root page instead of the actual root page. A table has a
54274 ** virtual root page when the actual root page contains no cells and a
54275 ** single child page. This can only happen with the table rooted at page 1.
54276 **
54277 ** If the b-tree structure is empty, the cursor state is set to
54278 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
54279 ** cell located on the root (or virtual root) page and the cursor state
54280 ** is set to CURSOR_VALID.
54281 **
54282 ** If this function returns successfully, it may be assumed that the
54283 ** page-header flags indicate that the [virtual] root-page is the expected
54284 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
54285 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
54286 ** indicating a table b-tree, or if the caller did specify a KeyInfo
54287 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
54288 ** b-tree).
54289 */
54290 static int moveToRoot(BtCursor *pCur){
54291   MemPage *pRoot;
54292   int rc = SQLITE_OK;
54293   Btree *p = pCur->pBtree;
54294   BtShared *pBt = p->pBt;
54295
54296   assert( cursorHoldsMutex(pCur) );
54297   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
54298   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
54299   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
54300   if( pCur->eState>=CURSOR_REQUIRESEEK ){
54301     if( pCur->eState==CURSOR_FAULT ){
54302       assert( pCur->skipNext!=SQLITE_OK );
54303       return pCur->skipNext;
54304     }
54305     sqlite3BtreeClearCursor(pCur);
54306   }
54307
54308   if( pCur->iPage>=0 ){
54309     int i;
54310     for(i=1; i<=pCur->iPage; i++){
54311       releasePage(pCur->apPage[i]);
54312     }
54313     pCur->iPage = 0;
54314   }else if( pCur->pgnoRoot==0 ){
54315     pCur->eState = CURSOR_INVALID;
54316     return SQLITE_OK;
54317   }else{
54318     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
54319     if( rc!=SQLITE_OK ){
54320       pCur->eState = CURSOR_INVALID;
54321       return rc;
54322     }
54323     pCur->iPage = 0;
54324
54325     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
54326     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
54327     ** NULL, the caller expects a table b-tree. If this is not the case,
54328     ** return an SQLITE_CORRUPT error.  */
54329     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
54330     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
54331       return SQLITE_CORRUPT_BKPT;
54332     }
54333   }
54334
54335   /* Assert that the root page is of the correct type. This must be the
54336   ** case as the call to this function that loaded the root-page (either
54337   ** this call or a previous invocation) would have detected corruption
54338   ** if the assumption were not true, and it is not possible for the flags
54339   ** byte to have been modified while this cursor is holding a reference
54340   ** to the page.  */
54341   pRoot = pCur->apPage[0];
54342   assert( pRoot->pgno==pCur->pgnoRoot );
54343   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
54344
54345   pCur->aiIdx[0] = 0;
54346   pCur->info.nSize = 0;
54347   pCur->atLast = 0;
54348   pCur->validNKey = 0;
54349
54350   if( pRoot->nCell==0 && !pRoot->leaf ){
54351     Pgno subpage;
54352     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
54353     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
54354     pCur->eState = CURSOR_VALID;
54355     rc = moveToChild(pCur, subpage);
54356   }else{
54357     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
54358   }
54359   return rc;
54360 }
54361
54362 /*
54363 ** Move the cursor down to the left-most leaf entry beneath the
54364 ** entry to which it is currently pointing.
54365 **
54366 ** The left-most leaf is the one with the smallest key - the first
54367 ** in ascending order.
54368 */
54369 static int moveToLeftmost(BtCursor *pCur){
54370   Pgno pgno;
54371   int rc = SQLITE_OK;
54372   MemPage *pPage;
54373
54374   assert( cursorHoldsMutex(pCur) );
54375   assert( pCur->eState==CURSOR_VALID );
54376   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54377     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54378     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
54379     rc = moveToChild(pCur, pgno);
54380   }
54381   return rc;
54382 }
54383
54384 /*
54385 ** Move the cursor down to the right-most leaf entry beneath the
54386 ** page to which it is currently pointing.  Notice the difference
54387 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
54388 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
54389 ** finds the right-most entry beneath the *page*.
54390 **
54391 ** The right-most entry is the one with the largest key - the last
54392 ** key in ascending order.
54393 */
54394 static int moveToRightmost(BtCursor *pCur){
54395   Pgno pgno;
54396   int rc = SQLITE_OK;
54397   MemPage *pPage = 0;
54398
54399   assert( cursorHoldsMutex(pCur) );
54400   assert( pCur->eState==CURSOR_VALID );
54401   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54402     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54403     pCur->aiIdx[pCur->iPage] = pPage->nCell;
54404     rc = moveToChild(pCur, pgno);
54405   }
54406   if( rc==SQLITE_OK ){
54407     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
54408     pCur->info.nSize = 0;
54409     pCur->validNKey = 0;
54410   }
54411   return rc;
54412 }
54413
54414 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
54415 ** on success.  Set *pRes to 0 if the cursor actually points to something
54416 ** or set *pRes to 1 if the table is empty.
54417 */
54418 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
54419   int rc;
54420
54421   assert( cursorHoldsMutex(pCur) );
54422   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54423   rc = moveToRoot(pCur);
54424   if( rc==SQLITE_OK ){
54425     if( pCur->eState==CURSOR_INVALID ){
54426       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54427       *pRes = 1;
54428     }else{
54429       assert( pCur->apPage[pCur->iPage]->nCell>0 );
54430       *pRes = 0;
54431       rc = moveToLeftmost(pCur);
54432     }
54433   }
54434   return rc;
54435 }
54436
54437 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
54438 ** on success.  Set *pRes to 0 if the cursor actually points to something
54439 ** or set *pRes to 1 if the table is empty.
54440 */
54441 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
54442   int rc;
54443
54444   assert( cursorHoldsMutex(pCur) );
54445   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54446
54447   /* If the cursor already points to the last entry, this is a no-op. */
54448   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
54449 #ifdef SQLITE_DEBUG
54450     /* This block serves to assert() that the cursor really does point
54451     ** to the last entry in the b-tree. */
54452     int ii;
54453     for(ii=0; ii<pCur->iPage; ii++){
54454       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
54455     }
54456     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
54457     assert( pCur->apPage[pCur->iPage]->leaf );
54458 #endif
54459     return SQLITE_OK;
54460   }
54461
54462   rc = moveToRoot(pCur);
54463   if( rc==SQLITE_OK ){
54464     if( CURSOR_INVALID==pCur->eState ){
54465       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54466       *pRes = 1;
54467     }else{
54468       assert( pCur->eState==CURSOR_VALID );
54469       *pRes = 0;
54470       rc = moveToRightmost(pCur);
54471       pCur->atLast = rc==SQLITE_OK ?1:0;
54472     }
54473   }
54474   return rc;
54475 }
54476
54477 /* Move the cursor so that it points to an entry near the key
54478 ** specified by pIdxKey or intKey.   Return a success code.
54479 **
54480 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
54481 ** must be NULL.  For index tables, pIdxKey is used and intKey
54482 ** is ignored.
54483 **
54484 ** If an exact match is not found, then the cursor is always
54485 ** left pointing at a leaf page which would hold the entry if it
54486 ** were present.  The cursor might point to an entry that comes
54487 ** before or after the key.
54488 **
54489 ** An integer is written into *pRes which is the result of
54490 ** comparing the key with the entry to which the cursor is
54491 ** pointing.  The meaning of the integer written into
54492 ** *pRes is as follows:
54493 **
54494 **     *pRes<0      The cursor is left pointing at an entry that
54495 **                  is smaller than intKey/pIdxKey or if the table is empty
54496 **                  and the cursor is therefore left point to nothing.
54497 **
54498 **     *pRes==0     The cursor is left pointing at an entry that
54499 **                  exactly matches intKey/pIdxKey.
54500 **
54501 **     *pRes>0      The cursor is left pointing at an entry that
54502 **                  is larger than intKey/pIdxKey.
54503 **
54504 */
54505 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
54506   BtCursor *pCur,          /* The cursor to be moved */
54507   UnpackedRecord *pIdxKey, /* Unpacked index key */
54508   i64 intKey,              /* The table key */
54509   int biasRight,           /* If true, bias the search to the high end */
54510   int *pRes                /* Write search results here */
54511 ){
54512   int rc;
54513
54514   assert( cursorHoldsMutex(pCur) );
54515   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54516   assert( pRes );
54517   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
54518
54519   /* If the cursor is already positioned at the point we are trying
54520   ** to move to, then just return without doing any work */
54521   if( pCur->eState==CURSOR_VALID && pCur->validNKey
54522    && pCur->apPage[0]->intKey
54523   ){
54524     if( pCur->info.nKey==intKey ){
54525       *pRes = 0;
54526       return SQLITE_OK;
54527     }
54528     if( pCur->atLast && pCur->info.nKey<intKey ){
54529       *pRes = -1;
54530       return SQLITE_OK;
54531     }
54532   }
54533
54534   rc = moveToRoot(pCur);
54535   if( rc ){
54536     return rc;
54537   }
54538   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
54539   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
54540   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
54541   if( pCur->eState==CURSOR_INVALID ){
54542     *pRes = -1;
54543     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54544     return SQLITE_OK;
54545   }
54546   assert( pCur->apPage[0]->intKey || pIdxKey );
54547   for(;;){
54548     int lwr, upr, idx;
54549     Pgno chldPg;
54550     MemPage *pPage = pCur->apPage[pCur->iPage];
54551     int c;
54552
54553     /* pPage->nCell must be greater than zero. If this is the root-page
54554     ** the cursor would have been INVALID above and this for(;;) loop
54555     ** not run. If this is not the root-page, then the moveToChild() routine
54556     ** would have already detected db corruption. Similarly, pPage must
54557     ** be the right kind (index or table) of b-tree page. Otherwise
54558     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
54559     assert( pPage->nCell>0 );
54560     assert( pPage->intKey==(pIdxKey==0) );
54561     lwr = 0;
54562     upr = pPage->nCell-1;
54563     if( biasRight ){
54564       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
54565     }else{
54566       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
54567     }
54568     for(;;){
54569       u8 *pCell;                          /* Pointer to current cell in pPage */
54570
54571       assert( idx==pCur->aiIdx[pCur->iPage] );
54572       pCur->info.nSize = 0;
54573       pCell = findCell(pPage, idx) + pPage->childPtrSize;
54574       if( pPage->intKey ){
54575         i64 nCellKey;
54576         if( pPage->hasData ){
54577           u32 dummy;
54578           pCell += getVarint32(pCell, dummy);
54579         }
54580         getVarint(pCell, (u64*)&nCellKey);
54581         if( nCellKey==intKey ){
54582           c = 0;
54583         }else if( nCellKey<intKey ){
54584           c = -1;
54585         }else{
54586           assert( nCellKey>intKey );
54587           c = +1;
54588         }
54589         pCur->validNKey = 1;
54590         pCur->info.nKey = nCellKey;
54591       }else{
54592         /* The maximum supported page-size is 65536 bytes. This means that
54593         ** the maximum number of record bytes stored on an index B-Tree
54594         ** page is less than 16384 bytes and may be stored as a 2-byte
54595         ** varint. This information is used to attempt to avoid parsing
54596         ** the entire cell by checking for the cases where the record is
54597         ** stored entirely within the b-tree page by inspecting the first
54598         ** 2 bytes of the cell.
54599         */
54600         int nCell = pCell[0];
54601         if( nCell<=pPage->max1bytePayload
54602          /* && (pCell+nCell)<pPage->aDataEnd */
54603         ){
54604           /* This branch runs if the record-size field of the cell is a
54605           ** single byte varint and the record fits entirely on the main
54606           ** b-tree page.  */
54607           testcase( pCell+nCell+1==pPage->aDataEnd );
54608           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
54609         }else if( !(pCell[1] & 0x80)
54610           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
54611           /* && (pCell+nCell+2)<=pPage->aDataEnd */
54612         ){
54613           /* The record-size field is a 2 byte varint and the record
54614           ** fits entirely on the main b-tree page.  */
54615           testcase( pCell+nCell+2==pPage->aDataEnd );
54616           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
54617         }else{
54618           /* The record flows over onto one or more overflow pages. In
54619           ** this case the whole cell needs to be parsed, a buffer allocated
54620           ** and accessPayload() used to retrieve the record into the
54621           ** buffer before VdbeRecordCompare() can be called. */
54622           void *pCellKey;
54623           u8 * const pCellBody = pCell - pPage->childPtrSize;
54624           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
54625           nCell = (int)pCur->info.nKey;
54626           pCellKey = sqlite3Malloc( nCell );
54627           if( pCellKey==0 ){
54628             rc = SQLITE_NOMEM;
54629             goto moveto_finish;
54630           }
54631           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
54632           if( rc ){
54633             sqlite3_free(pCellKey);
54634             goto moveto_finish;
54635           }
54636           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
54637           sqlite3_free(pCellKey);
54638         }
54639       }
54640       if( c==0 ){
54641         if( pPage->intKey && !pPage->leaf ){
54642           lwr = idx;
54643           break;
54644         }else{
54645           *pRes = 0;
54646           rc = SQLITE_OK;
54647           goto moveto_finish;
54648         }
54649       }
54650       if( c<0 ){
54651         lwr = idx+1;
54652       }else{
54653         upr = idx-1;
54654       }
54655       if( lwr>upr ){
54656         break;
54657       }
54658       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54659     }
54660     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54661     assert( pPage->isInit );
54662     if( pPage->leaf ){
54663       chldPg = 0;
54664     }else if( lwr>=pPage->nCell ){
54665       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54666     }else{
54667       chldPg = get4byte(findCell(pPage, lwr));
54668     }
54669     if( chldPg==0 ){
54670       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54671       *pRes = c;
54672       rc = SQLITE_OK;
54673       goto moveto_finish;
54674     }
54675     pCur->aiIdx[pCur->iPage] = (u16)lwr;
54676     pCur->info.nSize = 0;
54677     pCur->validNKey = 0;
54678     rc = moveToChild(pCur, chldPg);
54679     if( rc ) goto moveto_finish;
54680   }
54681 moveto_finish:
54682   return rc;
54683 }
54684
54685
54686 /*
54687 ** Return TRUE if the cursor is not pointing at an entry of the table.
54688 **
54689 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
54690 ** past the last entry in the table or sqlite3BtreePrev() moves past
54691 ** the first entry.  TRUE is also returned if the table is empty.
54692 */
54693 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
54694   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54695   ** have been deleted? This API will need to change to return an error code
54696   ** as well as the boolean result value.
54697   */
54698   return (CURSOR_VALID!=pCur->eState);
54699 }
54700
54701 /*
54702 ** Advance the cursor to the next entry in the database.  If
54703 ** successful then set *pRes=0.  If the cursor
54704 ** was already pointing to the last entry in the database before
54705 ** this routine was called, then set *pRes=1.
54706 */
54707 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
54708   int rc;
54709   int idx;
54710   MemPage *pPage;
54711
54712   assert( cursorHoldsMutex(pCur) );
54713   rc = restoreCursorPosition(pCur);
54714   if( rc!=SQLITE_OK ){
54715     return rc;
54716   }
54717   assert( pRes!=0 );
54718   if( CURSOR_INVALID==pCur->eState ){
54719     *pRes = 1;
54720     return SQLITE_OK;
54721   }
54722   if( pCur->skipNext>0 ){
54723     pCur->skipNext = 0;
54724     *pRes = 0;
54725     return SQLITE_OK;
54726   }
54727   pCur->skipNext = 0;
54728
54729   pPage = pCur->apPage[pCur->iPage];
54730   idx = ++pCur->aiIdx[pCur->iPage];
54731   assert( pPage->isInit );
54732
54733   /* If the database file is corrupt, it is possible for the value of idx
54734   ** to be invalid here. This can only occur if a second cursor modifies
54735   ** the page while cursor pCur is holding a reference to it. Which can
54736   ** only happen if the database is corrupt in such a way as to link the
54737   ** page into more than one b-tree structure. */
54738   testcase( idx>pPage->nCell );
54739
54740   pCur->info.nSize = 0;
54741   pCur->validNKey = 0;
54742   if( idx>=pPage->nCell ){
54743     if( !pPage->leaf ){
54744       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54745       if( rc ) return rc;
54746       rc = moveToLeftmost(pCur);
54747       *pRes = 0;
54748       return rc;
54749     }
54750     do{
54751       if( pCur->iPage==0 ){
54752         *pRes = 1;
54753         pCur->eState = CURSOR_INVALID;
54754         return SQLITE_OK;
54755       }
54756       moveToParent(pCur);
54757       pPage = pCur->apPage[pCur->iPage];
54758     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54759     *pRes = 0;
54760     if( pPage->intKey ){
54761       rc = sqlite3BtreeNext(pCur, pRes);
54762     }else{
54763       rc = SQLITE_OK;
54764     }
54765     return rc;
54766   }
54767   *pRes = 0;
54768   if( pPage->leaf ){
54769     return SQLITE_OK;
54770   }
54771   rc = moveToLeftmost(pCur);
54772   return rc;
54773 }
54774
54775
54776 /*
54777 ** Step the cursor to the back to the previous entry in the database.  If
54778 ** successful then set *pRes=0.  If the cursor
54779 ** was already pointing to the first entry in the database before
54780 ** this routine was called, then set *pRes=1.
54781 */
54782 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
54783   int rc;
54784   MemPage *pPage;
54785
54786   assert( cursorHoldsMutex(pCur) );
54787   rc = restoreCursorPosition(pCur);
54788   if( rc!=SQLITE_OK ){
54789     return rc;
54790   }
54791   pCur->atLast = 0;
54792   if( CURSOR_INVALID==pCur->eState ){
54793     *pRes = 1;
54794     return SQLITE_OK;
54795   }
54796   if( pCur->skipNext<0 ){
54797     pCur->skipNext = 0;
54798     *pRes = 0;
54799     return SQLITE_OK;
54800   }
54801   pCur->skipNext = 0;
54802
54803   pPage = pCur->apPage[pCur->iPage];
54804   assert( pPage->isInit );
54805   if( !pPage->leaf ){
54806     int idx = pCur->aiIdx[pCur->iPage];
54807     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54808     if( rc ){
54809       return rc;
54810     }
54811     rc = moveToRightmost(pCur);
54812   }else{
54813     while( pCur->aiIdx[pCur->iPage]==0 ){
54814       if( pCur->iPage==0 ){
54815         pCur->eState = CURSOR_INVALID;
54816         *pRes = 1;
54817         return SQLITE_OK;
54818       }
54819       moveToParent(pCur);
54820     }
54821     pCur->info.nSize = 0;
54822     pCur->validNKey = 0;
54823
54824     pCur->aiIdx[pCur->iPage]--;
54825     pPage = pCur->apPage[pCur->iPage];
54826     if( pPage->intKey && !pPage->leaf ){
54827       rc = sqlite3BtreePrevious(pCur, pRes);
54828     }else{
54829       rc = SQLITE_OK;
54830     }
54831   }
54832   *pRes = 0;
54833   return rc;
54834 }
54835
54836 /*
54837 ** Allocate a new page from the database file.
54838 **
54839 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
54840 ** has already been called on the new page.)  The new page has also
54841 ** been referenced and the calling routine is responsible for calling
54842 ** sqlite3PagerUnref() on the new page when it is done.
54843 **
54844 ** SQLITE_OK is returned on success.  Any other return value indicates
54845 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
54846 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
54847 **
54848 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
54849 ** locate a page close to the page number "nearby".  This can be used in an
54850 ** attempt to keep related pages close to each other in the database file,
54851 ** which in turn can make database access faster.
54852 **
54853 ** If the "exact" parameter is not 0, and the page-number nearby exists
54854 ** anywhere on the free-list, then it is guarenteed to be returned. This
54855 ** is only used by auto-vacuum databases when allocating a new table.
54856 */
54857 static int allocateBtreePage(
54858   BtShared *pBt,
54859   MemPage **ppPage,
54860   Pgno *pPgno,
54861   Pgno nearby,
54862   u8 exact
54863 ){
54864   MemPage *pPage1;
54865   int rc;
54866   u32 n;     /* Number of pages on the freelist */
54867   u32 k;     /* Number of leaves on the trunk of the freelist */
54868   MemPage *pTrunk = 0;
54869   MemPage *pPrevTrunk = 0;
54870   Pgno mxPage;     /* Total size of the database file */
54871
54872   assert( sqlite3_mutex_held(pBt->mutex) );
54873   pPage1 = pBt->pPage1;
54874   mxPage = btreePagecount(pBt);
54875   n = get4byte(&pPage1->aData[36]);
54876   testcase( n==mxPage-1 );
54877   if( n>=mxPage ){
54878     return SQLITE_CORRUPT_BKPT;
54879   }
54880   if( n>0 ){
54881     /* There are pages on the freelist.  Reuse one of those pages. */
54882     Pgno iTrunk;
54883     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54884
54885     /* If the 'exact' parameter was true and a query of the pointer-map
54886     ** shows that the page 'nearby' is somewhere on the free-list, then
54887     ** the entire-list will be searched for that page.
54888     */
54889 #ifndef SQLITE_OMIT_AUTOVACUUM
54890     if( exact && nearby<=mxPage ){
54891       u8 eType;
54892       assert( nearby>0 );
54893       assert( pBt->autoVacuum );
54894       rc = ptrmapGet(pBt, nearby, &eType, 0);
54895       if( rc ) return rc;
54896       if( eType==PTRMAP_FREEPAGE ){
54897         searchList = 1;
54898       }
54899       *pPgno = nearby;
54900     }
54901 #endif
54902
54903     /* Decrement the free-list count by 1. Set iTrunk to the index of the
54904     ** first free-list trunk page. iPrevTrunk is initially 1.
54905     */
54906     rc = sqlite3PagerWrite(pPage1->pDbPage);
54907     if( rc ) return rc;
54908     put4byte(&pPage1->aData[36], n-1);
54909
54910     /* The code within this loop is run only once if the 'searchList' variable
54911     ** is not true. Otherwise, it runs once for each trunk-page on the
54912     ** free-list until the page 'nearby' is located.
54913     */
54914     do {
54915       pPrevTrunk = pTrunk;
54916       if( pPrevTrunk ){
54917         iTrunk = get4byte(&pPrevTrunk->aData[0]);
54918       }else{
54919         iTrunk = get4byte(&pPage1->aData[32]);
54920       }
54921       testcase( iTrunk==mxPage );
54922       if( iTrunk>mxPage ){
54923         rc = SQLITE_CORRUPT_BKPT;
54924       }else{
54925         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54926       }
54927       if( rc ){
54928         pTrunk = 0;
54929         goto end_allocate_page;
54930       }
54931       assert( pTrunk!=0 );
54932       assert( pTrunk->aData!=0 );
54933
54934       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54935       if( k==0 && !searchList ){
54936         /* The trunk has no leaves and the list is not being searched.
54937         ** So extract the trunk page itself and use it as the newly
54938         ** allocated page */
54939         assert( pPrevTrunk==0 );
54940         rc = sqlite3PagerWrite(pTrunk->pDbPage);
54941         if( rc ){
54942           goto end_allocate_page;
54943         }
54944         *pPgno = iTrunk;
54945         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54946         *ppPage = pTrunk;
54947         pTrunk = 0;
54948         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54949       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54950         /* Value of k is out of range.  Database corruption */
54951         rc = SQLITE_CORRUPT_BKPT;
54952         goto end_allocate_page;
54953 #ifndef SQLITE_OMIT_AUTOVACUUM
54954       }else if( searchList && nearby==iTrunk ){
54955         /* The list is being searched and this trunk page is the page
54956         ** to allocate, regardless of whether it has leaves.
54957         */
54958         assert( *pPgno==iTrunk );
54959         *ppPage = pTrunk;
54960         searchList = 0;
54961         rc = sqlite3PagerWrite(pTrunk->pDbPage);
54962         if( rc ){
54963           goto end_allocate_page;
54964         }
54965         if( k==0 ){
54966           if( !pPrevTrunk ){
54967             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54968           }else{
54969             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54970             if( rc!=SQLITE_OK ){
54971               goto end_allocate_page;
54972             }
54973             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54974           }
54975         }else{
54976           /* The trunk page is required by the caller but it contains
54977           ** pointers to free-list leaves. The first leaf becomes a trunk
54978           ** page in this case.
54979           */
54980           MemPage *pNewTrunk;
54981           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54982           if( iNewTrunk>mxPage ){
54983             rc = SQLITE_CORRUPT_BKPT;
54984             goto end_allocate_page;
54985           }
54986           testcase( iNewTrunk==mxPage );
54987           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
54988           if( rc!=SQLITE_OK ){
54989             goto end_allocate_page;
54990           }
54991           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
54992           if( rc!=SQLITE_OK ){
54993             releasePage(pNewTrunk);
54994             goto end_allocate_page;
54995           }
54996           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54997           put4byte(&pNewTrunk->aData[4], k-1);
54998           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54999           releasePage(pNewTrunk);
55000           if( !pPrevTrunk ){
55001             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
55002             put4byte(&pPage1->aData[32], iNewTrunk);
55003           }else{
55004             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
55005             if( rc ){
55006               goto end_allocate_page;
55007             }
55008             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
55009           }
55010         }
55011         pTrunk = 0;
55012         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
55013 #endif
55014       }else if( k>0 ){
55015         /* Extract a leaf from the trunk */
55016         u32 closest;
55017         Pgno iPage;
55018         unsigned char *aData = pTrunk->aData;
55019         if( nearby>0 ){
55020           u32 i;
55021           int dist;
55022           closest = 0;
55023           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
55024           for(i=1; i<k; i++){
55025             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
55026             if( d2<dist ){
55027               closest = i;
55028               dist = d2;
55029             }
55030           }
55031         }else{
55032           closest = 0;
55033         }
55034
55035         iPage = get4byte(&aData[8+closest*4]);
55036         testcase( iPage==mxPage );
55037         if( iPage>mxPage ){
55038           rc = SQLITE_CORRUPT_BKPT;
55039           goto end_allocate_page;
55040         }
55041         testcase( iPage==mxPage );
55042         if( !searchList || iPage==nearby ){
55043           int noContent;
55044           *pPgno = iPage;
55045           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
55046                  ": %d more free pages\n",
55047                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
55048           rc = sqlite3PagerWrite(pTrunk->pDbPage);
55049           if( rc ) goto end_allocate_page;
55050           if( closest<k-1 ){
55051             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
55052           }
55053           put4byte(&aData[4], k-1);
55054           noContent = !btreeGetHasContent(pBt, *pPgno);
55055           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
55056           if( rc==SQLITE_OK ){
55057             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
55058             if( rc!=SQLITE_OK ){
55059               releasePage(*ppPage);
55060             }
55061           }
55062           searchList = 0;
55063         }
55064       }
55065       releasePage(pPrevTrunk);
55066       pPrevTrunk = 0;
55067     }while( searchList );
55068   }else{
55069     /* There are no pages on the freelist, so create a new page at the
55070     ** end of the file */
55071     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55072     if( rc ) return rc;
55073     pBt->nPage++;
55074     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
55075
55076 #ifndef SQLITE_OMIT_AUTOVACUUM
55077     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
55078       /* If *pPgno refers to a pointer-map page, allocate two new pages
55079       ** at the end of the file instead of one. The first allocated page
55080       ** becomes a new pointer-map page, the second is used by the caller.
55081       */
55082       MemPage *pPg = 0;
55083       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
55084       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
55085       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
55086       if( rc==SQLITE_OK ){
55087         rc = sqlite3PagerWrite(pPg->pDbPage);
55088         releasePage(pPg);
55089       }
55090       if( rc ) return rc;
55091       pBt->nPage++;
55092       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
55093     }
55094 #endif
55095     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
55096     *pPgno = pBt->nPage;
55097
55098     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
55099     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
55100     if( rc ) return rc;
55101     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
55102     if( rc!=SQLITE_OK ){
55103       releasePage(*ppPage);
55104     }
55105     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
55106   }
55107
55108   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
55109
55110 end_allocate_page:
55111   releasePage(pTrunk);
55112   releasePage(pPrevTrunk);
55113   if( rc==SQLITE_OK ){
55114     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
55115       releasePage(*ppPage);
55116       return SQLITE_CORRUPT_BKPT;
55117     }
55118     (*ppPage)->isInit = 0;
55119   }else{
55120     *ppPage = 0;
55121   }
55122   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
55123   return rc;
55124 }
55125
55126 /*
55127 ** This function is used to add page iPage to the database file free-list.
55128 ** It is assumed that the page is not already a part of the free-list.
55129 **
55130 ** The value passed as the second argument to this function is optional.
55131 ** If the caller happens to have a pointer to the MemPage object
55132 ** corresponding to page iPage handy, it may pass it as the second value.
55133 ** Otherwise, it may pass NULL.
55134 **
55135 ** If a pointer to a MemPage object is passed as the second argument,
55136 ** its reference count is not altered by this function.
55137 */
55138 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
55139   MemPage *pTrunk = 0;                /* Free-list trunk page */
55140   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
55141   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
55142   MemPage *pPage;                     /* Page being freed. May be NULL. */
55143   int rc;                             /* Return Code */
55144   int nFree;                          /* Initial number of pages on free-list */
55145
55146   assert( sqlite3_mutex_held(pBt->mutex) );
55147   assert( iPage>1 );
55148   assert( !pMemPage || pMemPage->pgno==iPage );
55149
55150   if( pMemPage ){
55151     pPage = pMemPage;
55152     sqlite3PagerRef(pPage->pDbPage);
55153   }else{
55154     pPage = btreePageLookup(pBt, iPage);
55155   }
55156
55157   /* Increment the free page count on pPage1 */
55158   rc = sqlite3PagerWrite(pPage1->pDbPage);
55159   if( rc ) goto freepage_out;
55160   nFree = get4byte(&pPage1->aData[36]);
55161   put4byte(&pPage1->aData[36], nFree+1);
55162
55163   if( pBt->btsFlags & BTS_SECURE_DELETE ){
55164     /* If the secure_delete option is enabled, then
55165     ** always fully overwrite deleted information with zeros.
55166     */
55167     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
55168      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
55169     ){
55170       goto freepage_out;
55171     }
55172     memset(pPage->aData, 0, pPage->pBt->pageSize);
55173   }
55174
55175   /* If the database supports auto-vacuum, write an entry in the pointer-map
55176   ** to indicate that the page is free.
55177   */
55178   if( ISAUTOVACUUM ){
55179     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
55180     if( rc ) goto freepage_out;
55181   }
55182
55183   /* Now manipulate the actual database free-list structure. There are two
55184   ** possibilities. If the free-list is currently empty, or if the first
55185   ** trunk page in the free-list is full, then this page will become a
55186   ** new free-list trunk page. Otherwise, it will become a leaf of the
55187   ** first trunk page in the current free-list. This block tests if it
55188   ** is possible to add the page as a new free-list leaf.
55189   */
55190   if( nFree!=0 ){
55191     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
55192
55193     iTrunk = get4byte(&pPage1->aData[32]);
55194     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
55195     if( rc!=SQLITE_OK ){
55196       goto freepage_out;
55197     }
55198
55199     nLeaf = get4byte(&pTrunk->aData[4]);
55200     assert( pBt->usableSize>32 );
55201     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
55202       rc = SQLITE_CORRUPT_BKPT;
55203       goto freepage_out;
55204     }
55205     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
55206       /* In this case there is room on the trunk page to insert the page
55207       ** being freed as a new leaf.
55208       **
55209       ** Note that the trunk page is not really full until it contains
55210       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
55211       ** coded.  But due to a coding error in versions of SQLite prior to
55212       ** 3.6.0, databases with freelist trunk pages holding more than
55213       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
55214       ** to maintain backwards compatibility with older versions of SQLite,
55215       ** we will continue to restrict the number of entries to usableSize/4 - 8
55216       ** for now.  At some point in the future (once everyone has upgraded
55217       ** to 3.6.0 or later) we should consider fixing the conditional above
55218       ** to read "usableSize/4-2" instead of "usableSize/4-8".
55219       */
55220       rc = sqlite3PagerWrite(pTrunk->pDbPage);
55221       if( rc==SQLITE_OK ){
55222         put4byte(&pTrunk->aData[4], nLeaf+1);
55223         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
55224         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
55225           sqlite3PagerDontWrite(pPage->pDbPage);
55226         }
55227         rc = btreeSetHasContent(pBt, iPage);
55228       }
55229       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
55230       goto freepage_out;
55231     }
55232   }
55233
55234   /* If control flows to this point, then it was not possible to add the
55235   ** the page being freed as a leaf page of the first trunk in the free-list.
55236   ** Possibly because the free-list is empty, or possibly because the
55237   ** first trunk in the free-list is full. Either way, the page being freed
55238   ** will become the new first trunk page in the free-list.
55239   */
55240   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
55241     goto freepage_out;
55242   }
55243   rc = sqlite3PagerWrite(pPage->pDbPage);
55244   if( rc!=SQLITE_OK ){
55245     goto freepage_out;
55246   }
55247   put4byte(pPage->aData, iTrunk);
55248   put4byte(&pPage->aData[4], 0);
55249   put4byte(&pPage1->aData[32], iPage);
55250   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
55251
55252 freepage_out:
55253   if( pPage ){
55254     pPage->isInit = 0;
55255   }
55256   releasePage(pPage);
55257   releasePage(pTrunk);
55258   return rc;
55259 }
55260 static void freePage(MemPage *pPage, int *pRC){
55261   if( (*pRC)==SQLITE_OK ){
55262     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
55263   }
55264 }
55265
55266 /*
55267 ** Free any overflow pages associated with the given Cell.
55268 */
55269 static int clearCell(MemPage *pPage, unsigned char *pCell){
55270   BtShared *pBt = pPage->pBt;
55271   CellInfo info;
55272   Pgno ovflPgno;
55273   int rc;
55274   int nOvfl;
55275   u32 ovflPageSize;
55276
55277   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55278   btreeParseCellPtr(pPage, pCell, &info);
55279   if( info.iOverflow==0 ){
55280     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
55281   }
55282   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
55283     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
55284   }
55285   ovflPgno = get4byte(&pCell[info.iOverflow]);
55286   assert( pBt->usableSize > 4 );
55287   ovflPageSize = pBt->usableSize - 4;
55288   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
55289   assert( ovflPgno==0 || nOvfl>0 );
55290   while( nOvfl-- ){
55291     Pgno iNext = 0;
55292     MemPage *pOvfl = 0;
55293     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
55294       /* 0 is not a legal page number and page 1 cannot be an
55295       ** overflow page. Therefore if ovflPgno<2 or past the end of the
55296       ** file the database must be corrupt. */
55297       return SQLITE_CORRUPT_BKPT;
55298     }
55299     if( nOvfl ){
55300       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
55301       if( rc ) return rc;
55302     }
55303
55304     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
55305      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
55306     ){
55307       /* There is no reason any cursor should have an outstanding reference
55308       ** to an overflow page belonging to a cell that is being deleted/updated.
55309       ** So if there exists more than one reference to this page, then it
55310       ** must not really be an overflow page and the database must be corrupt.
55311       ** It is helpful to detect this before calling freePage2(), as
55312       ** freePage2() may zero the page contents if secure-delete mode is
55313       ** enabled. If this 'overflow' page happens to be a page that the
55314       ** caller is iterating through or using in some other way, this
55315       ** can be problematic.
55316       */
55317       rc = SQLITE_CORRUPT_BKPT;
55318     }else{
55319       rc = freePage2(pBt, pOvfl, ovflPgno);
55320     }
55321
55322     if( pOvfl ){
55323       sqlite3PagerUnref(pOvfl->pDbPage);
55324     }
55325     if( rc ) return rc;
55326     ovflPgno = iNext;
55327   }
55328   return SQLITE_OK;
55329 }
55330
55331 /*
55332 ** Create the byte sequence used to represent a cell on page pPage
55333 ** and write that byte sequence into pCell[].  Overflow pages are
55334 ** allocated and filled in as necessary.  The calling procedure
55335 ** is responsible for making sure sufficient space has been allocated
55336 ** for pCell[].
55337 **
55338 ** Note that pCell does not necessary need to point to the pPage->aData
55339 ** area.  pCell might point to some temporary storage.  The cell will
55340 ** be constructed in this temporary area then copied into pPage->aData
55341 ** later.
55342 */
55343 static int fillInCell(
55344   MemPage *pPage,                /* The page that contains the cell */
55345   unsigned char *pCell,          /* Complete text of the cell */
55346   const void *pKey, i64 nKey,    /* The key */
55347   const void *pData,int nData,   /* The data */
55348   int nZero,                     /* Extra zero bytes to append to pData */
55349   int *pnSize                    /* Write cell size here */
55350 ){
55351   int nPayload;
55352   const u8 *pSrc;
55353   int nSrc, n, rc;
55354   int spaceLeft;
55355   MemPage *pOvfl = 0;
55356   MemPage *pToRelease = 0;
55357   unsigned char *pPrior;
55358   unsigned char *pPayload;
55359   BtShared *pBt = pPage->pBt;
55360   Pgno pgnoOvfl = 0;
55361   int nHeader;
55362   CellInfo info;
55363
55364   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55365
55366   /* pPage is not necessarily writeable since pCell might be auxiliary
55367   ** buffer space that is separate from the pPage buffer area */
55368   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
55369             || sqlite3PagerIswriteable(pPage->pDbPage) );
55370
55371   /* Fill in the header. */
55372   nHeader = 0;
55373   if( !pPage->leaf ){
55374     nHeader += 4;
55375   }
55376   if( pPage->hasData ){
55377     nHeader += putVarint(&pCell[nHeader], nData+nZero);
55378   }else{
55379     nData = nZero = 0;
55380   }
55381   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
55382   btreeParseCellPtr(pPage, pCell, &info);
55383   assert( info.nHeader==nHeader );
55384   assert( info.nKey==nKey );
55385   assert( info.nData==(u32)(nData+nZero) );
55386
55387   /* Fill in the payload */
55388   nPayload = nData + nZero;
55389   if( pPage->intKey ){
55390     pSrc = pData;
55391     nSrc = nData;
55392     nData = 0;
55393   }else{
55394     if( NEVER(nKey>0x7fffffff || pKey==0) ){
55395       return SQLITE_CORRUPT_BKPT;
55396     }
55397     nPayload += (int)nKey;
55398     pSrc = pKey;
55399     nSrc = (int)nKey;
55400   }
55401   *pnSize = info.nSize;
55402   spaceLeft = info.nLocal;
55403   pPayload = &pCell[nHeader];
55404   pPrior = &pCell[info.iOverflow];
55405
55406   while( nPayload>0 ){
55407     if( spaceLeft==0 ){
55408 #ifndef SQLITE_OMIT_AUTOVACUUM
55409       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
55410       if( pBt->autoVacuum ){
55411         do{
55412           pgnoOvfl++;
55413         } while(
55414           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
55415         );
55416       }
55417 #endif
55418       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
55419 #ifndef SQLITE_OMIT_AUTOVACUUM
55420       /* If the database supports auto-vacuum, and the second or subsequent
55421       ** overflow page is being allocated, add an entry to the pointer-map
55422       ** for that page now.
55423       **
55424       ** If this is the first overflow page, then write a partial entry
55425       ** to the pointer-map. If we write nothing to this pointer-map slot,
55426       ** then the optimistic overflow chain processing in clearCell()
55427       ** may misinterpret the uninitialised values and delete the
55428       ** wrong pages from the database.
55429       */
55430       if( pBt->autoVacuum && rc==SQLITE_OK ){
55431         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
55432         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
55433         if( rc ){
55434           releasePage(pOvfl);
55435         }
55436       }
55437 #endif
55438       if( rc ){
55439         releasePage(pToRelease);
55440         return rc;
55441       }
55442
55443       /* If pToRelease is not zero than pPrior points into the data area
55444       ** of pToRelease.  Make sure pToRelease is still writeable. */
55445       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55446
55447       /* If pPrior is part of the data area of pPage, then make sure pPage
55448       ** is still writeable */
55449       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
55450             || sqlite3PagerIswriteable(pPage->pDbPage) );
55451
55452       put4byte(pPrior, pgnoOvfl);
55453       releasePage(pToRelease);
55454       pToRelease = pOvfl;
55455       pPrior = pOvfl->aData;
55456       put4byte(pPrior, 0);
55457       pPayload = &pOvfl->aData[4];
55458       spaceLeft = pBt->usableSize - 4;
55459     }
55460     n = nPayload;
55461     if( n>spaceLeft ) n = spaceLeft;
55462
55463     /* If pToRelease is not zero than pPayload points into the data area
55464     ** of pToRelease.  Make sure pToRelease is still writeable. */
55465     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55466
55467     /* If pPayload is part of the data area of pPage, then make sure pPage
55468     ** is still writeable */
55469     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
55470             || sqlite3PagerIswriteable(pPage->pDbPage) );
55471
55472     if( nSrc>0 ){
55473       if( n>nSrc ) n = nSrc;
55474       assert( pSrc );
55475       memcpy(pPayload, pSrc, n);
55476     }else{
55477       memset(pPayload, 0, n);
55478     }
55479     nPayload -= n;
55480     pPayload += n;
55481     pSrc += n;
55482     nSrc -= n;
55483     spaceLeft -= n;
55484     if( nSrc==0 ){
55485       nSrc = nData;
55486       pSrc = pData;
55487     }
55488   }
55489   releasePage(pToRelease);
55490   return SQLITE_OK;
55491 }
55492
55493 /*
55494 ** Remove the i-th cell from pPage.  This routine effects pPage only.
55495 ** The cell content is not freed or deallocated.  It is assumed that
55496 ** the cell content has been copied someplace else.  This routine just
55497 ** removes the reference to the cell from pPage.
55498 **
55499 ** "sz" must be the number of bytes in the cell.
55500 */
55501 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
55502   u32 pc;         /* Offset to cell content of cell being deleted */
55503   u8 *data;       /* pPage->aData */
55504   u8 *ptr;        /* Used to move bytes around within data[] */
55505   u8 *endPtr;     /* End of loop */
55506   int rc;         /* The return code */
55507   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
55508
55509   if( *pRC ) return;
55510
55511   assert( idx>=0 && idx<pPage->nCell );
55512   assert( sz==cellSize(pPage, idx) );
55513   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55514   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55515   data = pPage->aData;
55516   ptr = &pPage->aCellIdx[2*idx];
55517   pc = get2byte(ptr);
55518   hdr = pPage->hdrOffset;
55519   testcase( pc==get2byte(&data[hdr+5]) );
55520   testcase( pc+sz==pPage->pBt->usableSize );
55521   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
55522     *pRC = SQLITE_CORRUPT_BKPT;
55523     return;
55524   }
55525   rc = freeSpace(pPage, pc, sz);
55526   if( rc ){
55527     *pRC = rc;
55528     return;
55529   }
55530   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
55531   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55532   while( ptr<endPtr ){
55533     *(u16*)ptr = *(u16*)&ptr[2];
55534     ptr += 2;
55535   }
55536   pPage->nCell--;
55537   put2byte(&data[hdr+3], pPage->nCell);
55538   pPage->nFree += 2;
55539 }
55540
55541 /*
55542 ** Insert a new cell on pPage at cell index "i".  pCell points to the
55543 ** content of the cell.
55544 **
55545 ** If the cell content will fit on the page, then put it there.  If it
55546 ** will not fit, then make a copy of the cell content into pTemp if
55547 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
55548 ** in pPage->apOvfl[] and make it point to the cell content (either
55549 ** in pTemp or the original pCell) and also record its index.
55550 ** Allocating a new entry in pPage->aCell[] implies that
55551 ** pPage->nOverflow is incremented.
55552 **
55553 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
55554 ** cell. The caller will overwrite them after this function returns. If
55555 ** nSkip is non-zero, then pCell may not point to an invalid memory location
55556 ** (but pCell+nSkip is always valid).
55557 */
55558 static void insertCell(
55559   MemPage *pPage,   /* Page into which we are copying */
55560   int i,            /* New cell becomes the i-th cell of the page */
55561   u8 *pCell,        /* Content of the new cell */
55562   int sz,           /* Bytes of content in pCell */
55563   u8 *pTemp,        /* Temp storage space for pCell, if needed */
55564   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
55565   int *pRC          /* Read and write return code from here */
55566 ){
55567   int idx = 0;      /* Where to write new cell content in data[] */
55568   int j;            /* Loop counter */
55569   int end;          /* First byte past the last cell pointer in data[] */
55570   int ins;          /* Index in data[] where new cell pointer is inserted */
55571   int cellOffset;   /* Address of first cell pointer in data[] */
55572   u8 *data;         /* The content of the whole page */
55573   u8 *ptr;          /* Used for moving information around in data[] */
55574   u8 *endPtr;       /* End of the loop */
55575
55576   int nSkip = (iChild ? 4 : 0);
55577
55578   if( *pRC ) return;
55579
55580   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
55581   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
55582   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
55583   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
55584   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55585   /* The cell should normally be sized correctly.  However, when moving a
55586   ** malformed cell from a leaf page to an interior page, if the cell size
55587   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
55588   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
55589   ** the term after the || in the following assert(). */
55590   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
55591   if( pPage->nOverflow || sz+2>pPage->nFree ){
55592     if( pTemp ){
55593       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
55594       pCell = pTemp;
55595     }
55596     if( iChild ){
55597       put4byte(pCell, iChild);
55598     }
55599     j = pPage->nOverflow++;
55600     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
55601     pPage->apOvfl[j] = pCell;
55602     pPage->aiOvfl[j] = (u16)i;
55603   }else{
55604     int rc = sqlite3PagerWrite(pPage->pDbPage);
55605     if( rc!=SQLITE_OK ){
55606       *pRC = rc;
55607       return;
55608     }
55609     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55610     data = pPage->aData;
55611     cellOffset = pPage->cellOffset;
55612     end = cellOffset + 2*pPage->nCell;
55613     ins = cellOffset + 2*i;
55614     rc = allocateSpace(pPage, sz, &idx);
55615     if( rc ){ *pRC = rc; return; }
55616     /* The allocateSpace() routine guarantees the following two properties
55617     ** if it returns success */
55618     assert( idx >= end+2 );
55619     assert( idx+sz <= (int)pPage->pBt->usableSize );
55620     pPage->nCell++;
55621     pPage->nFree -= (u16)(2 + sz);
55622     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
55623     if( iChild ){
55624       put4byte(&data[idx], iChild);
55625     }
55626     ptr = &data[end];
55627     endPtr = &data[ins];
55628     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55629     while( ptr>endPtr ){
55630       *(u16*)ptr = *(u16*)&ptr[-2];
55631       ptr -= 2;
55632     }
55633     put2byte(&data[ins], idx);
55634     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
55635 #ifndef SQLITE_OMIT_AUTOVACUUM
55636     if( pPage->pBt->autoVacuum ){
55637       /* The cell may contain a pointer to an overflow page. If so, write
55638       ** the entry for the overflow page into the pointer map.
55639       */
55640       ptrmapPutOvflPtr(pPage, pCell, pRC);
55641     }
55642 #endif
55643   }
55644 }
55645
55646 /*
55647 ** Add a list of cells to a page.  The page should be initially empty.
55648 ** The cells are guaranteed to fit on the page.
55649 */
55650 static void assemblePage(
55651   MemPage *pPage,   /* The page to be assemblied */
55652   int nCell,        /* The number of cells to add to this page */
55653   u8 **apCell,      /* Pointers to cell bodies */
55654   u16 *aSize        /* Sizes of the cells */
55655 ){
55656   int i;            /* Loop counter */
55657   u8 *pCellptr;     /* Address of next cell pointer */
55658   int cellbody;     /* Address of next cell body */
55659   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
55660   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
55661   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55662
55663   assert( pPage->nOverflow==0 );
55664   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55665   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55666             && (int)MX_CELL(pPage->pBt)<=10921);
55667   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55668
55669   /* Check that the page has just been zeroed by zeroPage() */
55670   assert( pPage->nCell==0 );
55671   assert( get2byteNotZero(&data[hdr+5])==nUsable );
55672
55673   pCellptr = &pPage->aCellIdx[nCell*2];
55674   cellbody = nUsable;
55675   for(i=nCell-1; i>=0; i--){
55676     u16 sz = aSize[i];
55677     pCellptr -= 2;
55678     cellbody -= sz;
55679     put2byte(pCellptr, cellbody);
55680     memcpy(&data[cellbody], apCell[i], sz);
55681   }
55682   put2byte(&data[hdr+3], nCell);
55683   put2byte(&data[hdr+5], cellbody);
55684   pPage->nFree -= (nCell*2 + nUsable - cellbody);
55685   pPage->nCell = (u16)nCell;
55686 }
55687
55688 /*
55689 ** The following parameters determine how many adjacent pages get involved
55690 ** in a balancing operation.  NN is the number of neighbors on either side
55691 ** of the page that participate in the balancing operation.  NB is the
55692 ** total number of pages that participate, including the target page and
55693 ** NN neighbors on either side.
55694 **
55695 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
55696 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55697 ** in exchange for a larger degradation in INSERT and UPDATE performance.
55698 ** The value of NN appears to give the best results overall.
55699 */
55700 #define NN 1             /* Number of neighbors on either side of pPage */
55701 #define NB (NN*2+1)      /* Total pages involved in the balance */
55702
55703
55704 #ifndef SQLITE_OMIT_QUICKBALANCE
55705 /*
55706 ** This version of balance() handles the common special case where
55707 ** a new entry is being inserted on the extreme right-end of the
55708 ** tree, in other words, when the new entry will become the largest
55709 ** entry in the tree.
55710 **
55711 ** Instead of trying to balance the 3 right-most leaf pages, just add
55712 ** a new page to the right-hand side and put the one new entry in
55713 ** that page.  This leaves the right side of the tree somewhat
55714 ** unbalanced.  But odds are that we will be inserting new entries
55715 ** at the end soon afterwards so the nearly empty page will quickly
55716 ** fill up.  On average.
55717 **
55718 ** pPage is the leaf page which is the right-most page in the tree.
55719 ** pParent is its parent.  pPage must have a single overflow entry
55720 ** which is also the right-most entry on the page.
55721 **
55722 ** The pSpace buffer is used to store a temporary copy of the divider
55723 ** cell that will be inserted into pParent. Such a cell consists of a 4
55724 ** byte page number followed by a variable length integer. In other
55725 ** words, at most 13 bytes. Hence the pSpace buffer must be at
55726 ** least 13 bytes in size.
55727 */
55728 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55729   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55730   MemPage *pNew;                       /* Newly allocated page */
55731   int rc;                              /* Return Code */
55732   Pgno pgnoNew;                        /* Page number of pNew */
55733
55734   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55735   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55736   assert( pPage->nOverflow==1 );
55737
55738   /* This error condition is now caught prior to reaching this function */
55739   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
55740
55741   /* Allocate a new page. This page will become the right-sibling of
55742   ** pPage. Make the parent page writable, so that the new divider cell
55743   ** may be inserted. If both these operations are successful, proceed.
55744   */
55745   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55746
55747   if( rc==SQLITE_OK ){
55748
55749     u8 *pOut = &pSpace[4];
55750     u8 *pCell = pPage->apOvfl[0];
55751     u16 szCell = cellSizePtr(pPage, pCell);
55752     u8 *pStop;
55753
55754     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
55755     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55756     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55757     assemblePage(pNew, 1, &pCell, &szCell);
55758
55759     /* If this is an auto-vacuum database, update the pointer map
55760     ** with entries for the new page, and any pointer from the
55761     ** cell on the page to an overflow page. If either of these
55762     ** operations fails, the return code is set, but the contents
55763     ** of the parent page are still manipulated by thh code below.
55764     ** That is Ok, at this point the parent page is guaranteed to
55765     ** be marked as dirty. Returning an error code will cause a
55766     ** rollback, undoing any changes made to the parent page.
55767     */
55768     if( ISAUTOVACUUM ){
55769       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55770       if( szCell>pNew->minLocal ){
55771         ptrmapPutOvflPtr(pNew, pCell, &rc);
55772       }
55773     }
55774
55775     /* Create a divider cell to insert into pParent. The divider cell
55776     ** consists of a 4-byte page number (the page number of pPage) and
55777     ** a variable length key value (which must be the same value as the
55778     ** largest key on pPage).
55779     **
55780     ** To find the largest key value on pPage, first find the right-most
55781     ** cell on pPage. The first two fields of this cell are the
55782     ** record-length (a variable length integer at most 32-bits in size)
55783     ** and the key value (a variable length integer, may have any value).
55784     ** The first of the while(...) loops below skips over the record-length
55785     ** field. The second while(...) loop copies the key value from the
55786     ** cell on pPage into the pSpace buffer.
55787     */
55788     pCell = findCell(pPage, pPage->nCell-1);
55789     pStop = &pCell[9];
55790     while( (*(pCell++)&0x80) && pCell<pStop );
55791     pStop = &pCell[9];
55792     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55793
55794     /* Insert the new divider cell into pParent. */
55795     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55796                0, pPage->pgno, &rc);
55797
55798     /* Set the right-child pointer of pParent to point to the new page. */
55799     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55800
55801     /* Release the reference to the new page. */
55802     releasePage(pNew);
55803   }
55804
55805   return rc;
55806 }
55807 #endif /* SQLITE_OMIT_QUICKBALANCE */
55808
55809 #if 0
55810 /*
55811 ** This function does not contribute anything to the operation of SQLite.
55812 ** it is sometimes activated temporarily while debugging code responsible
55813 ** for setting pointer-map entries.
55814 */
55815 static int ptrmapCheckPages(MemPage **apPage, int nPage){
55816   int i, j;
55817   for(i=0; i<nPage; i++){
55818     Pgno n;
55819     u8 e;
55820     MemPage *pPage = apPage[i];
55821     BtShared *pBt = pPage->pBt;
55822     assert( pPage->isInit );
55823
55824     for(j=0; j<pPage->nCell; j++){
55825       CellInfo info;
55826       u8 *z;
55827
55828       z = findCell(pPage, j);
55829       btreeParseCellPtr(pPage, z, &info);
55830       if( info.iOverflow ){
55831         Pgno ovfl = get4byte(&z[info.iOverflow]);
55832         ptrmapGet(pBt, ovfl, &e, &n);
55833         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55834       }
55835       if( !pPage->leaf ){
55836         Pgno child = get4byte(z);
55837         ptrmapGet(pBt, child, &e, &n);
55838         assert( n==pPage->pgno && e==PTRMAP_BTREE );
55839       }
55840     }
55841     if( !pPage->leaf ){
55842       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55843       ptrmapGet(pBt, child, &e, &n);
55844       assert( n==pPage->pgno && e==PTRMAP_BTREE );
55845     }
55846   }
55847   return 1;
55848 }
55849 #endif
55850
55851 /*
55852 ** This function is used to copy the contents of the b-tree node stored
55853 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55854 ** the pointer-map entries for each child page are updated so that the
55855 ** parent page stored in the pointer map is page pTo. If pFrom contained
55856 ** any cells with overflow page pointers, then the corresponding pointer
55857 ** map entries are also updated so that the parent page is page pTo.
55858 **
55859 ** If pFrom is currently carrying any overflow cells (entries in the
55860 ** MemPage.apOvfl[] array), they are not copied to pTo.
55861 **
55862 ** Before returning, page pTo is reinitialized using btreeInitPage().
55863 **
55864 ** The performance of this function is not critical. It is only used by
55865 ** the balance_shallower() and balance_deeper() procedures, neither of
55866 ** which are called often under normal circumstances.
55867 */
55868 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55869   if( (*pRC)==SQLITE_OK ){
55870     BtShared * const pBt = pFrom->pBt;
55871     u8 * const aFrom = pFrom->aData;
55872     u8 * const aTo = pTo->aData;
55873     int const iFromHdr = pFrom->hdrOffset;
55874     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55875     int rc;
55876     int iData;
55877
55878
55879     assert( pFrom->isInit );
55880     assert( pFrom->nFree>=iToHdr );
55881     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55882
55883     /* Copy the b-tree node content from page pFrom to page pTo. */
55884     iData = get2byte(&aFrom[iFromHdr+5]);
55885     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55886     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55887
55888     /* Reinitialize page pTo so that the contents of the MemPage structure
55889     ** match the new data. The initialization of pTo can actually fail under
55890     ** fairly obscure circumstances, even though it is a copy of initialized
55891     ** page pFrom.
55892     */
55893     pTo->isInit = 0;
55894     rc = btreeInitPage(pTo);
55895     if( rc!=SQLITE_OK ){
55896       *pRC = rc;
55897       return;
55898     }
55899
55900     /* If this is an auto-vacuum database, update the pointer-map entries
55901     ** for any b-tree or overflow pages that pTo now contains the pointers to.
55902     */
55903     if( ISAUTOVACUUM ){
55904       *pRC = setChildPtrmaps(pTo);
55905     }
55906   }
55907 }
55908
55909 /*
55910 ** This routine redistributes cells on the iParentIdx'th child of pParent
55911 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
55912 ** same amount of free space. Usually a single sibling on either side of the
55913 ** page are used in the balancing, though both siblings might come from one
55914 ** side if the page is the first or last child of its parent. If the page
55915 ** has fewer than 2 siblings (something which can only happen if the page
55916 ** is a root page or a child of a root page) then all available siblings
55917 ** participate in the balancing.
55918 **
55919 ** The number of siblings of the page might be increased or decreased by
55920 ** one or two in an effort to keep pages nearly full but not over full.
55921 **
55922 ** Note that when this routine is called, some of the cells on the page
55923 ** might not actually be stored in MemPage.aData[]. This can happen
55924 ** if the page is overfull. This routine ensures that all cells allocated
55925 ** to the page and its siblings fit into MemPage.aData[] before returning.
55926 **
55927 ** In the course of balancing the page and its siblings, cells may be
55928 ** inserted into or removed from the parent page (pParent). Doing so
55929 ** may cause the parent page to become overfull or underfull. If this
55930 ** happens, it is the responsibility of the caller to invoke the correct
55931 ** balancing routine to fix this problem (see the balance() routine).
55932 **
55933 ** If this routine fails for any reason, it might leave the database
55934 ** in a corrupted state. So if this routine fails, the database should
55935 ** be rolled back.
55936 **
55937 ** The third argument to this function, aOvflSpace, is a pointer to a
55938 ** buffer big enough to hold one page. If while inserting cells into the parent
55939 ** page (pParent) the parent page becomes overfull, this buffer is
55940 ** used to store the parent's overflow cells. Because this function inserts
55941 ** a maximum of four divider cells into the parent page, and the maximum
55942 ** size of a cell stored within an internal node is always less than 1/4
55943 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55944 ** enough for all overflow cells.
55945 **
55946 ** If aOvflSpace is set to a null pointer, this function returns
55947 ** SQLITE_NOMEM.
55948 */
55949 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
55950 #pragma optimize("", off)
55951 #endif
55952 static int balance_nonroot(
55953   MemPage *pParent,               /* Parent page of siblings being balanced */
55954   int iParentIdx,                 /* Index of "the page" in pParent */
55955   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
55956   int isRoot,                     /* True if pParent is a root-page */
55957   int bBulk                       /* True if this call is part of a bulk load */
55958 ){
55959   BtShared *pBt;               /* The whole database */
55960   int nCell = 0;               /* Number of cells in apCell[] */
55961   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
55962   int nNew = 0;                /* Number of pages in apNew[] */
55963   int nOld;                    /* Number of pages in apOld[] */
55964   int i, j, k;                 /* Loop counters */
55965   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
55966   int rc = SQLITE_OK;          /* The return code */
55967   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
55968   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
55969   int usableSpace;             /* Bytes in pPage beyond the header */
55970   int pageFlags;               /* Value of pPage->aData[0] */
55971   int subtotal;                /* Subtotal of bytes in cells on one page */
55972   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
55973   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
55974   int szScratch;               /* Size of scratch memory requested */
55975   MemPage *apOld[NB];          /* pPage and up to two siblings */
55976   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
55977   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
55978   u8 *pRight;                  /* Location in parent of right-sibling pointer */
55979   u8 *apDiv[NB-1];             /* Divider cells in pParent */
55980   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
55981   int szNew[NB+2];             /* Combined size of cells place on i-th page */
55982   u8 **apCell = 0;             /* All cells begin balanced */
55983   u16 *szCell;                 /* Local size of all cells in apCell[] */
55984   u8 *aSpace1;                 /* Space for copies of dividers cells */
55985   Pgno pgno;                   /* Temp var to store a page number in */
55986
55987   pBt = pParent->pBt;
55988   assert( sqlite3_mutex_held(pBt->mutex) );
55989   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55990
55991 #if 0
55992   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55993 #endif
55994
55995   /* At this point pParent may have at most one overflow cell. And if
55996   ** this overflow cell is present, it must be the cell with
55997   ** index iParentIdx. This scenario comes about when this function
55998   ** is called (indirectly) from sqlite3BtreeDelete().
55999   */
56000   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
56001   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
56002
56003   if( !aOvflSpace ){
56004     return SQLITE_NOMEM;
56005   }
56006
56007   /* Find the sibling pages to balance. Also locate the cells in pParent
56008   ** that divide the siblings. An attempt is made to find NN siblings on
56009   ** either side of pPage. More siblings are taken from one side, however,
56010   ** if there are fewer than NN siblings on the other side. If pParent
56011   ** has NB or fewer children then all children of pParent are taken.
56012   **
56013   ** This loop also drops the divider cells from the parent page. This
56014   ** way, the remainder of the function does not have to deal with any
56015   ** overflow cells in the parent page, since if any existed they will
56016   ** have already been removed.
56017   */
56018   i = pParent->nOverflow + pParent->nCell;
56019   if( i<2 ){
56020     nxDiv = 0;
56021   }else{
56022     assert( bBulk==0 || bBulk==1 );
56023     if( iParentIdx==0 ){
56024       nxDiv = 0;
56025     }else if( iParentIdx==i ){
56026       nxDiv = i-2+bBulk;
56027     }else{
56028       assert( bBulk==0 );
56029       nxDiv = iParentIdx-1;
56030     }
56031     i = 2-bBulk;
56032   }
56033   nOld = i+1;
56034   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
56035     pRight = &pParent->aData[pParent->hdrOffset+8];
56036   }else{
56037     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
56038   }
56039   pgno = get4byte(pRight);
56040   while( 1 ){
56041     rc = getAndInitPage(pBt, pgno, &apOld[i]);
56042     if( rc ){
56043       memset(apOld, 0, (i+1)*sizeof(MemPage*));
56044       goto balance_cleanup;
56045     }
56046     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
56047     if( (i--)==0 ) break;
56048
56049     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
56050       apDiv[i] = pParent->apOvfl[0];
56051       pgno = get4byte(apDiv[i]);
56052       szNew[i] = cellSizePtr(pParent, apDiv[i]);
56053       pParent->nOverflow = 0;
56054     }else{
56055       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
56056       pgno = get4byte(apDiv[i]);
56057       szNew[i] = cellSizePtr(pParent, apDiv[i]);
56058
56059       /* Drop the cell from the parent page. apDiv[i] still points to
56060       ** the cell within the parent, even though it has been dropped.
56061       ** This is safe because dropping a cell only overwrites the first
56062       ** four bytes of it, and this function does not need the first
56063       ** four bytes of the divider cell. So the pointer is safe to use
56064       ** later on.
56065       **
56066       ** But not if we are in secure-delete mode. In secure-delete mode,
56067       ** the dropCell() routine will overwrite the entire cell with zeroes.
56068       ** In this case, temporarily copy the cell into the aOvflSpace[]
56069       ** buffer. It will be copied out again as soon as the aSpace[] buffer
56070       ** is allocated.  */
56071       if( pBt->btsFlags & BTS_SECURE_DELETE ){
56072         int iOff;
56073
56074         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
56075         if( (iOff+szNew[i])>(int)pBt->usableSize ){
56076           rc = SQLITE_CORRUPT_BKPT;
56077           memset(apOld, 0, (i+1)*sizeof(MemPage*));
56078           goto balance_cleanup;
56079         }else{
56080           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
56081           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
56082         }
56083       }
56084       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
56085     }
56086   }
56087
56088   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
56089   ** alignment */
56090   nMaxCells = (nMaxCells + 3)&~3;
56091
56092   /*
56093   ** Allocate space for memory structures
56094   */
56095   k = pBt->pageSize + ROUND8(sizeof(MemPage));
56096   szScratch =
56097        nMaxCells*sizeof(u8*)                       /* apCell */
56098      + nMaxCells*sizeof(u16)                       /* szCell */
56099      + pBt->pageSize                               /* aSpace1 */
56100      + k*nOld;                                     /* Page copies (apCopy) */
56101   apCell = sqlite3ScratchMalloc( szScratch );
56102   if( apCell==0 ){
56103     rc = SQLITE_NOMEM;
56104     goto balance_cleanup;
56105   }
56106   szCell = (u16*)&apCell[nMaxCells];
56107   aSpace1 = (u8*)&szCell[nMaxCells];
56108   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
56109
56110   /*
56111   ** Load pointers to all cells on sibling pages and the divider cells
56112   ** into the local apCell[] array.  Make copies of the divider cells
56113   ** into space obtained from aSpace1[] and remove the divider cells
56114   ** from pParent.
56115   **
56116   ** If the siblings are on leaf pages, then the child pointers of the
56117   ** divider cells are stripped from the cells before they are copied
56118   ** into aSpace1[].  In this way, all cells in apCell[] are without
56119   ** child pointers.  If siblings are not leaves, then all cell in
56120   ** apCell[] include child pointers.  Either way, all cells in apCell[]
56121   ** are alike.
56122   **
56123   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
56124   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
56125   */
56126   leafCorrection = apOld[0]->leaf*4;
56127   leafData = apOld[0]->hasData;
56128   for(i=0; i<nOld; i++){
56129     int limit;
56130
56131     /* Before doing anything else, take a copy of the i'th original sibling
56132     ** The rest of this function will use data from the copies rather
56133     ** that the original pages since the original pages will be in the
56134     ** process of being overwritten.  */
56135     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
56136     memcpy(pOld, apOld[i], sizeof(MemPage));
56137     pOld->aData = (void*)&pOld[1];
56138     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
56139
56140     limit = pOld->nCell+pOld->nOverflow;
56141     if( pOld->nOverflow>0 ){
56142       for(j=0; j<limit; j++){
56143         assert( nCell<nMaxCells );
56144         apCell[nCell] = findOverflowCell(pOld, j);
56145         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
56146         nCell++;
56147       }
56148     }else{
56149       u8 *aData = pOld->aData;
56150       u16 maskPage = pOld->maskPage;
56151       u16 cellOffset = pOld->cellOffset;
56152       for(j=0; j<limit; j++){
56153         assert( nCell<nMaxCells );
56154         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
56155         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
56156         nCell++;
56157       }
56158     }
56159     if( i<nOld-1 && !leafData){
56160       u16 sz = (u16)szNew[i];
56161       u8 *pTemp;
56162       assert( nCell<nMaxCells );
56163       szCell[nCell] = sz;
56164       pTemp = &aSpace1[iSpace1];
56165       iSpace1 += sz;
56166       assert( sz<=pBt->maxLocal+23 );
56167       assert( iSpace1 <= (int)pBt->pageSize );
56168       memcpy(pTemp, apDiv[i], sz);
56169       apCell[nCell] = pTemp+leafCorrection;
56170       assert( leafCorrection==0 || leafCorrection==4 );
56171       szCell[nCell] = szCell[nCell] - leafCorrection;
56172       if( !pOld->leaf ){
56173         assert( leafCorrection==0 );
56174         assert( pOld->hdrOffset==0 );
56175         /* The right pointer of the child page pOld becomes the left
56176         ** pointer of the divider cell */
56177         memcpy(apCell[nCell], &pOld->aData[8], 4);
56178       }else{
56179         assert( leafCorrection==4 );
56180         if( szCell[nCell]<4 ){
56181           /* Do not allow any cells smaller than 4 bytes. */
56182           szCell[nCell] = 4;
56183         }
56184       }
56185       nCell++;
56186     }
56187   }
56188
56189   /*
56190   ** Figure out the number of pages needed to hold all nCell cells.
56191   ** Store this number in "k".  Also compute szNew[] which is the total
56192   ** size of all cells on the i-th page and cntNew[] which is the index
56193   ** in apCell[] of the cell that divides page i from page i+1.
56194   ** cntNew[k] should equal nCell.
56195   **
56196   ** Values computed by this block:
56197   **
56198   **           k: The total number of sibling pages
56199   **    szNew[i]: Spaced used on the i-th sibling page.
56200   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
56201   **              the right of the i-th sibling page.
56202   ** usableSpace: Number of bytes of space available on each sibling.
56203   **
56204   */
56205   usableSpace = pBt->usableSize - 12 + leafCorrection;
56206   for(subtotal=k=i=0; i<nCell; i++){
56207     assert( i<nMaxCells );
56208     subtotal += szCell[i] + 2;
56209     if( subtotal > usableSpace ){
56210       szNew[k] = subtotal - szCell[i];
56211       cntNew[k] = i;
56212       if( leafData ){ i--; }
56213       subtotal = 0;
56214       k++;
56215       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
56216     }
56217   }
56218   szNew[k] = subtotal;
56219   cntNew[k] = nCell;
56220   k++;
56221
56222   /*
56223   ** The packing computed by the previous block is biased toward the siblings
56224   ** on the left side.  The left siblings are always nearly full, while the
56225   ** right-most sibling might be nearly empty.  This block of code attempts
56226   ** to adjust the packing of siblings to get a better balance.
56227   **
56228   ** This adjustment is more than an optimization.  The packing above might
56229   ** be so out of balance as to be illegal.  For example, the right-most
56230   ** sibling might be completely empty.  This adjustment is not optional.
56231   */
56232   for(i=k-1; i>0; i--){
56233     int szRight = szNew[i];  /* Size of sibling on the right */
56234     int szLeft = szNew[i-1]; /* Size of sibling on the left */
56235     int r;              /* Index of right-most cell in left sibling */
56236     int d;              /* Index of first cell to the left of right sibling */
56237
56238     r = cntNew[i-1] - 1;
56239     d = r + 1 - leafData;
56240     assert( d<nMaxCells );
56241     assert( r<nMaxCells );
56242     while( szRight==0
56243        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
56244     ){
56245       szRight += szCell[d] + 2;
56246       szLeft -= szCell[r] + 2;
56247       cntNew[i-1]--;
56248       r = cntNew[i-1] - 1;
56249       d = r + 1 - leafData;
56250     }
56251     szNew[i] = szRight;
56252     szNew[i-1] = szLeft;
56253   }
56254
56255   /* Either we found one or more cells (cntnew[0])>0) or pPage is
56256   ** a virtual root page.  A virtual root page is when the real root
56257   ** page is page 1 and we are the only child of that page.
56258   **
56259   ** UPDATE:  The assert() below is not necessarily true if the database
56260   ** file is corrupt.  The corruption will be detected and reported later
56261   ** in this procedure so there is no need to act upon it now.
56262   */
56263 #if 0
56264   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
56265 #endif
56266
56267   TRACE(("BALANCE: old: %d %d %d  ",
56268     apOld[0]->pgno,
56269     nOld>=2 ? apOld[1]->pgno : 0,
56270     nOld>=3 ? apOld[2]->pgno : 0
56271   ));
56272
56273   /*
56274   ** Allocate k new pages.  Reuse old pages where possible.
56275   */
56276   if( apOld[0]->pgno<=1 ){
56277     rc = SQLITE_CORRUPT_BKPT;
56278     goto balance_cleanup;
56279   }
56280   pageFlags = apOld[0]->aData[0];
56281   for(i=0; i<k; i++){
56282     MemPage *pNew;
56283     if( i<nOld ){
56284       pNew = apNew[i] = apOld[i];
56285       apOld[i] = 0;
56286       rc = sqlite3PagerWrite(pNew->pDbPage);
56287       nNew++;
56288       if( rc ) goto balance_cleanup;
56289     }else{
56290       assert( i>0 );
56291       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
56292       if( rc ) goto balance_cleanup;
56293       apNew[i] = pNew;
56294       nNew++;
56295
56296       /* Set the pointer-map entry for the new sibling page. */
56297       if( ISAUTOVACUUM ){
56298         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
56299         if( rc!=SQLITE_OK ){
56300           goto balance_cleanup;
56301         }
56302       }
56303     }
56304   }
56305
56306   /* Free any old pages that were not reused as new pages.
56307   */
56308   while( i<nOld ){
56309     freePage(apOld[i], &rc);
56310     if( rc ) goto balance_cleanup;
56311     releasePage(apOld[i]);
56312     apOld[i] = 0;
56313     i++;
56314   }
56315
56316   /*
56317   ** Put the new pages in accending order.  This helps to
56318   ** keep entries in the disk file in order so that a scan
56319   ** of the table is a linear scan through the file.  That
56320   ** in turn helps the operating system to deliver pages
56321   ** from the disk more rapidly.
56322   **
56323   ** An O(n^2) insertion sort algorithm is used, but since
56324   ** n is never more than NB (a small constant), that should
56325   ** not be a problem.
56326   **
56327   ** When NB==3, this one optimization makes the database
56328   ** about 25% faster for large insertions and deletions.
56329   */
56330   for(i=0; i<k-1; i++){
56331     int minV = apNew[i]->pgno;
56332     int minI = i;
56333     for(j=i+1; j<k; j++){
56334       if( apNew[j]->pgno<(unsigned)minV ){
56335         minI = j;
56336         minV = apNew[j]->pgno;
56337       }
56338     }
56339     if( minI>i ){
56340       MemPage *pT;
56341       pT = apNew[i];
56342       apNew[i] = apNew[minI];
56343       apNew[minI] = pT;
56344     }
56345   }
56346   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
56347     apNew[0]->pgno, szNew[0],
56348     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
56349     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
56350     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
56351     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
56352
56353   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56354   put4byte(pRight, apNew[nNew-1]->pgno);
56355
56356   /*
56357   ** Evenly distribute the data in apCell[] across the new pages.
56358   ** Insert divider cells into pParent as necessary.
56359   */
56360   j = 0;
56361   for(i=0; i<nNew; i++){
56362     /* Assemble the new sibling page. */
56363     MemPage *pNew = apNew[i];
56364     assert( j<nMaxCells );
56365     zeroPage(pNew, pageFlags);
56366     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
56367     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
56368     assert( pNew->nOverflow==0 );
56369
56370     j = cntNew[i];
56371
56372     /* If the sibling page assembled above was not the right-most sibling,
56373     ** insert a divider cell into the parent page.
56374     */
56375     assert( i<nNew-1 || j==nCell );
56376     if( j<nCell ){
56377       u8 *pCell;
56378       u8 *pTemp;
56379       int sz;
56380
56381       assert( j<nMaxCells );
56382       pCell = apCell[j];
56383       sz = szCell[j] + leafCorrection;
56384       pTemp = &aOvflSpace[iOvflSpace];
56385       if( !pNew->leaf ){
56386         memcpy(&pNew->aData[8], pCell, 4);
56387       }else if( leafData ){
56388         /* If the tree is a leaf-data tree, and the siblings are leaves,
56389         ** then there is no divider cell in apCell[]. Instead, the divider
56390         ** cell consists of the integer key for the right-most cell of
56391         ** the sibling-page assembled above only.
56392         */
56393         CellInfo info;
56394         j--;
56395         btreeParseCellPtr(pNew, apCell[j], &info);
56396         pCell = pTemp;
56397         sz = 4 + putVarint(&pCell[4], info.nKey);
56398         pTemp = 0;
56399       }else{
56400         pCell -= 4;
56401         /* Obscure case for non-leaf-data trees: If the cell at pCell was
56402         ** previously stored on a leaf node, and its reported size was 4
56403         ** bytes, then it may actually be smaller than this
56404         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
56405         ** any cell). But it is important to pass the correct size to
56406         ** insertCell(), so reparse the cell now.
56407         **
56408         ** Note that this can never happen in an SQLite data file, as all
56409         ** cells are at least 4 bytes. It only happens in b-trees used
56410         ** to evaluate "IN (SELECT ...)" and similar clauses.
56411         */
56412         if( szCell[j]==4 ){
56413           assert(leafCorrection==4);
56414           sz = cellSizePtr(pParent, pCell);
56415         }
56416       }
56417       iOvflSpace += sz;
56418       assert( sz<=pBt->maxLocal+23 );
56419       assert( iOvflSpace <= (int)pBt->pageSize );
56420       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
56421       if( rc!=SQLITE_OK ) goto balance_cleanup;
56422       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56423
56424       j++;
56425       nxDiv++;
56426     }
56427   }
56428   assert( j==nCell );
56429   assert( nOld>0 );
56430   assert( nNew>0 );
56431   if( (pageFlags & PTF_LEAF)==0 ){
56432     u8 *zChild = &apCopy[nOld-1]->aData[8];
56433     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
56434   }
56435
56436   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
56437     /* The root page of the b-tree now contains no cells. The only sibling
56438     ** page is the right-child of the parent. Copy the contents of the
56439     ** child page into the parent, decreasing the overall height of the
56440     ** b-tree structure by one. This is described as the "balance-shallower"
56441     ** sub-algorithm in some documentation.
56442     **
56443     ** If this is an auto-vacuum database, the call to copyNodeContent()
56444     ** sets all pointer-map entries corresponding to database image pages
56445     ** for which the pointer is stored within the content being copied.
56446     **
56447     ** The second assert below verifies that the child page is defragmented
56448     ** (it must be, as it was just reconstructed using assemblePage()). This
56449     ** is important if the parent page happens to be page 1 of the database
56450     ** image.  */
56451     assert( nNew==1 );
56452     assert( apNew[0]->nFree ==
56453         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
56454     );
56455     copyNodeContent(apNew[0], pParent, &rc);
56456     freePage(apNew[0], &rc);
56457   }else if( ISAUTOVACUUM ){
56458     /* Fix the pointer-map entries for all the cells that were shifted around.
56459     ** There are several different types of pointer-map entries that need to
56460     ** be dealt with by this routine. Some of these have been set already, but
56461     ** many have not. The following is a summary:
56462     **
56463     **   1) The entries associated with new sibling pages that were not
56464     **      siblings when this function was called. These have already
56465     **      been set. We don't need to worry about old siblings that were
56466     **      moved to the free-list - the freePage() code has taken care
56467     **      of those.
56468     **
56469     **   2) The pointer-map entries associated with the first overflow
56470     **      page in any overflow chains used by new divider cells. These
56471     **      have also already been taken care of by the insertCell() code.
56472     **
56473     **   3) If the sibling pages are not leaves, then the child pages of
56474     **      cells stored on the sibling pages may need to be updated.
56475     **
56476     **   4) If the sibling pages are not internal intkey nodes, then any
56477     **      overflow pages used by these cells may need to be updated
56478     **      (internal intkey nodes never contain pointers to overflow pages).
56479     **
56480     **   5) If the sibling pages are not leaves, then the pointer-map
56481     **      entries for the right-child pages of each sibling may need
56482     **      to be updated.
56483     **
56484     ** Cases 1 and 2 are dealt with above by other code. The next
56485     ** block deals with cases 3 and 4 and the one after that, case 5. Since
56486     ** setting a pointer map entry is a relatively expensive operation, this
56487     ** code only sets pointer map entries for child or overflow pages that have
56488     ** actually moved between pages.  */
56489     MemPage *pNew = apNew[0];
56490     MemPage *pOld = apCopy[0];
56491     int nOverflow = pOld->nOverflow;
56492     int iNextOld = pOld->nCell + nOverflow;
56493     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
56494     j = 0;                             /* Current 'old' sibling page */
56495     k = 0;                             /* Current 'new' sibling page */
56496     for(i=0; i<nCell; i++){
56497       int isDivider = 0;
56498       while( i==iNextOld ){
56499         /* Cell i is the cell immediately following the last cell on old
56500         ** sibling page j. If the siblings are not leaf pages of an
56501         ** intkey b-tree, then cell i was a divider cell. */
56502         assert( j+1 < ArraySize(apCopy) );
56503         assert( j+1 < nOld );
56504         pOld = apCopy[++j];
56505         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
56506         if( pOld->nOverflow ){
56507           nOverflow = pOld->nOverflow;
56508           iOverflow = i + !leafData + pOld->aiOvfl[0];
56509         }
56510         isDivider = !leafData;
56511       }
56512
56513       assert(nOverflow>0 || iOverflow<i );
56514       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
56515       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
56516       if( i==iOverflow ){
56517         isDivider = 1;
56518         if( (--nOverflow)>0 ){
56519           iOverflow++;
56520         }
56521       }
56522
56523       if( i==cntNew[k] ){
56524         /* Cell i is the cell immediately following the last cell on new
56525         ** sibling page k. If the siblings are not leaf pages of an
56526         ** intkey b-tree, then cell i is a divider cell.  */
56527         pNew = apNew[++k];
56528         if( !leafData ) continue;
56529       }
56530       assert( j<nOld );
56531       assert( k<nNew );
56532
56533       /* If the cell was originally divider cell (and is not now) or
56534       ** an overflow cell, or if the cell was located on a different sibling
56535       ** page before the balancing, then the pointer map entries associated
56536       ** with any child or overflow pages need to be updated.  */
56537       if( isDivider || pOld->pgno!=pNew->pgno ){
56538         if( !leafCorrection ){
56539           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
56540         }
56541         if( szCell[i]>pNew->minLocal ){
56542           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
56543         }
56544       }
56545     }
56546
56547     if( !leafCorrection ){
56548       for(i=0; i<nNew; i++){
56549         u32 key = get4byte(&apNew[i]->aData[8]);
56550         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
56551       }
56552     }
56553
56554 #if 0
56555     /* The ptrmapCheckPages() contains assert() statements that verify that
56556     ** all pointer map pages are set correctly. This is helpful while
56557     ** debugging. This is usually disabled because a corrupt database may
56558     ** cause an assert() statement to fail.  */
56559     ptrmapCheckPages(apNew, nNew);
56560     ptrmapCheckPages(&pParent, 1);
56561 #endif
56562   }
56563
56564   assert( pParent->isInit );
56565   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
56566           nOld, nNew, nCell));
56567
56568   /*
56569   ** Cleanup before returning.
56570   */
56571 balance_cleanup:
56572   sqlite3ScratchFree(apCell);
56573   for(i=0; i<nOld; i++){
56574     releasePage(apOld[i]);
56575   }
56576   for(i=0; i<nNew; i++){
56577     releasePage(apNew[i]);
56578   }
56579
56580   return rc;
56581 }
56582 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
56583 #pragma optimize("", on)
56584 #endif
56585
56586
56587 /*
56588 ** This function is called when the root page of a b-tree structure is
56589 ** overfull (has one or more overflow pages).
56590 **
56591 ** A new child page is allocated and the contents of the current root
56592 ** page, including overflow cells, are copied into the child. The root
56593 ** page is then overwritten to make it an empty page with the right-child
56594 ** pointer pointing to the new page.
56595 **
56596 ** Before returning, all pointer-map entries corresponding to pages
56597 ** that the new child-page now contains pointers to are updated. The
56598 ** entry corresponding to the new right-child pointer of the root
56599 ** page is also updated.
56600 **
56601 ** If successful, *ppChild is set to contain a reference to the child
56602 ** page and SQLITE_OK is returned. In this case the caller is required
56603 ** to call releasePage() on *ppChild exactly once. If an error occurs,
56604 ** an error code is returned and *ppChild is set to 0.
56605 */
56606 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
56607   int rc;                        /* Return value from subprocedures */
56608   MemPage *pChild = 0;           /* Pointer to a new child page */
56609   Pgno pgnoChild = 0;            /* Page number of the new child page */
56610   BtShared *pBt = pRoot->pBt;    /* The BTree */
56611
56612   assert( pRoot->nOverflow>0 );
56613   assert( sqlite3_mutex_held(pBt->mutex) );
56614
56615   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
56616   ** page that will become the new right-child of pPage. Copy the contents
56617   ** of the node stored on pRoot into the new child page.
56618   */
56619   rc = sqlite3PagerWrite(pRoot->pDbPage);
56620   if( rc==SQLITE_OK ){
56621     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
56622     copyNodeContent(pRoot, pChild, &rc);
56623     if( ISAUTOVACUUM ){
56624       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
56625     }
56626   }
56627   if( rc ){
56628     *ppChild = 0;
56629     releasePage(pChild);
56630     return rc;
56631   }
56632   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
56633   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56634   assert( pChild->nCell==pRoot->nCell );
56635
56636   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
56637
56638   /* Copy the overflow cells from pRoot to pChild */
56639   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
56640          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
56641   memcpy(pChild->apOvfl, pRoot->apOvfl,
56642          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
56643   pChild->nOverflow = pRoot->nOverflow;
56644
56645   /* Zero the contents of pRoot. Then install pChild as the right-child. */
56646   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
56647   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
56648
56649   *ppChild = pChild;
56650   return SQLITE_OK;
56651 }
56652
56653 /*
56654 ** The page that pCur currently points to has just been modified in
56655 ** some way. This function figures out if this modification means the
56656 ** tree needs to be balanced, and if so calls the appropriate balancing
56657 ** routine. Balancing routines are:
56658 **
56659 **   balance_quick()
56660 **   balance_deeper()
56661 **   balance_nonroot()
56662 */
56663 static int balance(BtCursor *pCur){
56664   int rc = SQLITE_OK;
56665   const int nMin = pCur->pBt->usableSize * 2 / 3;
56666   u8 aBalanceQuickSpace[13];
56667   u8 *pFree = 0;
56668
56669   TESTONLY( int balance_quick_called = 0 );
56670   TESTONLY( int balance_deeper_called = 0 );
56671
56672   do {
56673     int iPage = pCur->iPage;
56674     MemPage *pPage = pCur->apPage[iPage];
56675
56676     if( iPage==0 ){
56677       if( pPage->nOverflow ){
56678         /* The root page of the b-tree is overfull. In this case call the
56679         ** balance_deeper() function to create a new child for the root-page
56680         ** and copy the current contents of the root-page to it. The
56681         ** next iteration of the do-loop will balance the child page.
56682         */
56683         assert( (balance_deeper_called++)==0 );
56684         rc = balance_deeper(pPage, &pCur->apPage[1]);
56685         if( rc==SQLITE_OK ){
56686           pCur->iPage = 1;
56687           pCur->aiIdx[0] = 0;
56688           pCur->aiIdx[1] = 0;
56689           assert( pCur->apPage[1]->nOverflow );
56690         }
56691       }else{
56692         break;
56693       }
56694     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56695       break;
56696     }else{
56697       MemPage * const pParent = pCur->apPage[iPage-1];
56698       int const iIdx = pCur->aiIdx[iPage-1];
56699
56700       rc = sqlite3PagerWrite(pParent->pDbPage);
56701       if( rc==SQLITE_OK ){
56702 #ifndef SQLITE_OMIT_QUICKBALANCE
56703         if( pPage->hasData
56704          && pPage->nOverflow==1
56705          && pPage->aiOvfl[0]==pPage->nCell
56706          && pParent->pgno!=1
56707          && pParent->nCell==iIdx
56708         ){
56709           /* Call balance_quick() to create a new sibling of pPage on which
56710           ** to store the overflow cell. balance_quick() inserts a new cell
56711           ** into pParent, which may cause pParent overflow. If this
56712           ** happens, the next interation of the do-loop will balance pParent
56713           ** use either balance_nonroot() or balance_deeper(). Until this
56714           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56715           ** buffer.
56716           **
56717           ** The purpose of the following assert() is to check that only a
56718           ** single call to balance_quick() is made for each call to this
56719           ** function. If this were not verified, a subtle bug involving reuse
56720           ** of the aBalanceQuickSpace[] might sneak in.
56721           */
56722           assert( (balance_quick_called++)==0 );
56723           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56724         }else
56725 #endif
56726         {
56727           /* In this case, call balance_nonroot() to redistribute cells
56728           ** between pPage and up to 2 of its sibling pages. This involves
56729           ** modifying the contents of pParent, which may cause pParent to
56730           ** become overfull or underfull. The next iteration of the do-loop
56731           ** will balance the parent page to correct this.
56732           **
56733           ** If the parent page becomes overfull, the overflow cell or cells
56734           ** are stored in the pSpace buffer allocated immediately below.
56735           ** A subsequent iteration of the do-loop will deal with this by
56736           ** calling balance_nonroot() (balance_deeper() may be called first,
56737           ** but it doesn't deal with overflow cells - just moves them to a
56738           ** different page). Once this subsequent call to balance_nonroot()
56739           ** has completed, it is safe to release the pSpace buffer used by
56740           ** the previous call, as the overflow cell data will have been
56741           ** copied either into the body of a database page or into the new
56742           ** pSpace buffer passed to the latter call to balance_nonroot().
56743           */
56744           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
56745           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
56746           if( pFree ){
56747             /* If pFree is not NULL, it points to the pSpace buffer used
56748             ** by a previous call to balance_nonroot(). Its contents are
56749             ** now stored either on real database pages or within the
56750             ** new pSpace buffer, so it may be safely freed here. */
56751             sqlite3PageFree(pFree);
56752           }
56753
56754           /* The pSpace buffer will be freed after the next call to
56755           ** balance_nonroot(), or just before this function returns, whichever
56756           ** comes first. */
56757           pFree = pSpace;
56758         }
56759       }
56760
56761       pPage->nOverflow = 0;
56762
56763       /* The next iteration of the do-loop balances the parent page. */
56764       releasePage(pPage);
56765       pCur->iPage--;
56766     }
56767   }while( rc==SQLITE_OK );
56768
56769   if( pFree ){
56770     sqlite3PageFree(pFree);
56771   }
56772   return rc;
56773 }
56774
56775
56776 /*
56777 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56778 ** and the data is given by (pData,nData).  The cursor is used only to
56779 ** define what table the record should be inserted into.  The cursor
56780 ** is left pointing at a random location.
56781 **
56782 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
56783 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56784 **
56785 ** If the seekResult parameter is non-zero, then a successful call to
56786 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56787 ** been performed. seekResult is the search result returned (a negative
56788 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
56789 ** a positive value if pCur points at an etry that is larger than
56790 ** (pKey, nKey)).
56791 **
56792 ** If the seekResult parameter is non-zero, then the caller guarantees that
56793 ** cursor pCur is pointing at the existing copy of a row that is to be
56794 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56795 ** point to any entry or to no entry at all and so this function has to seek
56796 ** the cursor before the new key can be inserted.
56797 */
56798 SQLITE_PRIVATE int sqlite3BtreeInsert(
56799   BtCursor *pCur,                /* Insert data into the table of this cursor */
56800   const void *pKey, i64 nKey,    /* The key of the new record */
56801   const void *pData, int nData,  /* The data of the new record */
56802   int nZero,                     /* Number of extra 0 bytes to append to data */
56803   int appendBias,                /* True if this is likely an append */
56804   int seekResult                 /* Result of prior MovetoUnpacked() call */
56805 ){
56806   int rc;
56807   int loc = seekResult;          /* -1: before desired location  +1: after */
56808   int szNew = 0;
56809   int idx;
56810   MemPage *pPage;
56811   Btree *p = pCur->pBtree;
56812   BtShared *pBt = p->pBt;
56813   unsigned char *oldCell;
56814   unsigned char *newCell = 0;
56815
56816   if( pCur->eState==CURSOR_FAULT ){
56817     assert( pCur->skipNext!=SQLITE_OK );
56818     return pCur->skipNext;
56819   }
56820
56821   assert( cursorHoldsMutex(pCur) );
56822   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
56823               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
56824   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56825
56826   /* Assert that the caller has been consistent. If this cursor was opened
56827   ** expecting an index b-tree, then the caller should be inserting blob
56828   ** keys with no associated data. If the cursor was opened expecting an
56829   ** intkey table, the caller should be inserting integer keys with a
56830   ** blob of associated data.  */
56831   assert( (pKey==0)==(pCur->pKeyInfo==0) );
56832
56833   /* Save the positions of any other cursors open on this table.
56834   **
56835   ** In some cases, the call to btreeMoveto() below is a no-op. For
56836   ** example, when inserting data into a table with auto-generated integer
56837   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
56838   ** integer key to use. It then calls this function to actually insert the
56839   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56840   ** that the cursor is already where it needs to be and returns without
56841   ** doing any work. To avoid thwarting these optimizations, it is important
56842   ** not to clear the cursor here.
56843   */
56844   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56845   if( rc ) return rc;
56846
56847   /* If this is an insert into a table b-tree, invalidate any incrblob
56848   ** cursors open on the row being replaced (assuming this is a replace
56849   ** operation - if it is not, the following is a no-op).  */
56850   if( pCur->pKeyInfo==0 ){
56851     invalidateIncrblobCursors(p, nKey, 0);
56852   }
56853
56854   if( !loc ){
56855     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56856     if( rc ) return rc;
56857   }
56858   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56859
56860   pPage = pCur->apPage[pCur->iPage];
56861   assert( pPage->intKey || nKey>=0 );
56862   assert( pPage->leaf || !pPage->intKey );
56863
56864   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56865           pCur->pgnoRoot, nKey, nData, pPage->pgno,
56866           loc==0 ? "overwrite" : "new entry"));
56867   assert( pPage->isInit );
56868   allocateTempSpace(pBt);
56869   newCell = pBt->pTmpSpace;
56870   if( newCell==0 ) return SQLITE_NOMEM;
56871   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56872   if( rc ) goto end_insert;
56873   assert( szNew==cellSizePtr(pPage, newCell) );
56874   assert( szNew <= MX_CELL_SIZE(pBt) );
56875   idx = pCur->aiIdx[pCur->iPage];
56876   if( loc==0 ){
56877     u16 szOld;
56878     assert( idx<pPage->nCell );
56879     rc = sqlite3PagerWrite(pPage->pDbPage);
56880     if( rc ){
56881       goto end_insert;
56882     }
56883     oldCell = findCell(pPage, idx);
56884     if( !pPage->leaf ){
56885       memcpy(newCell, oldCell, 4);
56886     }
56887     szOld = cellSizePtr(pPage, oldCell);
56888     rc = clearCell(pPage, oldCell);
56889     dropCell(pPage, idx, szOld, &rc);
56890     if( rc ) goto end_insert;
56891   }else if( loc<0 && pPage->nCell>0 ){
56892     assert( pPage->leaf );
56893     idx = ++pCur->aiIdx[pCur->iPage];
56894   }else{
56895     assert( pPage->leaf );
56896   }
56897   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56898   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56899
56900   /* If no error has occured and pPage has an overflow cell, call balance()
56901   ** to redistribute the cells within the tree. Since balance() may move
56902   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56903   ** variables.
56904   **
56905   ** Previous versions of SQLite called moveToRoot() to move the cursor
56906   ** back to the root page as balance() used to invalidate the contents
56907   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56908   ** set the cursor state to "invalid". This makes common insert operations
56909   ** slightly faster.
56910   **
56911   ** There is a subtle but important optimization here too. When inserting
56912   ** multiple records into an intkey b-tree using a single cursor (as can
56913   ** happen while processing an "INSERT INTO ... SELECT" statement), it
56914   ** is advantageous to leave the cursor pointing to the last entry in
56915   ** the b-tree if possible. If the cursor is left pointing to the last
56916   ** entry in the table, and the next row inserted has an integer key
56917   ** larger than the largest existing key, it is possible to insert the
56918   ** row without seeking the cursor. This can be a big performance boost.
56919   */
56920   pCur->info.nSize = 0;
56921   pCur->validNKey = 0;
56922   if( rc==SQLITE_OK && pPage->nOverflow ){
56923     rc = balance(pCur);
56924
56925     /* Must make sure nOverflow is reset to zero even if the balance()
56926     ** fails. Internal data structure corruption will result otherwise.
56927     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56928     ** from trying to save the current position of the cursor.  */
56929     pCur->apPage[pCur->iPage]->nOverflow = 0;
56930     pCur->eState = CURSOR_INVALID;
56931   }
56932   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56933
56934 end_insert:
56935   return rc;
56936 }
56937
56938 /*
56939 ** Delete the entry that the cursor is pointing to.  The cursor
56940 ** is left pointing at a arbitrary location.
56941 */
56942 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
56943   Btree *p = pCur->pBtree;
56944   BtShared *pBt = p->pBt;
56945   int rc;                              /* Return code */
56946   MemPage *pPage;                      /* Page to delete cell from */
56947   unsigned char *pCell;                /* Pointer to cell to delete */
56948   int iCellIdx;                        /* Index of cell to delete */
56949   int iCellDepth;                      /* Depth of node containing pCell */
56950
56951   assert( cursorHoldsMutex(pCur) );
56952   assert( pBt->inTransaction==TRANS_WRITE );
56953   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56954   assert( pCur->wrFlag );
56955   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56956   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56957
56958   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
56959    || NEVER(pCur->eState!=CURSOR_VALID)
56960   ){
56961     return SQLITE_ERROR;  /* Something has gone awry. */
56962   }
56963
56964   iCellDepth = pCur->iPage;
56965   iCellIdx = pCur->aiIdx[iCellDepth];
56966   pPage = pCur->apPage[iCellDepth];
56967   pCell = findCell(pPage, iCellIdx);
56968
56969   /* If the page containing the entry to delete is not a leaf page, move
56970   ** the cursor to the largest entry in the tree that is smaller than
56971   ** the entry being deleted. This cell will replace the cell being deleted
56972   ** from the internal node. The 'previous' entry is used for this instead
56973   ** of the 'next' entry, as the previous entry is always a part of the
56974   ** sub-tree headed by the child page of the cell being deleted. This makes
56975   ** balancing the tree following the delete operation easier.  */
56976   if( !pPage->leaf ){
56977     int notUsed;
56978     rc = sqlite3BtreePrevious(pCur, &notUsed);
56979     if( rc ) return rc;
56980   }
56981
56982   /* Save the positions of any other cursors open on this table before
56983   ** making any modifications. Make the page containing the entry to be
56984   ** deleted writable. Then free any overflow pages associated with the
56985   ** entry and finally remove the cell itself from within the page.
56986   */
56987   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56988   if( rc ) return rc;
56989
56990   /* If this is a delete operation to remove a row from a table b-tree,
56991   ** invalidate any incrblob cursors open on the row being deleted.  */
56992   if( pCur->pKeyInfo==0 ){
56993     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56994   }
56995
56996   rc = sqlite3PagerWrite(pPage->pDbPage);
56997   if( rc ) return rc;
56998   rc = clearCell(pPage, pCell);
56999   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
57000   if( rc ) return rc;
57001
57002   /* If the cell deleted was not located on a leaf page, then the cursor
57003   ** is currently pointing to the largest entry in the sub-tree headed
57004   ** by the child-page of the cell that was just deleted from an internal
57005   ** node. The cell from the leaf node needs to be moved to the internal
57006   ** node to replace the deleted cell.  */
57007   if( !pPage->leaf ){
57008     MemPage *pLeaf = pCur->apPage[pCur->iPage];
57009     int nCell;
57010     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
57011     unsigned char *pTmp;
57012
57013     pCell = findCell(pLeaf, pLeaf->nCell-1);
57014     nCell = cellSizePtr(pLeaf, pCell);
57015     assert( MX_CELL_SIZE(pBt) >= nCell );
57016
57017     allocateTempSpace(pBt);
57018     pTmp = pBt->pTmpSpace;
57019
57020     rc = sqlite3PagerWrite(pLeaf->pDbPage);
57021     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
57022     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
57023     if( rc ) return rc;
57024   }
57025
57026   /* Balance the tree. If the entry deleted was located on a leaf page,
57027   ** then the cursor still points to that page. In this case the first
57028   ** call to balance() repairs the tree, and the if(...) condition is
57029   ** never true.
57030   **
57031   ** Otherwise, if the entry deleted was on an internal node page, then
57032   ** pCur is pointing to the leaf page from which a cell was removed to
57033   ** replace the cell deleted from the internal node. This is slightly
57034   ** tricky as the leaf node may be underfull, and the internal node may
57035   ** be either under or overfull. In this case run the balancing algorithm
57036   ** on the leaf node first. If the balance proceeds far enough up the
57037   ** tree that we can be sure that any problem in the internal node has
57038   ** been corrected, so be it. Otherwise, after balancing the leaf node,
57039   ** walk the cursor up the tree to the internal node and balance it as
57040   ** well.  */
57041   rc = balance(pCur);
57042   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
57043     while( pCur->iPage>iCellDepth ){
57044       releasePage(pCur->apPage[pCur->iPage--]);
57045     }
57046     rc = balance(pCur);
57047   }
57048
57049   if( rc==SQLITE_OK ){
57050     moveToRoot(pCur);
57051   }
57052   return rc;
57053 }
57054
57055 /*
57056 ** Create a new BTree table.  Write into *piTable the page
57057 ** number for the root page of the new table.
57058 **
57059 ** The type of type is determined by the flags parameter.  Only the
57060 ** following values of flags are currently in use.  Other values for
57061 ** flags might not work:
57062 **
57063 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
57064 **     BTREE_ZERODATA                  Used for SQL indices
57065 */
57066 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
57067   BtShared *pBt = p->pBt;
57068   MemPage *pRoot;
57069   Pgno pgnoRoot;
57070   int rc;
57071   int ptfFlags;          /* Page-type flage for the root page of new table */
57072
57073   assert( sqlite3BtreeHoldsMutex(p) );
57074   assert( pBt->inTransaction==TRANS_WRITE );
57075   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
57076
57077 #ifdef SQLITE_OMIT_AUTOVACUUM
57078   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
57079   if( rc ){
57080     return rc;
57081   }
57082 #else
57083   if( pBt->autoVacuum ){
57084     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
57085     MemPage *pPageMove; /* The page to move to. */
57086
57087     /* Creating a new table may probably require moving an existing database
57088     ** to make room for the new tables root page. In case this page turns
57089     ** out to be an overflow page, delete all overflow page-map caches
57090     ** held by open cursors.
57091     */
57092     invalidateAllOverflowCache(pBt);
57093
57094     /* Read the value of meta[3] from the database to determine where the
57095     ** root page of the new table should go. meta[3] is the largest root-page
57096     ** created so far, so the new root-page is (meta[3]+1).
57097     */
57098     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
57099     pgnoRoot++;
57100
57101     /* The new root-page may not be allocated on a pointer-map page, or the
57102     ** PENDING_BYTE page.
57103     */
57104     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
57105         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
57106       pgnoRoot++;
57107     }
57108     assert( pgnoRoot>=3 );
57109
57110     /* Allocate a page. The page that currently resides at pgnoRoot will
57111     ** be moved to the allocated page (unless the allocated page happens
57112     ** to reside at pgnoRoot).
57113     */
57114     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
57115     if( rc!=SQLITE_OK ){
57116       return rc;
57117     }
57118
57119     if( pgnoMove!=pgnoRoot ){
57120       /* pgnoRoot is the page that will be used for the root-page of
57121       ** the new table (assuming an error did not occur). But we were
57122       ** allocated pgnoMove. If required (i.e. if it was not allocated
57123       ** by extending the file), the current page at position pgnoMove
57124       ** is already journaled.
57125       */
57126       u8 eType = 0;
57127       Pgno iPtrPage = 0;
57128
57129       releasePage(pPageMove);
57130
57131       /* Move the page currently at pgnoRoot to pgnoMove. */
57132       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
57133       if( rc!=SQLITE_OK ){
57134         return rc;
57135       }
57136       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
57137       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
57138         rc = SQLITE_CORRUPT_BKPT;
57139       }
57140       if( rc!=SQLITE_OK ){
57141         releasePage(pRoot);
57142         return rc;
57143       }
57144       assert( eType!=PTRMAP_ROOTPAGE );
57145       assert( eType!=PTRMAP_FREEPAGE );
57146       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
57147       releasePage(pRoot);
57148
57149       /* Obtain the page at pgnoRoot */
57150       if( rc!=SQLITE_OK ){
57151         return rc;
57152       }
57153       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
57154       if( rc!=SQLITE_OK ){
57155         return rc;
57156       }
57157       rc = sqlite3PagerWrite(pRoot->pDbPage);
57158       if( rc!=SQLITE_OK ){
57159         releasePage(pRoot);
57160         return rc;
57161       }
57162     }else{
57163       pRoot = pPageMove;
57164     }
57165
57166     /* Update the pointer-map and meta-data with the new root-page number. */
57167     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
57168     if( rc ){
57169       releasePage(pRoot);
57170       return rc;
57171     }
57172
57173     /* When the new root page was allocated, page 1 was made writable in
57174     ** order either to increase the database filesize, or to decrement the
57175     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
57176     */
57177     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
57178     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
57179     if( NEVER(rc) ){
57180       releasePage(pRoot);
57181       return rc;
57182     }
57183
57184   }else{
57185     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
57186     if( rc ) return rc;
57187   }
57188 #endif
57189   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
57190   if( createTabFlags & BTREE_INTKEY ){
57191     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
57192   }else{
57193     ptfFlags = PTF_ZERODATA | PTF_LEAF;
57194   }
57195   zeroPage(pRoot, ptfFlags);
57196   sqlite3PagerUnref(pRoot->pDbPage);
57197   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
57198   *piTable = (int)pgnoRoot;
57199   return SQLITE_OK;
57200 }
57201 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
57202   int rc;
57203   sqlite3BtreeEnter(p);
57204   rc = btreeCreateTable(p, piTable, flags);
57205   sqlite3BtreeLeave(p);
57206   return rc;
57207 }
57208
57209 /*
57210 ** Erase the given database page and all its children.  Return
57211 ** the page to the freelist.
57212 */
57213 static int clearDatabasePage(
57214   BtShared *pBt,           /* The BTree that contains the table */
57215   Pgno pgno,               /* Page number to clear */
57216   int freePageFlag,        /* Deallocate page if true */
57217   int *pnChange            /* Add number of Cells freed to this counter */
57218 ){
57219   MemPage *pPage;
57220   int rc;
57221   unsigned char *pCell;
57222   int i;
57223
57224   assert( sqlite3_mutex_held(pBt->mutex) );
57225   if( pgno>btreePagecount(pBt) ){
57226     return SQLITE_CORRUPT_BKPT;
57227   }
57228
57229   rc = getAndInitPage(pBt, pgno, &pPage);
57230   if( rc ) return rc;
57231   for(i=0; i<pPage->nCell; i++){
57232     pCell = findCell(pPage, i);
57233     if( !pPage->leaf ){
57234       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
57235       if( rc ) goto cleardatabasepage_out;
57236     }
57237     rc = clearCell(pPage, pCell);
57238     if( rc ) goto cleardatabasepage_out;
57239   }
57240   if( !pPage->leaf ){
57241     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
57242     if( rc ) goto cleardatabasepage_out;
57243   }else if( pnChange ){
57244     assert( pPage->intKey );
57245     *pnChange += pPage->nCell;
57246   }
57247   if( freePageFlag ){
57248     freePage(pPage, &rc);
57249   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
57250     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
57251   }
57252
57253 cleardatabasepage_out:
57254   releasePage(pPage);
57255   return rc;
57256 }
57257
57258 /*
57259 ** Delete all information from a single table in the database.  iTable is
57260 ** the page number of the root of the table.  After this routine returns,
57261 ** the root page is empty, but still exists.
57262 **
57263 ** This routine will fail with SQLITE_LOCKED if there are any open
57264 ** read cursors on the table.  Open write cursors are moved to the
57265 ** root of the table.
57266 **
57267 ** If pnChange is not NULL, then table iTable must be an intkey table. The
57268 ** integer value pointed to by pnChange is incremented by the number of
57269 ** entries in the table.
57270 */
57271 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
57272   int rc;
57273   BtShared *pBt = p->pBt;
57274   sqlite3BtreeEnter(p);
57275   assert( p->inTrans==TRANS_WRITE );
57276
57277   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
57278
57279   if( SQLITE_OK==rc ){
57280     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
57281     ** is the root of a table b-tree - if it is not, the following call is
57282     ** a no-op).  */
57283     invalidateIncrblobCursors(p, 0, 1);
57284     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
57285   }
57286   sqlite3BtreeLeave(p);
57287   return rc;
57288 }
57289
57290 /*
57291 ** Erase all information in a table and add the root of the table to
57292 ** the freelist.  Except, the root of the principle table (the one on
57293 ** page 1) is never added to the freelist.
57294 **
57295 ** This routine will fail with SQLITE_LOCKED if there are any open
57296 ** cursors on the table.
57297 **
57298 ** If AUTOVACUUM is enabled and the page at iTable is not the last
57299 ** root page in the database file, then the last root page
57300 ** in the database file is moved into the slot formerly occupied by
57301 ** iTable and that last slot formerly occupied by the last root page
57302 ** is added to the freelist instead of iTable.  In this say, all
57303 ** root pages are kept at the beginning of the database file, which
57304 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
57305 ** page number that used to be the last root page in the file before
57306 ** the move.  If no page gets moved, *piMoved is set to 0.
57307 ** The last root page is recorded in meta[3] and the value of
57308 ** meta[3] is updated by this procedure.
57309 */
57310 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
57311   int rc;
57312   MemPage *pPage = 0;
57313   BtShared *pBt = p->pBt;
57314
57315   assert( sqlite3BtreeHoldsMutex(p) );
57316   assert( p->inTrans==TRANS_WRITE );
57317
57318   /* It is illegal to drop a table if any cursors are open on the
57319   ** database. This is because in auto-vacuum mode the backend may
57320   ** need to move another root-page to fill a gap left by the deleted
57321   ** root page. If an open cursor was using this page a problem would
57322   ** occur.
57323   **
57324   ** This error is caught long before control reaches this point.
57325   */
57326   if( NEVER(pBt->pCursor) ){
57327     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
57328     return SQLITE_LOCKED_SHAREDCACHE;
57329   }
57330
57331   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
57332   if( rc ) return rc;
57333   rc = sqlite3BtreeClearTable(p, iTable, 0);
57334   if( rc ){
57335     releasePage(pPage);
57336     return rc;
57337   }
57338
57339   *piMoved = 0;
57340
57341   if( iTable>1 ){
57342 #ifdef SQLITE_OMIT_AUTOVACUUM
57343     freePage(pPage, &rc);
57344     releasePage(pPage);
57345 #else
57346     if( pBt->autoVacuum ){
57347       Pgno maxRootPgno;
57348       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
57349
57350       if( iTable==maxRootPgno ){
57351         /* If the table being dropped is the table with the largest root-page
57352         ** number in the database, put the root page on the free list.
57353         */
57354         freePage(pPage, &rc);
57355         releasePage(pPage);
57356         if( rc!=SQLITE_OK ){
57357           return rc;
57358         }
57359       }else{
57360         /* The table being dropped does not have the largest root-page
57361         ** number in the database. So move the page that does into the
57362         ** gap left by the deleted root-page.
57363         */
57364         MemPage *pMove;
57365         releasePage(pPage);
57366         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
57367         if( rc!=SQLITE_OK ){
57368           return rc;
57369         }
57370         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
57371         releasePage(pMove);
57372         if( rc!=SQLITE_OK ){
57373           return rc;
57374         }
57375         pMove = 0;
57376         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
57377         freePage(pMove, &rc);
57378         releasePage(pMove);
57379         if( rc!=SQLITE_OK ){
57380           return rc;
57381         }
57382         *piMoved = maxRootPgno;
57383       }
57384
57385       /* Set the new 'max-root-page' value in the database header. This
57386       ** is the old value less one, less one more if that happens to
57387       ** be a root-page number, less one again if that is the
57388       ** PENDING_BYTE_PAGE.
57389       */
57390       maxRootPgno--;
57391       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
57392              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
57393         maxRootPgno--;
57394       }
57395       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
57396
57397       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
57398     }else{
57399       freePage(pPage, &rc);
57400       releasePage(pPage);
57401     }
57402 #endif
57403   }else{
57404     /* If sqlite3BtreeDropTable was called on page 1.
57405     ** This really never should happen except in a corrupt
57406     ** database.
57407     */
57408     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
57409     releasePage(pPage);
57410   }
57411   return rc;
57412 }
57413 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
57414   int rc;
57415   sqlite3BtreeEnter(p);
57416   rc = btreeDropTable(p, iTable, piMoved);
57417   sqlite3BtreeLeave(p);
57418   return rc;
57419 }
57420
57421
57422 /*
57423 ** This function may only be called if the b-tree connection already
57424 ** has a read or write transaction open on the database.
57425 **
57426 ** Read the meta-information out of a database file.  Meta[0]
57427 ** is the number of free pages currently in the database.  Meta[1]
57428 ** through meta[15] are available for use by higher layers.  Meta[0]
57429 ** is read-only, the others are read/write.
57430 **
57431 ** The schema layer numbers meta values differently.  At the schema
57432 ** layer (and the SetCookie and ReadCookie opcodes) the number of
57433 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
57434 */
57435 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
57436   BtShared *pBt = p->pBt;
57437
57438   sqlite3BtreeEnter(p);
57439   assert( p->inTrans>TRANS_NONE );
57440   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
57441   assert( pBt->pPage1 );
57442   assert( idx>=0 && idx<=15 );
57443
57444   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
57445
57446   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
57447   ** database, mark the database as read-only.  */
57448 #ifdef SQLITE_OMIT_AUTOVACUUM
57449   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
57450     pBt->btsFlags |= BTS_READ_ONLY;
57451   }
57452 #endif
57453
57454   sqlite3BtreeLeave(p);
57455 }
57456
57457 /*
57458 ** Write meta-information back into the database.  Meta[0] is
57459 ** read-only and may not be written.
57460 */
57461 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
57462   BtShared *pBt = p->pBt;
57463   unsigned char *pP1;
57464   int rc;
57465   assert( idx>=1 && idx<=15 );
57466   sqlite3BtreeEnter(p);
57467   assert( p->inTrans==TRANS_WRITE );
57468   assert( pBt->pPage1!=0 );
57469   pP1 = pBt->pPage1->aData;
57470   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57471   if( rc==SQLITE_OK ){
57472     put4byte(&pP1[36 + idx*4], iMeta);
57473 #ifndef SQLITE_OMIT_AUTOVACUUM
57474     if( idx==BTREE_INCR_VACUUM ){
57475       assert( pBt->autoVacuum || iMeta==0 );
57476       assert( iMeta==0 || iMeta==1 );
57477       pBt->incrVacuum = (u8)iMeta;
57478     }
57479 #endif
57480   }
57481   sqlite3BtreeLeave(p);
57482   return rc;
57483 }
57484
57485 #ifndef SQLITE_OMIT_BTREECOUNT
57486 /*
57487 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
57488 ** number of entries in the b-tree and write the result to *pnEntry.
57489 **
57490 ** SQLITE_OK is returned if the operation is successfully executed.
57491 ** Otherwise, if an error is encountered (i.e. an IO error or database
57492 ** corruption) an SQLite error code is returned.
57493 */
57494 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
57495   i64 nEntry = 0;                      /* Value to return in *pnEntry */
57496   int rc;                              /* Return code */
57497
57498   if( pCur->pgnoRoot==0 ){
57499     *pnEntry = 0;
57500     return SQLITE_OK;
57501   }
57502   rc = moveToRoot(pCur);
57503
57504   /* Unless an error occurs, the following loop runs one iteration for each
57505   ** page in the B-Tree structure (not including overflow pages).
57506   */
57507   while( rc==SQLITE_OK ){
57508     int iIdx;                          /* Index of child node in parent */
57509     MemPage *pPage;                    /* Current page of the b-tree */
57510
57511     /* If this is a leaf page or the tree is not an int-key tree, then
57512     ** this page contains countable entries. Increment the entry counter
57513     ** accordingly.
57514     */
57515     pPage = pCur->apPage[pCur->iPage];
57516     if( pPage->leaf || !pPage->intKey ){
57517       nEntry += pPage->nCell;
57518     }
57519
57520     /* pPage is a leaf node. This loop navigates the cursor so that it
57521     ** points to the first interior cell that it points to the parent of
57522     ** the next page in the tree that has not yet been visited. The
57523     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
57524     ** of the page, or to the number of cells in the page if the next page
57525     ** to visit is the right-child of its parent.
57526     **
57527     ** If all pages in the tree have been visited, return SQLITE_OK to the
57528     ** caller.
57529     */
57530     if( pPage->leaf ){
57531       do {
57532         if( pCur->iPage==0 ){
57533           /* All pages of the b-tree have been visited. Return successfully. */
57534           *pnEntry = nEntry;
57535           return SQLITE_OK;
57536         }
57537         moveToParent(pCur);
57538       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
57539
57540       pCur->aiIdx[pCur->iPage]++;
57541       pPage = pCur->apPage[pCur->iPage];
57542     }
57543
57544     /* Descend to the child node of the cell that the cursor currently
57545     ** points at. This is the right-child if (iIdx==pPage->nCell).
57546     */
57547     iIdx = pCur->aiIdx[pCur->iPage];
57548     if( iIdx==pPage->nCell ){
57549       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57550     }else{
57551       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
57552     }
57553   }
57554
57555   /* An error has occurred. Return an error code. */
57556   return rc;
57557 }
57558 #endif
57559
57560 /*
57561 ** Return the pager associated with a BTree.  This routine is used for
57562 ** testing and debugging only.
57563 */
57564 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
57565   return p->pBt->pPager;
57566 }
57567
57568 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57569 /*
57570 ** Append a message to the error message string.
57571 */
57572 static void checkAppendMsg(
57573   IntegrityCk *pCheck,
57574   char *zMsg1,
57575   const char *zFormat,
57576   ...
57577 ){
57578   va_list ap;
57579   if( !pCheck->mxErr ) return;
57580   pCheck->mxErr--;
57581   pCheck->nErr++;
57582   va_start(ap, zFormat);
57583   if( pCheck->errMsg.nChar ){
57584     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
57585   }
57586   if( zMsg1 ){
57587     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
57588   }
57589   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
57590   va_end(ap);
57591   if( pCheck->errMsg.mallocFailed ){
57592     pCheck->mallocFailed = 1;
57593   }
57594 }
57595 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57596
57597 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57598
57599 /*
57600 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
57601 ** corresponds to page iPg is already set.
57602 */
57603 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57604   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57605   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
57606 }
57607
57608 /*
57609 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
57610 */
57611 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57612   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57613   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
57614 }
57615
57616
57617 /*
57618 ** Add 1 to the reference count for page iPage.  If this is the second
57619 ** reference to the page, add an error message to pCheck->zErrMsg.
57620 ** Return 1 if there are 2 ore more references to the page and 0 if
57621 ** if this is the first reference to the page.
57622 **
57623 ** Also check that the page number is in bounds.
57624 */
57625 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
57626   if( iPage==0 ) return 1;
57627   if( iPage>pCheck->nPage ){
57628     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
57629     return 1;
57630   }
57631   if( getPageReferenced(pCheck, iPage) ){
57632     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
57633     return 1;
57634   }
57635   setPageReferenced(pCheck, iPage);
57636   return 0;
57637 }
57638
57639 #ifndef SQLITE_OMIT_AUTOVACUUM
57640 /*
57641 ** Check that the entry in the pointer-map for page iChild maps to
57642 ** page iParent, pointer type ptrType. If not, append an error message
57643 ** to pCheck.
57644 */
57645 static void checkPtrmap(
57646   IntegrityCk *pCheck,   /* Integrity check context */
57647   Pgno iChild,           /* Child page number */
57648   u8 eType,              /* Expected pointer map type */
57649   Pgno iParent,          /* Expected pointer map parent page number */
57650   char *zContext         /* Context description (used for error msg) */
57651 ){
57652   int rc;
57653   u8 ePtrmapType;
57654   Pgno iPtrmapParent;
57655
57656   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
57657   if( rc!=SQLITE_OK ){
57658     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
57659     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
57660     return;
57661   }
57662
57663   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
57664     checkAppendMsg(pCheck, zContext,
57665       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
57666       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
57667   }
57668 }
57669 #endif
57670
57671 /*
57672 ** Check the integrity of the freelist or of an overflow page list.
57673 ** Verify that the number of pages on the list is N.
57674 */
57675 static void checkList(
57676   IntegrityCk *pCheck,  /* Integrity checking context */
57677   int isFreeList,       /* True for a freelist.  False for overflow page list */
57678   int iPage,            /* Page number for first page in the list */
57679   int N,                /* Expected number of pages in the list */
57680   char *zContext        /* Context for error messages */
57681 ){
57682   int i;
57683   int expected = N;
57684   int iFirst = iPage;
57685   while( N-- > 0 && pCheck->mxErr ){
57686     DbPage *pOvflPage;
57687     unsigned char *pOvflData;
57688     if( iPage<1 ){
57689       checkAppendMsg(pCheck, zContext,
57690          "%d of %d pages missing from overflow list starting at %d",
57691           N+1, expected, iFirst);
57692       break;
57693     }
57694     if( checkRef(pCheck, iPage, zContext) ) break;
57695     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57696       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57697       break;
57698     }
57699     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
57700     if( isFreeList ){
57701       int n = get4byte(&pOvflData[4]);
57702 #ifndef SQLITE_OMIT_AUTOVACUUM
57703       if( pCheck->pBt->autoVacuum ){
57704         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57705       }
57706 #endif
57707       if( n>(int)pCheck->pBt->usableSize/4-2 ){
57708         checkAppendMsg(pCheck, zContext,
57709            "freelist leaf count too big on page %d", iPage);
57710         N--;
57711       }else{
57712         for(i=0; i<n; i++){
57713           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57714 #ifndef SQLITE_OMIT_AUTOVACUUM
57715           if( pCheck->pBt->autoVacuum ){
57716             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57717           }
57718 #endif
57719           checkRef(pCheck, iFreePage, zContext);
57720         }
57721         N -= n;
57722       }
57723     }
57724 #ifndef SQLITE_OMIT_AUTOVACUUM
57725     else{
57726       /* If this database supports auto-vacuum and iPage is not the last
57727       ** page in this overflow list, check that the pointer-map entry for
57728       ** the following page matches iPage.
57729       */
57730       if( pCheck->pBt->autoVacuum && N>0 ){
57731         i = get4byte(pOvflData);
57732         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57733       }
57734     }
57735 #endif
57736     iPage = get4byte(pOvflData);
57737     sqlite3PagerUnref(pOvflPage);
57738   }
57739 }
57740 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57741
57742 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57743 /*
57744 ** Do various sanity checks on a single page of a tree.  Return
57745 ** the tree depth.  Root pages return 0.  Parents of root pages
57746 ** return 1, and so forth.
57747 **
57748 ** These checks are done:
57749 **
57750 **      1.  Make sure that cells and freeblocks do not overlap
57751 **          but combine to completely cover the page.
57752 **  NO  2.  Make sure cell keys are in order.
57753 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
57754 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57755 **      5.  Check the integrity of overflow pages.
57756 **      6.  Recursively call checkTreePage on all children.
57757 **      7.  Verify that the depth of all children is the same.
57758 **      8.  Make sure this page is at least 33% full or else it is
57759 **          the root of the tree.
57760 */
57761 static int checkTreePage(
57762   IntegrityCk *pCheck,  /* Context for the sanity check */
57763   int iPage,            /* Page number of the page to check */
57764   char *zParentContext, /* Parent context */
57765   i64 *pnParentMinKey,
57766   i64 *pnParentMaxKey
57767 ){
57768   MemPage *pPage;
57769   int i, rc, depth, d2, pgno, cnt;
57770   int hdr, cellStart;
57771   int nCell;
57772   u8 *data;
57773   BtShared *pBt;
57774   int usableSize;
57775   char zContext[100];
57776   char *hit = 0;
57777   i64 nMinKey = 0;
57778   i64 nMaxKey = 0;
57779
57780   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57781
57782   /* Check that the page exists
57783   */
57784   pBt = pCheck->pBt;
57785   usableSize = pBt->usableSize;
57786   if( iPage==0 ) return 0;
57787   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57788   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
57789     checkAppendMsg(pCheck, zContext,
57790        "unable to get the page. error code=%d", rc);
57791     return 0;
57792   }
57793
57794   /* Clear MemPage.isInit to make sure the corruption detection code in
57795   ** btreeInitPage() is executed.  */
57796   pPage->isInit = 0;
57797   if( (rc = btreeInitPage(pPage))!=0 ){
57798     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
57799     checkAppendMsg(pCheck, zContext,
57800                    "btreeInitPage() returns error code %d", rc);
57801     releasePage(pPage);
57802     return 0;
57803   }
57804
57805   /* Check out all the cells.
57806   */
57807   depth = 0;
57808   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57809     u8 *pCell;
57810     u32 sz;
57811     CellInfo info;
57812
57813     /* Check payload overflow pages
57814     */
57815     sqlite3_snprintf(sizeof(zContext), zContext,
57816              "On tree page %d cell %d: ", iPage, i);
57817     pCell = findCell(pPage,i);
57818     btreeParseCellPtr(pPage, pCell, &info);
57819     sz = info.nData;
57820     if( !pPage->intKey ) sz += (int)info.nKey;
57821     /* For intKey pages, check that the keys are in order.
57822     */
57823     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57824     else{
57825       if( info.nKey <= nMaxKey ){
57826         checkAppendMsg(pCheck, zContext,
57827             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57828       }
57829       nMaxKey = info.nKey;
57830     }
57831     assert( sz==info.nPayload );
57832     if( (sz>info.nLocal)
57833      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57834     ){
57835       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57836       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57837 #ifndef SQLITE_OMIT_AUTOVACUUM
57838       if( pBt->autoVacuum ){
57839         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57840       }
57841 #endif
57842       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57843     }
57844
57845     /* Check sanity of left child page.
57846     */
57847     if( !pPage->leaf ){
57848       pgno = get4byte(pCell);
57849 #ifndef SQLITE_OMIT_AUTOVACUUM
57850       if( pBt->autoVacuum ){
57851         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57852       }
57853 #endif
57854       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57855       if( i>0 && d2!=depth ){
57856         checkAppendMsg(pCheck, zContext, "Child page depth differs");
57857       }
57858       depth = d2;
57859     }
57860   }
57861
57862   if( !pPage->leaf ){
57863     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57864     sqlite3_snprintf(sizeof(zContext), zContext,
57865                      "On page %d at right child: ", iPage);
57866 #ifndef SQLITE_OMIT_AUTOVACUUM
57867     if( pBt->autoVacuum ){
57868       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57869     }
57870 #endif
57871     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57872   }
57873
57874   /* For intKey leaf pages, check that the min/max keys are in order
57875   ** with any left/parent/right pages.
57876   */
57877   if( pPage->leaf && pPage->intKey ){
57878     /* if we are a left child page */
57879     if( pnParentMinKey ){
57880       /* if we are the left most child page */
57881       if( !pnParentMaxKey ){
57882         if( nMaxKey > *pnParentMinKey ){
57883           checkAppendMsg(pCheck, zContext,
57884               "Rowid %lld out of order (max larger than parent min of %lld)",
57885               nMaxKey, *pnParentMinKey);
57886         }
57887       }else{
57888         if( nMinKey <= *pnParentMinKey ){
57889           checkAppendMsg(pCheck, zContext,
57890               "Rowid %lld out of order (min less than parent min of %lld)",
57891               nMinKey, *pnParentMinKey);
57892         }
57893         if( nMaxKey > *pnParentMaxKey ){
57894           checkAppendMsg(pCheck, zContext,
57895               "Rowid %lld out of order (max larger than parent max of %lld)",
57896               nMaxKey, *pnParentMaxKey);
57897         }
57898         *pnParentMinKey = nMaxKey;
57899       }
57900     /* else if we're a right child page */
57901     } else if( pnParentMaxKey ){
57902       if( nMinKey <= *pnParentMaxKey ){
57903         checkAppendMsg(pCheck, zContext,
57904             "Rowid %lld out of order (min less than parent max of %lld)",
57905             nMinKey, *pnParentMaxKey);
57906       }
57907     }
57908   }
57909
57910   /* Check for complete coverage of the page
57911   */
57912   data = pPage->aData;
57913   hdr = pPage->hdrOffset;
57914   hit = sqlite3PageMalloc( pBt->pageSize );
57915   if( hit==0 ){
57916     pCheck->mallocFailed = 1;
57917   }else{
57918     int contentOffset = get2byteNotZero(&data[hdr+5]);
57919     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
57920     memset(hit+contentOffset, 0, usableSize-contentOffset);
57921     memset(hit, 1, contentOffset);
57922     nCell = get2byte(&data[hdr+3]);
57923     cellStart = hdr + 12 - 4*pPage->leaf;
57924     for(i=0; i<nCell; i++){
57925       int pc = get2byte(&data[cellStart+i*2]);
57926       u32 size = 65536;
57927       int j;
57928       if( pc<=usableSize-4 ){
57929         size = cellSizePtr(pPage, &data[pc]);
57930       }
57931       if( (int)(pc+size-1)>=usableSize ){
57932         checkAppendMsg(pCheck, 0,
57933             "Corruption detected in cell %d on page %d",i,iPage);
57934       }else{
57935         for(j=pc+size-1; j>=pc; j--) hit[j]++;
57936       }
57937     }
57938     i = get2byte(&data[hdr+1]);
57939     while( i>0 ){
57940       int size, j;
57941       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
57942       size = get2byte(&data[i+2]);
57943       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
57944       for(j=i+size-1; j>=i; j--) hit[j]++;
57945       j = get2byte(&data[i]);
57946       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
57947       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
57948       i = j;
57949     }
57950     for(i=cnt=0; i<usableSize; i++){
57951       if( hit[i]==0 ){
57952         cnt++;
57953       }else if( hit[i]>1 ){
57954         checkAppendMsg(pCheck, 0,
57955           "Multiple uses for byte %d of page %d", i, iPage);
57956         break;
57957       }
57958     }
57959     if( cnt!=data[hdr+7] ){
57960       checkAppendMsg(pCheck, 0,
57961           "Fragmentation of %d bytes reported as %d on page %d",
57962           cnt, data[hdr+7], iPage);
57963     }
57964   }
57965   sqlite3PageFree(hit);
57966   releasePage(pPage);
57967   return depth+1;
57968 }
57969 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57970
57971 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57972 /*
57973 ** This routine does a complete check of the given BTree file.  aRoot[] is
57974 ** an array of pages numbers were each page number is the root page of
57975 ** a table.  nRoot is the number of entries in aRoot.
57976 **
57977 ** A read-only or read-write transaction must be opened before calling
57978 ** this function.
57979 **
57980 ** Write the number of error seen in *pnErr.  Except for some memory
57981 ** allocation errors,  an error message held in memory obtained from
57982 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
57983 ** returned.  If a memory allocation error occurs, NULL is returned.
57984 */
57985 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
57986   Btree *p,     /* The btree to be checked */
57987   int *aRoot,   /* An array of root pages numbers for individual trees */
57988   int nRoot,    /* Number of entries in aRoot[] */
57989   int mxErr,    /* Stop reporting errors after this many */
57990   int *pnErr    /* Write number of errors seen to this variable */
57991 ){
57992   Pgno i;
57993   int nRef;
57994   IntegrityCk sCheck;
57995   BtShared *pBt = p->pBt;
57996   char zErr[100];
57997
57998   sqlite3BtreeEnter(p);
57999   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
58000   nRef = sqlite3PagerRefcount(pBt->pPager);
58001   sCheck.pBt = pBt;
58002   sCheck.pPager = pBt->pPager;
58003   sCheck.nPage = btreePagecount(sCheck.pBt);
58004   sCheck.mxErr = mxErr;
58005   sCheck.nErr = 0;
58006   sCheck.mallocFailed = 0;
58007   *pnErr = 0;
58008   if( sCheck.nPage==0 ){
58009     sqlite3BtreeLeave(p);
58010     return 0;
58011   }
58012
58013   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
58014   if( !sCheck.aPgRef ){
58015     *pnErr = 1;
58016     sqlite3BtreeLeave(p);
58017     return 0;
58018   }
58019   i = PENDING_BYTE_PAGE(pBt);
58020   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
58021   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
58022   sCheck.errMsg.useMalloc = 2;
58023
58024   /* Check the integrity of the freelist
58025   */
58026   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
58027             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
58028
58029   /* Check all the tables.
58030   */
58031   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
58032     if( aRoot[i]==0 ) continue;
58033 #ifndef SQLITE_OMIT_AUTOVACUUM
58034     if( pBt->autoVacuum && aRoot[i]>1 ){
58035       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
58036     }
58037 #endif
58038     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
58039   }
58040
58041   /* Make sure every page in the file is referenced
58042   */
58043   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
58044 #ifdef SQLITE_OMIT_AUTOVACUUM
58045     if( getPageReferenced(&sCheck, i)==0 ){
58046       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
58047     }
58048 #else
58049     /* If the database supports auto-vacuum, make sure no tables contain
58050     ** references to pointer-map pages.
58051     */
58052     if( getPageReferenced(&sCheck, i)==0 &&
58053        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
58054       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
58055     }
58056     if( getPageReferenced(&sCheck, i)!=0 &&
58057        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
58058       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
58059     }
58060 #endif
58061   }
58062
58063   /* Make sure this analysis did not leave any unref() pages.
58064   ** This is an internal consistency check; an integrity check
58065   ** of the integrity check.
58066   */
58067   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
58068     checkAppendMsg(&sCheck, 0,
58069       "Outstanding page count goes from %d to %d during this analysis",
58070       nRef, sqlite3PagerRefcount(pBt->pPager)
58071     );
58072   }
58073
58074   /* Clean  up and report errors.
58075   */
58076   sqlite3BtreeLeave(p);
58077   sqlite3_free(sCheck.aPgRef);
58078   if( sCheck.mallocFailed ){
58079     sqlite3StrAccumReset(&sCheck.errMsg);
58080     *pnErr = sCheck.nErr+1;
58081     return 0;
58082   }
58083   *pnErr = sCheck.nErr;
58084   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
58085   return sqlite3StrAccumFinish(&sCheck.errMsg);
58086 }
58087 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58088
58089 /*
58090 ** Return the full pathname of the underlying database file.  Return
58091 ** an empty string if the database is in-memory or a TEMP database.
58092 **
58093 ** The pager filename is invariant as long as the pager is
58094 ** open so it is safe to access without the BtShared mutex.
58095 */
58096 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
58097   assert( p->pBt->pPager!=0 );
58098   return sqlite3PagerFilename(p->pBt->pPager, 1);
58099 }
58100
58101 /*
58102 ** Return the pathname of the journal file for this database. The return
58103 ** value of this routine is the same regardless of whether the journal file
58104 ** has been created or not.
58105 **
58106 ** The pager journal filename is invariant as long as the pager is
58107 ** open so it is safe to access without the BtShared mutex.
58108 */
58109 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
58110   assert( p->pBt->pPager!=0 );
58111   return sqlite3PagerJournalname(p->pBt->pPager);
58112 }
58113
58114 /*
58115 ** Return non-zero if a transaction is active.
58116 */
58117 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
58118   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
58119   return (p && (p->inTrans==TRANS_WRITE));
58120 }
58121
58122 #ifndef SQLITE_OMIT_WAL
58123 /*
58124 ** Run a checkpoint on the Btree passed as the first argument.
58125 **
58126 ** Return SQLITE_LOCKED if this or any other connection has an open
58127 ** transaction on the shared-cache the argument Btree is connected to.
58128 **
58129 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
58130 */
58131 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
58132   int rc = SQLITE_OK;
58133   if( p ){
58134     BtShared *pBt = p->pBt;
58135     sqlite3BtreeEnter(p);
58136     if( pBt->inTransaction!=TRANS_NONE ){
58137       rc = SQLITE_LOCKED;
58138     }else{
58139       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
58140     }
58141     sqlite3BtreeLeave(p);
58142   }
58143   return rc;
58144 }
58145 #endif
58146
58147 /*
58148 ** Return non-zero if a read (or write) transaction is active.
58149 */
58150 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
58151   assert( p );
58152   assert( sqlite3_mutex_held(p->db->mutex) );
58153   return p->inTrans!=TRANS_NONE;
58154 }
58155
58156 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
58157   assert( p );
58158   assert( sqlite3_mutex_held(p->db->mutex) );
58159   return p->nBackup!=0;
58160 }
58161
58162 /*
58163 ** This function returns a pointer to a blob of memory associated with
58164 ** a single shared-btree. The memory is used by client code for its own
58165 ** purposes (for example, to store a high-level schema associated with
58166 ** the shared-btree). The btree layer manages reference counting issues.
58167 **
58168 ** The first time this is called on a shared-btree, nBytes bytes of memory
58169 ** are allocated, zeroed, and returned to the caller. For each subsequent
58170 ** call the nBytes parameter is ignored and a pointer to the same blob
58171 ** of memory returned.
58172 **
58173 ** If the nBytes parameter is 0 and the blob of memory has not yet been
58174 ** allocated, a null pointer is returned. If the blob has already been
58175 ** allocated, it is returned as normal.
58176 **
58177 ** Just before the shared-btree is closed, the function passed as the
58178 ** xFree argument when the memory allocation was made is invoked on the
58179 ** blob of allocated memory. The xFree function should not call sqlite3_free()
58180 ** on the memory, the btree layer does that.
58181 */
58182 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
58183   BtShared *pBt = p->pBt;
58184   sqlite3BtreeEnter(p);
58185   if( !pBt->pSchema && nBytes ){
58186     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
58187     pBt->xFreeSchema = xFree;
58188   }
58189   sqlite3BtreeLeave(p);
58190   return pBt->pSchema;
58191 }
58192
58193 /*
58194 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
58195 ** btree as the argument handle holds an exclusive lock on the
58196 ** sqlite_master table. Otherwise SQLITE_OK.
58197 */
58198 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
58199   int rc;
58200   assert( sqlite3_mutex_held(p->db->mutex) );
58201   sqlite3BtreeEnter(p);
58202   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
58203   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
58204   sqlite3BtreeLeave(p);
58205   return rc;
58206 }
58207
58208
58209 #ifndef SQLITE_OMIT_SHARED_CACHE
58210 /*
58211 ** Obtain a lock on the table whose root page is iTab.  The
58212 ** lock is a write lock if isWritelock is true or a read lock
58213 ** if it is false.
58214 */
58215 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
58216   int rc = SQLITE_OK;
58217   assert( p->inTrans!=TRANS_NONE );
58218   if( p->sharable ){
58219     u8 lockType = READ_LOCK + isWriteLock;
58220     assert( READ_LOCK+1==WRITE_LOCK );
58221     assert( isWriteLock==0 || isWriteLock==1 );
58222
58223     sqlite3BtreeEnter(p);
58224     rc = querySharedCacheTableLock(p, iTab, lockType);
58225     if( rc==SQLITE_OK ){
58226       rc = setSharedCacheTableLock(p, iTab, lockType);
58227     }
58228     sqlite3BtreeLeave(p);
58229   }
58230   return rc;
58231 }
58232 #endif
58233
58234 #ifndef SQLITE_OMIT_INCRBLOB
58235 /*
58236 ** Argument pCsr must be a cursor opened for writing on an
58237 ** INTKEY table currently pointing at a valid table entry.
58238 ** This function modifies the data stored as part of that entry.
58239 **
58240 ** Only the data content may only be modified, it is not possible to
58241 ** change the length of the data stored. If this function is called with
58242 ** parameters that attempt to write past the end of the existing data,
58243 ** no modifications are made and SQLITE_CORRUPT is returned.
58244 */
58245 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
58246   int rc;
58247   assert( cursorHoldsMutex(pCsr) );
58248   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
58249   assert( pCsr->isIncrblobHandle );
58250
58251   rc = restoreCursorPosition(pCsr);
58252   if( rc!=SQLITE_OK ){
58253     return rc;
58254   }
58255   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
58256   if( pCsr->eState!=CURSOR_VALID ){
58257     return SQLITE_ABORT;
58258   }
58259
58260   /* Check some assumptions:
58261   **   (a) the cursor is open for writing,
58262   **   (b) there is a read/write transaction open,
58263   **   (c) the connection holds a write-lock on the table (if required),
58264   **   (d) there are no conflicting read-locks, and
58265   **   (e) the cursor points at a valid row of an intKey table.
58266   */
58267   if( !pCsr->wrFlag ){
58268     return SQLITE_READONLY;
58269   }
58270   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
58271               && pCsr->pBt->inTransaction==TRANS_WRITE );
58272   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
58273   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
58274   assert( pCsr->apPage[pCsr->iPage]->intKey );
58275
58276   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
58277 }
58278
58279 /*
58280 ** Set a flag on this cursor to cache the locations of pages from the
58281 ** overflow list for the current row. This is used by cursors opened
58282 ** for incremental blob IO only.
58283 **
58284 ** This function sets a flag only. The actual page location cache
58285 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
58286 ** accessPayload() (the worker function for sqlite3BtreeData() and
58287 ** sqlite3BtreePutData()).
58288 */
58289 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
58290   assert( cursorHoldsMutex(pCur) );
58291   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
58292   invalidateOverflowCache(pCur);
58293   pCur->isIncrblobHandle = 1;
58294 }
58295 #endif
58296
58297 /*
58298 ** Set both the "read version" (single byte at byte offset 18) and
58299 ** "write version" (single byte at byte offset 19) fields in the database
58300 ** header to iVersion.
58301 */
58302 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
58303   BtShared *pBt = pBtree->pBt;
58304   int rc;                         /* Return code */
58305
58306   assert( iVersion==1 || iVersion==2 );
58307
58308   /* If setting the version fields to 1, do not automatically open the
58309   ** WAL connection, even if the version fields are currently set to 2.
58310   */
58311   pBt->btsFlags &= ~BTS_NO_WAL;
58312   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
58313
58314   rc = sqlite3BtreeBeginTrans(pBtree, 0);
58315   if( rc==SQLITE_OK ){
58316     u8 *aData = pBt->pPage1->aData;
58317     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
58318       rc = sqlite3BtreeBeginTrans(pBtree, 2);
58319       if( rc==SQLITE_OK ){
58320         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58321         if( rc==SQLITE_OK ){
58322           aData[18] = (u8)iVersion;
58323           aData[19] = (u8)iVersion;
58324         }
58325       }
58326     }
58327   }
58328
58329   pBt->btsFlags &= ~BTS_NO_WAL;
58330   return rc;
58331 }
58332
58333 /*
58334 ** set the mask of hint flags for cursor pCsr. Currently the only valid
58335 ** values are 0 and BTREE_BULKLOAD.
58336 */
58337 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
58338   assert( mask==BTREE_BULKLOAD || mask==0 );
58339   pCsr->hints = mask;
58340 }
58341
58342 /************** End of btree.c ***********************************************/
58343 /************** Begin file backup.c ******************************************/
58344 /*
58345 ** 2009 January 28
58346 **
58347 ** The author disclaims copyright to this source code.  In place of
58348 ** a legal notice, here is a blessing:
58349 **
58350 **    May you do good and not evil.
58351 **    May you find forgiveness for yourself and forgive others.
58352 **    May you share freely, never taking more than you give.
58353 **
58354 *************************************************************************
58355 ** This file contains the implementation of the sqlite3_backup_XXX()
58356 ** API functions and the related features.
58357 */
58358
58359 /* Macro to find the minimum of two numeric values.
58360 */
58361 #ifndef MIN
58362 # define MIN(x,y) ((x)<(y)?(x):(y))
58363 #endif
58364
58365 /*
58366 ** Structure allocated for each backup operation.
58367 */
58368 struct sqlite3_backup {
58369   sqlite3* pDestDb;        /* Destination database handle */
58370   Btree *pDest;            /* Destination b-tree file */
58371   u32 iDestSchema;         /* Original schema cookie in destination */
58372   int bDestLocked;         /* True once a write-transaction is open on pDest */
58373
58374   Pgno iNext;              /* Page number of the next source page to copy */
58375   sqlite3* pSrcDb;         /* Source database handle */
58376   Btree *pSrc;             /* Source b-tree file */
58377
58378   int rc;                  /* Backup process error code */
58379
58380   /* These two variables are set by every call to backup_step(). They are
58381   ** read by calls to backup_remaining() and backup_pagecount().
58382   */
58383   Pgno nRemaining;         /* Number of pages left to copy */
58384   Pgno nPagecount;         /* Total number of pages to copy */
58385
58386   int isAttached;          /* True once backup has been registered with pager */
58387   sqlite3_backup *pNext;   /* Next backup associated with source pager */
58388 };
58389
58390 /*
58391 ** THREAD SAFETY NOTES:
58392 **
58393 **   Once it has been created using backup_init(), a single sqlite3_backup
58394 **   structure may be accessed via two groups of thread-safe entry points:
58395 **
58396 **     * Via the sqlite3_backup_XXX() API function backup_step() and
58397 **       backup_finish(). Both these functions obtain the source database
58398 **       handle mutex and the mutex associated with the source BtShared
58399 **       structure, in that order.
58400 **
58401 **     * Via the BackupUpdate() and BackupRestart() functions, which are
58402 **       invoked by the pager layer to report various state changes in
58403 **       the page cache associated with the source database. The mutex
58404 **       associated with the source database BtShared structure will always
58405 **       be held when either of these functions are invoked.
58406 **
58407 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
58408 **   backup_pagecount() are not thread-safe functions. If they are called
58409 **   while some other thread is calling backup_step() or backup_finish(),
58410 **   the values returned may be invalid. There is no way for a call to
58411 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
58412 **   or backup_pagecount().
58413 **
58414 **   Depending on the SQLite configuration, the database handles and/or
58415 **   the Btree objects may have their own mutexes that require locking.
58416 **   Non-sharable Btrees (in-memory databases for example), do not have
58417 **   associated mutexes.
58418 */
58419
58420 /*
58421 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
58422 ** in connection handle pDb. If such a database cannot be found, return
58423 ** a NULL pointer and write an error message to pErrorDb.
58424 **
58425 ** If the "temp" database is requested, it may need to be opened by this
58426 ** function. If an error occurs while doing so, return 0 and write an
58427 ** error message to pErrorDb.
58428 */
58429 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
58430   int i = sqlite3FindDbName(pDb, zDb);
58431
58432   if( i==1 ){
58433     Parse *pParse;
58434     int rc = 0;
58435     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
58436     if( pParse==0 ){
58437       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
58438       rc = SQLITE_NOMEM;
58439     }else{
58440       pParse->db = pDb;
58441       if( sqlite3OpenTempDatabase(pParse) ){
58442         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
58443         rc = SQLITE_ERROR;
58444       }
58445       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
58446       sqlite3StackFree(pErrorDb, pParse);
58447     }
58448     if( rc ){
58449       return 0;
58450     }
58451   }
58452
58453   if( i<0 ){
58454     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
58455     return 0;
58456   }
58457
58458   return pDb->aDb[i].pBt;
58459 }
58460
58461 /*
58462 ** Attempt to set the page size of the destination to match the page size
58463 ** of the source.
58464 */
58465 static int setDestPgsz(sqlite3_backup *p){
58466   int rc;
58467   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
58468   return rc;
58469 }
58470
58471 /*
58472 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
58473 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
58474 ** a pointer to the new sqlite3_backup object.
58475 **
58476 ** If an error occurs, NULL is returned and an error code and error message
58477 ** stored in database handle pDestDb.
58478 */
58479 SQLITE_API sqlite3_backup *sqlite3_backup_init(
58480   sqlite3* pDestDb,                     /* Database to write to */
58481   const char *zDestDb,                  /* Name of database within pDestDb */
58482   sqlite3* pSrcDb,                      /* Database connection to read from */
58483   const char *zSrcDb                    /* Name of database within pSrcDb */
58484 ){
58485   sqlite3_backup *p;                    /* Value to return */
58486
58487   /* Lock the source database handle. The destination database
58488   ** handle is not locked in this routine, but it is locked in
58489   ** sqlite3_backup_step(). The user is required to ensure that no
58490   ** other thread accesses the destination handle for the duration
58491   ** of the backup operation.  Any attempt to use the destination
58492   ** database connection while a backup is in progress may cause
58493   ** a malfunction or a deadlock.
58494   */
58495   sqlite3_mutex_enter(pSrcDb->mutex);
58496   sqlite3_mutex_enter(pDestDb->mutex);
58497
58498   if( pSrcDb==pDestDb ){
58499     sqlite3Error(
58500         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
58501     );
58502     p = 0;
58503   }else {
58504     /* Allocate space for a new sqlite3_backup object...
58505     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58506     ** call to sqlite3_backup_init() and is destroyed by a call to
58507     ** sqlite3_backup_finish(). */
58508     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
58509     if( !p ){
58510       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
58511     }
58512   }
58513
58514   /* If the allocation succeeded, populate the new object. */
58515   if( p ){
58516     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
58517     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
58518     p->pDestDb = pDestDb;
58519     p->pSrcDb = pSrcDb;
58520     p->iNext = 1;
58521     p->isAttached = 0;
58522
58523     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
58524       /* One (or both) of the named databases did not exist or an OOM
58525       ** error was hit.  The error has already been written into the
58526       ** pDestDb handle.  All that is left to do here is free the
58527       ** sqlite3_backup structure.
58528       */
58529       sqlite3_free(p);
58530       p = 0;
58531     }
58532   }
58533   if( p ){
58534     p->pSrc->nBackup++;
58535   }
58536
58537   sqlite3_mutex_leave(pDestDb->mutex);
58538   sqlite3_mutex_leave(pSrcDb->mutex);
58539   return p;
58540 }
58541
58542 /*
58543 ** Argument rc is an SQLite error code. Return true if this error is
58544 ** considered fatal if encountered during a backup operation. All errors
58545 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
58546 */
58547 static int isFatalError(int rc){
58548   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
58549 }
58550
58551 /*
58552 ** Parameter zSrcData points to a buffer containing the data for
58553 ** page iSrcPg from the source database. Copy this data into the
58554 ** destination database.
58555 */
58556 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
58557   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
58558   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
58559   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
58560   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
58561   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
58562 #ifdef SQLITE_HAS_CODEC
58563   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
58564   ** guaranteed that the shared-mutex is held by this thread, handle
58565   ** p->pSrc may not actually be the owner.  */
58566   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
58567   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
58568 #endif
58569   int rc = SQLITE_OK;
58570   i64 iOff;
58571
58572   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
58573   assert( p->bDestLocked );
58574   assert( !isFatalError(p->rc) );
58575   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
58576   assert( zSrcData );
58577
58578   /* Catch the case where the destination is an in-memory database and the
58579   ** page sizes of the source and destination differ.
58580   */
58581   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
58582     rc = SQLITE_READONLY;
58583   }
58584
58585 #ifdef SQLITE_HAS_CODEC
58586   /* Backup is not possible if the page size of the destination is changing
58587   ** and a codec is in use.
58588   */
58589   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
58590     rc = SQLITE_READONLY;
58591   }
58592
58593   /* Backup is not possible if the number of bytes of reserve space differ
58594   ** between source and destination.  If there is a difference, try to
58595   ** fix the destination to agree with the source.  If that is not possible,
58596   ** then the backup cannot proceed.
58597   */
58598   if( nSrcReserve!=nDestReserve ){
58599     u32 newPgsz = nSrcPgsz;
58600     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
58601     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
58602   }
58603 #endif
58604
58605   /* This loop runs once for each destination page spanned by the source
58606   ** page. For each iteration, variable iOff is set to the byte offset
58607   ** of the destination page.
58608   */
58609   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
58610     DbPage *pDestPg = 0;
58611     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
58612     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
58613     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
58614      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
58615     ){
58616       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
58617       u8 *zDestData = sqlite3PagerGetData(pDestPg);
58618       u8 *zOut = &zDestData[iOff%nDestPgsz];
58619
58620       /* Copy the data from the source page into the destination page.
58621       ** Then clear the Btree layer MemPage.isInit flag. Both this module
58622       ** and the pager code use this trick (clearing the first byte
58623       ** of the page 'extra' space to invalidate the Btree layers
58624       ** cached parse of the page). MemPage.isInit is marked
58625       ** "MUST BE FIRST" for this purpose.
58626       */
58627       memcpy(zOut, zIn, nCopy);
58628       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
58629     }
58630     sqlite3PagerUnref(pDestPg);
58631   }
58632
58633   return rc;
58634 }
58635
58636 /*
58637 ** If pFile is currently larger than iSize bytes, then truncate it to
58638 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
58639 ** this function is a no-op.
58640 **
58641 ** Return SQLITE_OK if everything is successful, or an SQLite error
58642 ** code if an error occurs.
58643 */
58644 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
58645   i64 iCurrent;
58646   int rc = sqlite3OsFileSize(pFile, &iCurrent);
58647   if( rc==SQLITE_OK && iCurrent>iSize ){
58648     rc = sqlite3OsTruncate(pFile, iSize);
58649   }
58650   return rc;
58651 }
58652
58653 /*
58654 ** Register this backup object with the associated source pager for
58655 ** callbacks when pages are changed or the cache invalidated.
58656 */
58657 static void attachBackupObject(sqlite3_backup *p){
58658   sqlite3_backup **pp;
58659   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
58660   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58661   p->pNext = *pp;
58662   *pp = p;
58663   p->isAttached = 1;
58664 }
58665
58666 /*
58667 ** Copy nPage pages from the source b-tree to the destination.
58668 */
58669 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
58670   int rc;
58671   int destMode;       /* Destination journal mode */
58672   int pgszSrc = 0;    /* Source page size */
58673   int pgszDest = 0;   /* Destination page size */
58674
58675   sqlite3_mutex_enter(p->pSrcDb->mutex);
58676   sqlite3BtreeEnter(p->pSrc);
58677   if( p->pDestDb ){
58678     sqlite3_mutex_enter(p->pDestDb->mutex);
58679   }
58680
58681   rc = p->rc;
58682   if( !isFatalError(rc) ){
58683     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
58684     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
58685     int ii;                            /* Iterator variable */
58686     int nSrcPage = -1;                 /* Size of source db in pages */
58687     int bCloseTrans = 0;               /* True if src db requires unlocking */
58688
58689     /* If the source pager is currently in a write-transaction, return
58690     ** SQLITE_BUSY immediately.
58691     */
58692     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
58693       rc = SQLITE_BUSY;
58694     }else{
58695       rc = SQLITE_OK;
58696     }
58697
58698     /* Lock the destination database, if it is not locked already. */
58699     if( SQLITE_OK==rc && p->bDestLocked==0
58700      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
58701     ){
58702       p->bDestLocked = 1;
58703       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58704     }
58705
58706     /* If there is no open read-transaction on the source database, open
58707     ** one now. If a transaction is opened here, then it will be closed
58708     ** before this function exits.
58709     */
58710     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
58711       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
58712       bCloseTrans = 1;
58713     }
58714
58715     /* Do not allow backup if the destination database is in WAL mode
58716     ** and the page sizes are different between source and destination */
58717     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
58718     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
58719     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
58720     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58721       rc = SQLITE_READONLY;
58722     }
58723
58724     /* Now that there is a read-lock on the source database, query the
58725     ** source pager for the number of pages in the database.
58726     */
58727     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
58728     assert( nSrcPage>=0 );
58729     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58730       const Pgno iSrcPg = p->iNext;                 /* Source page number */
58731       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58732         DbPage *pSrcPg;                             /* Source page object */
58733         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58734         if( rc==SQLITE_OK ){
58735           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
58736           sqlite3PagerUnref(pSrcPg);
58737         }
58738       }
58739       p->iNext++;
58740     }
58741     if( rc==SQLITE_OK ){
58742       p->nPagecount = nSrcPage;
58743       p->nRemaining = nSrcPage+1-p->iNext;
58744       if( p->iNext>(Pgno)nSrcPage ){
58745         rc = SQLITE_DONE;
58746       }else if( !p->isAttached ){
58747         attachBackupObject(p);
58748       }
58749     }
58750
58751     /* Update the schema version field in the destination database. This
58752     ** is to make sure that the schema-version really does change in
58753     ** the case where the source and destination databases have the
58754     ** same schema version.
58755     */
58756     if( rc==SQLITE_DONE ){
58757       if( nSrcPage==0 ){
58758         rc = sqlite3BtreeNewDb(p->pDest);
58759         nSrcPage = 1;
58760       }
58761       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
58762         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58763       }
58764       if( rc==SQLITE_OK ){
58765         if( p->pDestDb ){
58766           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
58767         }
58768         if( destMode==PAGER_JOURNALMODE_WAL ){
58769           rc = sqlite3BtreeSetVersion(p->pDest, 2);
58770         }
58771       }
58772       if( rc==SQLITE_OK ){
58773         int nDestTruncate;
58774         /* Set nDestTruncate to the final number of pages in the destination
58775         ** database. The complication here is that the destination page
58776         ** size may be different to the source page size.
58777         **
58778         ** If the source page size is smaller than the destination page size,
58779         ** round up. In this case the call to sqlite3OsTruncate() below will
58780         ** fix the size of the file. However it is important to call
58781         ** sqlite3PagerTruncateImage() here so that any pages in the
58782         ** destination file that lie beyond the nDestTruncate page mark are
58783         ** journalled by PagerCommitPhaseOne() before they are destroyed
58784         ** by the file truncation.
58785         */
58786         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
58787         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
58788         if( pgszSrc<pgszDest ){
58789           int ratio = pgszDest/pgszSrc;
58790           nDestTruncate = (nSrcPage+ratio-1)/ratio;
58791           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58792             nDestTruncate--;
58793           }
58794         }else{
58795           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58796         }
58797         assert( nDestTruncate>0 );
58798         sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
58799
58800         if( pgszSrc<pgszDest ){
58801           /* If the source page-size is smaller than the destination page-size,
58802           ** two extra things may need to happen:
58803           **
58804           **   * The destination may need to be truncated, and
58805           **
58806           **   * Data stored on the pages immediately following the
58807           **     pending-byte page in the source database may need to be
58808           **     copied into the destination database.
58809           */
58810           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58811           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
58812           i64 iOff;
58813           i64 iEnd;
58814
58815           assert( pFile );
58816           assert( nDestTruncate==0
58817               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58818                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58819              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58820           ));
58821
58822           /* This call ensures that all data required to recreate the original
58823           ** database has been stored in the journal for pDestPager and the
58824           ** journal synced to disk. So at this point we may safely modify
58825           ** the database file in any way, knowing that if a power failure
58826           ** occurs, the original database will be reconstructed from the
58827           ** journal file.  */
58828           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
58829
58830           /* Write the extra pages and truncate the database file as required */
58831           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58832           for(
58833             iOff=PENDING_BYTE+pgszSrc;
58834             rc==SQLITE_OK && iOff<iEnd;
58835             iOff+=pgszSrc
58836           ){
58837             PgHdr *pSrcPg = 0;
58838             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58839             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58840             if( rc==SQLITE_OK ){
58841               u8 *zData = sqlite3PagerGetData(pSrcPg);
58842               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
58843             }
58844             sqlite3PagerUnref(pSrcPg);
58845           }
58846           if( rc==SQLITE_OK ){
58847             rc = backupTruncateFile(pFile, iSize);
58848           }
58849
58850           /* Sync the database file to disk. */
58851           if( rc==SQLITE_OK ){
58852             rc = sqlite3PagerSync(pDestPager);
58853           }
58854         }else{
58855           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
58856         }
58857
58858         /* Finish committing the transaction to the destination database. */
58859         if( SQLITE_OK==rc
58860          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
58861         ){
58862           rc = SQLITE_DONE;
58863         }
58864       }
58865     }
58866
58867     /* If bCloseTrans is true, then this function opened a read transaction
58868     ** on the source database. Close the read transaction here. There is
58869     ** no need to check the return values of the btree methods here, as
58870     ** "committing" a read-only transaction cannot fail.
58871     */
58872     if( bCloseTrans ){
58873       TESTONLY( int rc2 );
58874       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
58875       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
58876       assert( rc2==SQLITE_OK );
58877     }
58878
58879     if( rc==SQLITE_IOERR_NOMEM ){
58880       rc = SQLITE_NOMEM;
58881     }
58882     p->rc = rc;
58883   }
58884   if( p->pDestDb ){
58885     sqlite3_mutex_leave(p->pDestDb->mutex);
58886   }
58887   sqlite3BtreeLeave(p->pSrc);
58888   sqlite3_mutex_leave(p->pSrcDb->mutex);
58889   return rc;
58890 }
58891
58892 /*
58893 ** Release all resources associated with an sqlite3_backup* handle.
58894 */
58895 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
58896   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
58897   sqlite3 *pSrcDb;                     /* Source database connection */
58898   int rc;                              /* Value to return */
58899
58900   /* Enter the mutexes */
58901   if( p==0 ) return SQLITE_OK;
58902   pSrcDb = p->pSrcDb;
58903   sqlite3_mutex_enter(pSrcDb->mutex);
58904   sqlite3BtreeEnter(p->pSrc);
58905   if( p->pDestDb ){
58906     sqlite3_mutex_enter(p->pDestDb->mutex);
58907   }
58908
58909   /* Detach this backup from the source pager. */
58910   if( p->pDestDb ){
58911     p->pSrc->nBackup--;
58912   }
58913   if( p->isAttached ){
58914     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58915     while( *pp!=p ){
58916       pp = &(*pp)->pNext;
58917     }
58918     *pp = p->pNext;
58919   }
58920
58921   /* If a transaction is still open on the Btree, roll it back. */
58922   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
58923
58924   /* Set the error code of the destination database handle. */
58925   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
58926   sqlite3Error(p->pDestDb, rc, 0);
58927
58928   /* Exit the mutexes and free the backup context structure. */
58929   if( p->pDestDb ){
58930     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
58931   }
58932   sqlite3BtreeLeave(p->pSrc);
58933   if( p->pDestDb ){
58934     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58935     ** call to sqlite3_backup_init() and is destroyed by a call to
58936     ** sqlite3_backup_finish(). */
58937     sqlite3_free(p);
58938   }
58939   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
58940   return rc;
58941 }
58942
58943 /*
58944 ** Return the number of pages still to be backed up as of the most recent
58945 ** call to sqlite3_backup_step().
58946 */
58947 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
58948   return p->nRemaining;
58949 }
58950
58951 /*
58952 ** Return the total number of pages in the source database as of the most
58953 ** recent call to sqlite3_backup_step().
58954 */
58955 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
58956   return p->nPagecount;
58957 }
58958
58959 /*
58960 ** This function is called after the contents of page iPage of the
58961 ** source database have been modified. If page iPage has already been
58962 ** copied into the destination database, then the data written to the
58963 ** destination is now invalidated. The destination copy of iPage needs
58964 ** to be updated with the new data before the backup operation is
58965 ** complete.
58966 **
58967 ** It is assumed that the mutex associated with the BtShared object
58968 ** corresponding to the source database is held when this function is
58969 ** called.
58970 */
58971 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
58972   sqlite3_backup *p;                   /* Iterator variable */
58973   for(p=pBackup; p; p=p->pNext){
58974     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58975     if( !isFatalError(p->rc) && iPage<p->iNext ){
58976       /* The backup process p has already copied page iPage. But now it
58977       ** has been modified by a transaction on the source pager. Copy
58978       ** the new data into the backup.
58979       */
58980       int rc;
58981       assert( p->pDestDb );
58982       sqlite3_mutex_enter(p->pDestDb->mutex);
58983       rc = backupOnePage(p, iPage, aData);
58984       sqlite3_mutex_leave(p->pDestDb->mutex);
58985       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
58986       if( rc!=SQLITE_OK ){
58987         p->rc = rc;
58988       }
58989     }
58990   }
58991 }
58992
58993 /*
58994 ** Restart the backup process. This is called when the pager layer
58995 ** detects that the database has been modified by an external database
58996 ** connection. In this case there is no way of knowing which of the
58997 ** pages that have been copied into the destination database are still
58998 ** valid and which are not, so the entire process needs to be restarted.
58999 **
59000 ** It is assumed that the mutex associated with the BtShared object
59001 ** corresponding to the source database is held when this function is
59002 ** called.
59003 */
59004 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
59005   sqlite3_backup *p;                   /* Iterator variable */
59006   for(p=pBackup; p; p=p->pNext){
59007     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
59008     p->iNext = 1;
59009   }
59010 }
59011
59012 #ifndef SQLITE_OMIT_VACUUM
59013 /*
59014 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
59015 ** must be active for both files.
59016 **
59017 ** The size of file pTo may be reduced by this operation. If anything
59018 ** goes wrong, the transaction on pTo is rolled back. If successful, the
59019 ** transaction is committed before returning.
59020 */
59021 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
59022   int rc;
59023   sqlite3_file *pFd;              /* File descriptor for database pTo */
59024   sqlite3_backup b;
59025   sqlite3BtreeEnter(pTo);
59026   sqlite3BtreeEnter(pFrom);
59027
59028   assert( sqlite3BtreeIsInTrans(pTo) );
59029   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
59030   if( pFd->pMethods ){
59031     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
59032     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
59033     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
59034     if( rc ) goto copy_finished;
59035   }
59036
59037   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
59038   ** to 0. This is used by the implementations of sqlite3_backup_step()
59039   ** and sqlite3_backup_finish() to detect that they are being called
59040   ** from this function, not directly by the user.
59041   */
59042   memset(&b, 0, sizeof(b));
59043   b.pSrcDb = pFrom->db;
59044   b.pSrc = pFrom;
59045   b.pDest = pTo;
59046   b.iNext = 1;
59047
59048   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
59049   ** file. By passing this as the number of pages to copy to
59050   ** sqlite3_backup_step(), we can guarantee that the copy finishes
59051   ** within a single call (unless an error occurs). The assert() statement
59052   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
59053   ** or an error code.
59054   */
59055   sqlite3_backup_step(&b, 0x7FFFFFFF);
59056   assert( b.rc!=SQLITE_OK );
59057   rc = sqlite3_backup_finish(&b);
59058   if( rc==SQLITE_OK ){
59059     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
59060   }else{
59061     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
59062   }
59063
59064   assert( sqlite3BtreeIsInTrans(pTo)==0 );
59065 copy_finished:
59066   sqlite3BtreeLeave(pFrom);
59067   sqlite3BtreeLeave(pTo);
59068   return rc;
59069 }
59070 #endif /* SQLITE_OMIT_VACUUM */
59071
59072 /************** End of backup.c **********************************************/
59073 /************** Begin file vdbemem.c *****************************************/
59074 /*
59075 ** 2004 May 26
59076 **
59077 ** The author disclaims copyright to this source code.  In place of
59078 ** a legal notice, here is a blessing:
59079 **
59080 **    May you do good and not evil.
59081 **    May you find forgiveness for yourself and forgive others.
59082 **    May you share freely, never taking more than you give.
59083 **
59084 *************************************************************************
59085 **
59086 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
59087 ** stores a single value in the VDBE.  Mem is an opaque structure visible
59088 ** only within the VDBE.  Interface routines refer to a Mem using the
59089 ** name sqlite_value
59090 */
59091
59092 /*
59093 ** If pMem is an object with a valid string representation, this routine
59094 ** ensures the internal encoding for the string representation is
59095 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
59096 **
59097 ** If pMem is not a string object, or the encoding of the string
59098 ** representation is already stored using the requested encoding, then this
59099 ** routine is a no-op.
59100 **
59101 ** SQLITE_OK is returned if the conversion is successful (or not required).
59102 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
59103 ** between formats.
59104 */
59105 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
59106   int rc;
59107   assert( (pMem->flags&MEM_RowSet)==0 );
59108   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
59109            || desiredEnc==SQLITE_UTF16BE );
59110   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
59111     return SQLITE_OK;
59112   }
59113   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59114 #ifdef SQLITE_OMIT_UTF16
59115   return SQLITE_ERROR;
59116 #else
59117
59118   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
59119   ** then the encoding of the value may not have changed.
59120   */
59121   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
59122   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
59123   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
59124   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
59125   return rc;
59126 #endif
59127 }
59128
59129 /*
59130 ** Make sure pMem->z points to a writable allocation of at least
59131 ** n bytes.
59132 **
59133 ** If the third argument passed to this function is true, then memory
59134 ** cell pMem must contain a string or blob. In this case the content is
59135 ** preserved. Otherwise, if the third parameter to this function is false,
59136 ** any current string or blob value may be discarded.
59137 **
59138 ** This function sets the MEM_Dyn flag and clears any xDel callback.
59139 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
59140 ** not set, Mem.n is zeroed.
59141 */
59142 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
59143   assert( 1 >=
59144     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
59145     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
59146     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
59147     ((pMem->flags&MEM_Static) ? 1 : 0)
59148   );
59149   assert( (pMem->flags&MEM_RowSet)==0 );
59150
59151   /* If the preserve flag is set to true, then the memory cell must already
59152   ** contain a valid string or blob value.  */
59153   assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
59154
59155   if( n<32 ) n = 32;
59156   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
59157     if( preserve && pMem->z==pMem->zMalloc ){
59158       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
59159       preserve = 0;
59160     }else{
59161       sqlite3DbFree(pMem->db, pMem->zMalloc);
59162       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
59163     }
59164   }
59165
59166   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
59167     memcpy(pMem->zMalloc, pMem->z, pMem->n);
59168   }
59169   if( pMem->flags&MEM_Dyn && pMem->xDel ){
59170     assert( pMem->xDel!=SQLITE_DYNAMIC );
59171     pMem->xDel((void *)(pMem->z));
59172   }
59173
59174   pMem->z = pMem->zMalloc;
59175   if( pMem->z==0 ){
59176     pMem->flags = MEM_Null;
59177   }else{
59178     pMem->flags &= ~(MEM_Ephem|MEM_Static);
59179   }
59180   pMem->xDel = 0;
59181   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
59182 }
59183
59184 /*
59185 ** Make the given Mem object MEM_Dyn.  In other words, make it so
59186 ** that any TEXT or BLOB content is stored in memory obtained from
59187 ** malloc().  In this way, we know that the memory is safe to be
59188 ** overwritten or altered.
59189 **
59190 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
59191 */
59192 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
59193   int f;
59194   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59195   assert( (pMem->flags&MEM_RowSet)==0 );
59196   ExpandBlob(pMem);
59197   f = pMem->flags;
59198   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
59199     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
59200       return SQLITE_NOMEM;
59201     }
59202     pMem->z[pMem->n] = 0;
59203     pMem->z[pMem->n+1] = 0;
59204     pMem->flags |= MEM_Term;
59205 #ifdef SQLITE_DEBUG
59206     pMem->pScopyFrom = 0;
59207 #endif
59208   }
59209
59210   return SQLITE_OK;
59211 }
59212
59213 /*
59214 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
59215 ** blob stored in dynamically allocated space.
59216 */
59217 #ifndef SQLITE_OMIT_INCRBLOB
59218 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
59219   if( pMem->flags & MEM_Zero ){
59220     int nByte;
59221     assert( pMem->flags&MEM_Blob );
59222     assert( (pMem->flags&MEM_RowSet)==0 );
59223     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59224
59225     /* Set nByte to the number of bytes required to store the expanded blob. */
59226     nByte = pMem->n + pMem->u.nZero;
59227     if( nByte<=0 ){
59228       nByte = 1;
59229     }
59230     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
59231       return SQLITE_NOMEM;
59232     }
59233
59234     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
59235     pMem->n += pMem->u.nZero;
59236     pMem->flags &= ~(MEM_Zero|MEM_Term);
59237   }
59238   return SQLITE_OK;
59239 }
59240 #endif
59241
59242
59243 /*
59244 ** Make sure the given Mem is \u0000 terminated.
59245 */
59246 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
59247   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59248   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
59249     return SQLITE_OK;   /* Nothing to do */
59250   }
59251   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
59252     return SQLITE_NOMEM;
59253   }
59254   pMem->z[pMem->n] = 0;
59255   pMem->z[pMem->n+1] = 0;
59256   pMem->flags |= MEM_Term;
59257   return SQLITE_OK;
59258 }
59259
59260 /*
59261 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
59262 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
59263 ** is a no-op.
59264 **
59265 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
59266 **
59267 ** A MEM_Null value will never be passed to this function. This function is
59268 ** used for converting values to text for returning to the user (i.e. via
59269 ** sqlite3_value_text()), or for ensuring that values to be used as btree
59270 ** keys are strings. In the former case a NULL pointer is returned the
59271 ** user and the later is an internal programming error.
59272 */
59273 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
59274   int rc = SQLITE_OK;
59275   int fg = pMem->flags;
59276   const int nByte = 32;
59277
59278   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59279   assert( !(fg&MEM_Zero) );
59280   assert( !(fg&(MEM_Str|MEM_Blob)) );
59281   assert( fg&(MEM_Int|MEM_Real) );
59282   assert( (pMem->flags&MEM_RowSet)==0 );
59283   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59284
59285
59286   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59287     return SQLITE_NOMEM;
59288   }
59289
59290   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
59291   ** string representation of the value. Then, if the required encoding
59292   ** is UTF-16le or UTF-16be do a translation.
59293   **
59294   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
59295   */
59296   if( fg & MEM_Int ){
59297     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
59298   }else{
59299     assert( fg & MEM_Real );
59300     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
59301   }
59302   pMem->n = sqlite3Strlen30(pMem->z);
59303   pMem->enc = SQLITE_UTF8;
59304   pMem->flags |= MEM_Str|MEM_Term;
59305   sqlite3VdbeChangeEncoding(pMem, enc);
59306   return rc;
59307 }
59308
59309 /*
59310 ** Memory cell pMem contains the context of an aggregate function.
59311 ** This routine calls the finalize method for that function.  The
59312 ** result of the aggregate is stored back into pMem.
59313 **
59314 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
59315 ** otherwise.
59316 */
59317 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
59318   int rc = SQLITE_OK;
59319   if( ALWAYS(pFunc && pFunc->xFinalize) ){
59320     sqlite3_context ctx;
59321     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
59322     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59323     memset(&ctx, 0, sizeof(ctx));
59324     ctx.s.flags = MEM_Null;
59325     ctx.s.db = pMem->db;
59326     ctx.pMem = pMem;
59327     ctx.pFunc = pFunc;
59328     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
59329     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
59330     sqlite3DbFree(pMem->db, pMem->zMalloc);
59331     memcpy(pMem, &ctx.s, sizeof(ctx.s));
59332     rc = ctx.isError;
59333   }
59334   return rc;
59335 }
59336
59337 /*
59338 ** If the memory cell contains a string value that must be freed by
59339 ** invoking an external callback, free it now. Calling this function
59340 ** does not free any Mem.zMalloc buffer.
59341 */
59342 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
59343   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
59344   if( p->flags&MEM_Agg ){
59345     sqlite3VdbeMemFinalize(p, p->u.pDef);
59346     assert( (p->flags & MEM_Agg)==0 );
59347     sqlite3VdbeMemRelease(p);
59348   }else if( p->flags&MEM_Dyn && p->xDel ){
59349     assert( (p->flags&MEM_RowSet)==0 );
59350     assert( p->xDel!=SQLITE_DYNAMIC );
59351     p->xDel((void *)p->z);
59352     p->xDel = 0;
59353   }else if( p->flags&MEM_RowSet ){
59354     sqlite3RowSetClear(p->u.pRowSet);
59355   }else if( p->flags&MEM_Frame ){
59356     sqlite3VdbeMemSetNull(p);
59357   }
59358 }
59359
59360 /*
59361 ** Release any memory held by the Mem. This may leave the Mem in an
59362 ** inconsistent state, for example with (Mem.z==0) and
59363 ** (Mem.type==SQLITE_TEXT).
59364 */
59365 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
59366   VdbeMemRelease(p);
59367   sqlite3DbFree(p->db, p->zMalloc);
59368   p->z = 0;
59369   p->zMalloc = 0;
59370   p->xDel = 0;
59371 }
59372
59373 /*
59374 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
59375 ** If the double is too large, return 0x8000000000000000.
59376 **
59377 ** Most systems appear to do this simply by assigning
59378 ** variables and without the extra range tests.  But
59379 ** there are reports that windows throws an expection
59380 ** if the floating point value is out of range. (See ticket #2880.)
59381 ** Because we do not completely understand the problem, we will
59382 ** take the conservative approach and always do range tests
59383 ** before attempting the conversion.
59384 */
59385 static i64 doubleToInt64(double r){
59386 #ifdef SQLITE_OMIT_FLOATING_POINT
59387   /* When floating-point is omitted, double and int64 are the same thing */
59388   return r;
59389 #else
59390   /*
59391   ** Many compilers we encounter do not define constants for the
59392   ** minimum and maximum 64-bit integers, or they define them
59393   ** inconsistently.  And many do not understand the "LL" notation.
59394   ** So we define our own static constants here using nothing
59395   ** larger than a 32-bit integer constant.
59396   */
59397   static const i64 maxInt = LARGEST_INT64;
59398   static const i64 minInt = SMALLEST_INT64;
59399
59400   if( r<(double)minInt ){
59401     return minInt;
59402   }else if( r>(double)maxInt ){
59403     /* minInt is correct here - not maxInt.  It turns out that assigning
59404     ** a very large positive number to an integer results in a very large
59405     ** negative integer.  This makes no sense, but it is what x86 hardware
59406     ** does so for compatibility we will do the same in software. */
59407     return minInt;
59408   }else{
59409     return (i64)r;
59410   }
59411 #endif
59412 }
59413
59414 /*
59415 ** Return some kind of integer value which is the best we can do
59416 ** at representing the value that *pMem describes as an integer.
59417 ** If pMem is an integer, then the value is exact.  If pMem is
59418 ** a floating-point then the value returned is the integer part.
59419 ** If pMem is a string or blob, then we make an attempt to convert
59420 ** it into a integer and return that.  If pMem represents an
59421 ** an SQL-NULL value, return 0.
59422 **
59423 ** If pMem represents a string value, its encoding might be changed.
59424 */
59425 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
59426   int flags;
59427   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59428   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59429   flags = pMem->flags;
59430   if( flags & MEM_Int ){
59431     return pMem->u.i;
59432   }else if( flags & MEM_Real ){
59433     return doubleToInt64(pMem->r);
59434   }else if( flags & (MEM_Str|MEM_Blob) ){
59435     i64 value = 0;
59436     assert( pMem->z || pMem->n==0 );
59437     testcase( pMem->z==0 );
59438     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
59439     return value;
59440   }else{
59441     return 0;
59442   }
59443 }
59444
59445 /*
59446 ** Return the best representation of pMem that we can get into a
59447 ** double.  If pMem is already a double or an integer, return its
59448 ** value.  If it is a string or blob, try to convert it to a double.
59449 ** If it is a NULL, return 0.0.
59450 */
59451 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
59452   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59453   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59454   if( pMem->flags & MEM_Real ){
59455     return pMem->r;
59456   }else if( pMem->flags & MEM_Int ){
59457     return (double)pMem->u.i;
59458   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
59459     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59460     double val = (double)0;
59461     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
59462     return val;
59463   }else{
59464     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59465     return (double)0;
59466   }
59467 }
59468
59469 /*
59470 ** The MEM structure is already a MEM_Real.  Try to also make it a
59471 ** MEM_Int if we can.
59472 */
59473 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
59474   assert( pMem->flags & MEM_Real );
59475   assert( (pMem->flags & MEM_RowSet)==0 );
59476   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59477   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59478
59479   pMem->u.i = doubleToInt64(pMem->r);
59480
59481   /* Only mark the value as an integer if
59482   **
59483   **    (1) the round-trip conversion real->int->real is a no-op, and
59484   **    (2) The integer is neither the largest nor the smallest
59485   **        possible integer (ticket #3922)
59486   **
59487   ** The second and third terms in the following conditional enforces
59488   ** the second condition under the assumption that addition overflow causes
59489   ** values to wrap around.  On x86 hardware, the third term is always
59490   ** true and could be omitted.  But we leave it in because other
59491   ** architectures might behave differently.
59492   */
59493   if( pMem->r==(double)pMem->u.i
59494    && pMem->u.i>SMALLEST_INT64
59495 #if defined(__i486__) || defined(__x86_64__)
59496    && ALWAYS(pMem->u.i<LARGEST_INT64)
59497 #else
59498    && pMem->u.i<LARGEST_INT64
59499 #endif
59500   ){
59501     pMem->flags |= MEM_Int;
59502   }
59503 }
59504
59505 /*
59506 ** Convert pMem to type integer.  Invalidate any prior representations.
59507 */
59508 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
59509   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59510   assert( (pMem->flags & MEM_RowSet)==0 );
59511   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59512
59513   pMem->u.i = sqlite3VdbeIntValue(pMem);
59514   MemSetTypeFlag(pMem, MEM_Int);
59515   return SQLITE_OK;
59516 }
59517
59518 /*
59519 ** Convert pMem so that it is of type MEM_Real.
59520 ** Invalidate any prior representations.
59521 */
59522 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
59523   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59524   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59525
59526   pMem->r = sqlite3VdbeRealValue(pMem);
59527   MemSetTypeFlag(pMem, MEM_Real);
59528   return SQLITE_OK;
59529 }
59530
59531 /*
59532 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
59533 ** Invalidate any prior representations.
59534 **
59535 ** Every effort is made to force the conversion, even if the input
59536 ** is a string that does not look completely like a number.  Convert
59537 ** as much of the string as we can and ignore the rest.
59538 */
59539 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
59540   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
59541     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
59542     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59543     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
59544       MemSetTypeFlag(pMem, MEM_Int);
59545     }else{
59546       pMem->r = sqlite3VdbeRealValue(pMem);
59547       MemSetTypeFlag(pMem, MEM_Real);
59548       sqlite3VdbeIntegerAffinity(pMem);
59549     }
59550   }
59551   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
59552   pMem->flags &= ~(MEM_Str|MEM_Blob);
59553   return SQLITE_OK;
59554 }
59555
59556 /*
59557 ** Delete any previous value and set the value stored in *pMem to NULL.
59558 */
59559 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
59560   if( pMem->flags & MEM_Frame ){
59561     VdbeFrame *pFrame = pMem->u.pFrame;
59562     pFrame->pParent = pFrame->v->pDelFrame;
59563     pFrame->v->pDelFrame = pFrame;
59564   }
59565   if( pMem->flags & MEM_RowSet ){
59566     sqlite3RowSetClear(pMem->u.pRowSet);
59567   }
59568   MemSetTypeFlag(pMem, MEM_Null);
59569   pMem->type = SQLITE_NULL;
59570 }
59571
59572 /*
59573 ** Delete any previous value and set the value to be a BLOB of length
59574 ** n containing all zeros.
59575 */
59576 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
59577   sqlite3VdbeMemRelease(pMem);
59578   pMem->flags = MEM_Blob|MEM_Zero;
59579   pMem->type = SQLITE_BLOB;
59580   pMem->n = 0;
59581   if( n<0 ) n = 0;
59582   pMem->u.nZero = n;
59583   pMem->enc = SQLITE_UTF8;
59584
59585 #ifdef SQLITE_OMIT_INCRBLOB
59586   sqlite3VdbeMemGrow(pMem, n, 0);
59587   if( pMem->z ){
59588     pMem->n = n;
59589     memset(pMem->z, 0, n);
59590   }
59591 #endif
59592 }
59593
59594 /*
59595 ** Delete any previous value and set the value stored in *pMem to val,
59596 ** manifest type INTEGER.
59597 */
59598 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
59599   sqlite3VdbeMemRelease(pMem);
59600   pMem->u.i = val;
59601   pMem->flags = MEM_Int;
59602   pMem->type = SQLITE_INTEGER;
59603 }
59604
59605 #ifndef SQLITE_OMIT_FLOATING_POINT
59606 /*
59607 ** Delete any previous value and set the value stored in *pMem to val,
59608 ** manifest type REAL.
59609 */
59610 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
59611   if( sqlite3IsNaN(val) ){
59612     sqlite3VdbeMemSetNull(pMem);
59613   }else{
59614     sqlite3VdbeMemRelease(pMem);
59615     pMem->r = val;
59616     pMem->flags = MEM_Real;
59617     pMem->type = SQLITE_FLOAT;
59618   }
59619 }
59620 #endif
59621
59622 /*
59623 ** Delete any previous value and set the value of pMem to be an
59624 ** empty boolean index.
59625 */
59626 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
59627   sqlite3 *db = pMem->db;
59628   assert( db!=0 );
59629   assert( (pMem->flags & MEM_RowSet)==0 );
59630   sqlite3VdbeMemRelease(pMem);
59631   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
59632   if( db->mallocFailed ){
59633     pMem->flags = MEM_Null;
59634   }else{
59635     assert( pMem->zMalloc );
59636     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
59637                                        sqlite3DbMallocSize(db, pMem->zMalloc));
59638     assert( pMem->u.pRowSet!=0 );
59639     pMem->flags = MEM_RowSet;
59640   }
59641 }
59642
59643 /*
59644 ** Return true if the Mem object contains a TEXT or BLOB that is
59645 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
59646 */
59647 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
59648   assert( p->db!=0 );
59649   if( p->flags & (MEM_Str|MEM_Blob) ){
59650     int n = p->n;
59651     if( p->flags & MEM_Zero ){
59652       n += p->u.nZero;
59653     }
59654     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
59655   }
59656   return 0;
59657 }
59658
59659 #ifdef SQLITE_DEBUG
59660 /*
59661 ** This routine prepares a memory cell for modication by breaking
59662 ** its link to a shallow copy and by marking any current shallow
59663 ** copies of this cell as invalid.
59664 **
59665 ** This is used for testing and debugging only - to make sure shallow
59666 ** copies are not misused.
59667 */
59668 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
59669   int i;
59670   Mem *pX;
59671   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
59672     if( pX->pScopyFrom==pMem ){
59673       pX->flags |= MEM_Invalid;
59674       pX->pScopyFrom = 0;
59675     }
59676   }
59677   pMem->pScopyFrom = 0;
59678 }
59679 #endif /* SQLITE_DEBUG */
59680
59681 /*
59682 ** Size of struct Mem not including the Mem.zMalloc member.
59683 */
59684 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
59685
59686 /*
59687 ** Make an shallow copy of pFrom into pTo.  Prior contents of
59688 ** pTo are freed.  The pFrom->z field is not duplicated.  If
59689 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
59690 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
59691 */
59692 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
59693   assert( (pFrom->flags & MEM_RowSet)==0 );
59694   VdbeMemRelease(pTo);
59695   memcpy(pTo, pFrom, MEMCELLSIZE);
59696   pTo->xDel = 0;
59697   if( (pFrom->flags&MEM_Static)==0 ){
59698     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
59699     assert( srcType==MEM_Ephem || srcType==MEM_Static );
59700     pTo->flags |= srcType;
59701   }
59702 }
59703
59704 /*
59705 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
59706 ** freed before the copy is made.
59707 */
59708 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59709   int rc = SQLITE_OK;
59710
59711   assert( (pFrom->flags & MEM_RowSet)==0 );
59712   VdbeMemRelease(pTo);
59713   memcpy(pTo, pFrom, MEMCELLSIZE);
59714   pTo->flags &= ~MEM_Dyn;
59715
59716   if( pTo->flags&(MEM_Str|MEM_Blob) ){
59717     if( 0==(pFrom->flags&MEM_Static) ){
59718       pTo->flags |= MEM_Ephem;
59719       rc = sqlite3VdbeMemMakeWriteable(pTo);
59720     }
59721   }
59722
59723   return rc;
59724 }
59725
59726 /*
59727 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59728 ** freed. If pFrom contains ephemeral data, a copy is made.
59729 **
59730 ** pFrom contains an SQL NULL when this routine returns.
59731 */
59732 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
59733   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
59734   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
59735   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59736
59737   sqlite3VdbeMemRelease(pTo);
59738   memcpy(pTo, pFrom, sizeof(Mem));
59739   pFrom->flags = MEM_Null;
59740   pFrom->xDel = 0;
59741   pFrom->zMalloc = 0;
59742 }
59743
59744 /*
59745 ** Change the value of a Mem to be a string or a BLOB.
59746 **
59747 ** The memory management strategy depends on the value of the xDel
59748 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
59749 ** string is copied into a (possibly existing) buffer managed by the
59750 ** Mem structure. Otherwise, any existing buffer is freed and the
59751 ** pointer copied.
59752 **
59753 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
59754 ** size limit) then no memory allocation occurs.  If the string can be
59755 ** stored without allocating memory, then it is.  If a memory allocation
59756 ** is required to store the string, then value of pMem is unchanged.  In
59757 ** either case, SQLITE_TOOBIG is returned.
59758 */
59759 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
59760   Mem *pMem,          /* Memory cell to set to string value */
59761   const char *z,      /* String pointer */
59762   int n,              /* Bytes in string, or negative */
59763   u8 enc,             /* Encoding of z.  0 for BLOBs */
59764   void (*xDel)(void*) /* Destructor function */
59765 ){
59766   int nByte = n;      /* New value for pMem->n */
59767   int iLimit;         /* Maximum allowed string or blob size */
59768   u16 flags = 0;      /* New value for pMem->flags */
59769
59770   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59771   assert( (pMem->flags & MEM_RowSet)==0 );
59772
59773   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59774   if( !z ){
59775     sqlite3VdbeMemSetNull(pMem);
59776     return SQLITE_OK;
59777   }
59778
59779   if( pMem->db ){
59780     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
59781   }else{
59782     iLimit = SQLITE_MAX_LENGTH;
59783   }
59784   flags = (enc==0?MEM_Blob:MEM_Str);
59785   if( nByte<0 ){
59786     assert( enc!=0 );
59787     if( enc==SQLITE_UTF8 ){
59788       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59789     }else{
59790       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59791     }
59792     flags |= MEM_Term;
59793   }
59794
59795   /* The following block sets the new values of Mem.z and Mem.xDel. It
59796   ** also sets a flag in local variable "flags" to indicate the memory
59797   ** management (one of MEM_Dyn or MEM_Static).
59798   */
59799   if( xDel==SQLITE_TRANSIENT ){
59800     int nAlloc = nByte;
59801     if( flags&MEM_Term ){
59802       nAlloc += (enc==SQLITE_UTF8?1:2);
59803     }
59804     if( nByte>iLimit ){
59805       return SQLITE_TOOBIG;
59806     }
59807     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
59808       return SQLITE_NOMEM;
59809     }
59810     memcpy(pMem->z, z, nAlloc);
59811   }else if( xDel==SQLITE_DYNAMIC ){
59812     sqlite3VdbeMemRelease(pMem);
59813     pMem->zMalloc = pMem->z = (char *)z;
59814     pMem->xDel = 0;
59815   }else{
59816     sqlite3VdbeMemRelease(pMem);
59817     pMem->z = (char *)z;
59818     pMem->xDel = xDel;
59819     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
59820   }
59821
59822   pMem->n = nByte;
59823   pMem->flags = flags;
59824   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
59825   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
59826
59827 #ifndef SQLITE_OMIT_UTF16
59828   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
59829     return SQLITE_NOMEM;
59830   }
59831 #endif
59832
59833   if( nByte>iLimit ){
59834     return SQLITE_TOOBIG;
59835   }
59836
59837   return SQLITE_OK;
59838 }
59839
59840 /*
59841 ** Compare the values contained by the two memory cells, returning
59842 ** negative, zero or positive if pMem1 is less than, equal to, or greater
59843 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59844 ** and reals) sorted numerically, followed by text ordered by the collating
59845 ** sequence pColl and finally blob's ordered by memcmp().
59846 **
59847 ** Two NULL values are considered equal by this function.
59848 */
59849 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59850   int rc;
59851   int f1, f2;
59852   int combined_flags;
59853
59854   f1 = pMem1->flags;
59855   f2 = pMem2->flags;
59856   combined_flags = f1|f2;
59857   assert( (combined_flags & MEM_RowSet)==0 );
59858
59859   /* If one value is NULL, it is less than the other. If both values
59860   ** are NULL, return 0.
59861   */
59862   if( combined_flags&MEM_Null ){
59863     return (f2&MEM_Null) - (f1&MEM_Null);
59864   }
59865
59866   /* If one value is a number and the other is not, the number is less.
59867   ** If both are numbers, compare as reals if one is a real, or as integers
59868   ** if both values are integers.
59869   */
59870   if( combined_flags&(MEM_Int|MEM_Real) ){
59871     if( !(f1&(MEM_Int|MEM_Real)) ){
59872       return 1;
59873     }
59874     if( !(f2&(MEM_Int|MEM_Real)) ){
59875       return -1;
59876     }
59877     if( (f1 & f2 & MEM_Int)==0 ){
59878       double r1, r2;
59879       if( (f1&MEM_Real)==0 ){
59880         r1 = (double)pMem1->u.i;
59881       }else{
59882         r1 = pMem1->r;
59883       }
59884       if( (f2&MEM_Real)==0 ){
59885         r2 = (double)pMem2->u.i;
59886       }else{
59887         r2 = pMem2->r;
59888       }
59889       if( r1<r2 ) return -1;
59890       if( r1>r2 ) return 1;
59891       return 0;
59892     }else{
59893       assert( f1&MEM_Int );
59894       assert( f2&MEM_Int );
59895       if( pMem1->u.i < pMem2->u.i ) return -1;
59896       if( pMem1->u.i > pMem2->u.i ) return 1;
59897       return 0;
59898     }
59899   }
59900
59901   /* If one value is a string and the other is a blob, the string is less.
59902   ** If both are strings, compare using the collating functions.
59903   */
59904   if( combined_flags&MEM_Str ){
59905     if( (f1 & MEM_Str)==0 ){
59906       return 1;
59907     }
59908     if( (f2 & MEM_Str)==0 ){
59909       return -1;
59910     }
59911
59912     assert( pMem1->enc==pMem2->enc );
59913     assert( pMem1->enc==SQLITE_UTF8 ||
59914             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
59915
59916     /* The collation sequence must be defined at this point, even if
59917     ** the user deletes the collation sequence after the vdbe program is
59918     ** compiled (this was not always the case).
59919     */
59920     assert( !pColl || pColl->xCmp );
59921
59922     if( pColl ){
59923       if( pMem1->enc==pColl->enc ){
59924         /* The strings are already in the correct encoding.  Call the
59925         ** comparison function directly */
59926         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59927       }else{
59928         const void *v1, *v2;
59929         int n1, n2;
59930         Mem c1;
59931         Mem c2;
59932         memset(&c1, 0, sizeof(c1));
59933         memset(&c2, 0, sizeof(c2));
59934         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59935         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59936         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
59937         n1 = v1==0 ? 0 : c1.n;
59938         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
59939         n2 = v2==0 ? 0 : c2.n;
59940         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59941         sqlite3VdbeMemRelease(&c1);
59942         sqlite3VdbeMemRelease(&c2);
59943         return rc;
59944       }
59945     }
59946     /* If a NULL pointer was passed as the collate function, fall through
59947     ** to the blob case and use memcmp().  */
59948   }
59949
59950   /* Both values must be blobs.  Compare using memcmp().  */
59951   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59952   if( rc==0 ){
59953     rc = pMem1->n - pMem2->n;
59954   }
59955   return rc;
59956 }
59957
59958 /*
59959 ** Move data out of a btree key or data field and into a Mem structure.
59960 ** The data or key is taken from the entry that pCur is currently pointing
59961 ** to.  offset and amt determine what portion of the data or key to retrieve.
59962 ** key is true to get the key or false to get data.  The result is written
59963 ** into the pMem element.
59964 **
59965 ** The pMem structure is assumed to be uninitialized.  Any prior content
59966 ** is overwritten without being freed.
59967 **
59968 ** If this routine fails for any reason (malloc returns NULL or unable
59969 ** to read from the disk) then the pMem is left in an inconsistent state.
59970 */
59971 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
59972   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
59973   int offset,       /* Offset from the start of data to return bytes from. */
59974   int amt,          /* Number of bytes to return. */
59975   int key,          /* If true, retrieve from the btree key, not data. */
59976   Mem *pMem         /* OUT: Return data in this Mem structure. */
59977 ){
59978   char *zData;        /* Data from the btree layer */
59979   int available = 0;  /* Number of bytes available on the local btree page */
59980   int rc = SQLITE_OK; /* Return code */
59981
59982   assert( sqlite3BtreeCursorIsValid(pCur) );
59983
59984   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
59985   ** that both the BtShared and database handle mutexes are held. */
59986   assert( (pMem->flags & MEM_RowSet)==0 );
59987   if( key ){
59988     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
59989   }else{
59990     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
59991   }
59992   assert( zData!=0 );
59993
59994   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59995     sqlite3VdbeMemRelease(pMem);
59996     pMem->z = &zData[offset];
59997     pMem->flags = MEM_Blob|MEM_Ephem;
59998   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
59999     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
60000     pMem->enc = 0;
60001     pMem->type = SQLITE_BLOB;
60002     if( key ){
60003       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
60004     }else{
60005       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
60006     }
60007     pMem->z[amt] = 0;
60008     pMem->z[amt+1] = 0;
60009     if( rc!=SQLITE_OK ){
60010       sqlite3VdbeMemRelease(pMem);
60011     }
60012   }
60013   pMem->n = amt;
60014
60015   return rc;
60016 }
60017
60018 /* This function is only available internally, it is not part of the
60019 ** external API. It works in a similar way to sqlite3_value_text(),
60020 ** except the data returned is in the encoding specified by the second
60021 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
60022 ** SQLITE_UTF8.
60023 **
60024 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
60025 ** If that is the case, then the result must be aligned on an even byte
60026 ** boundary.
60027 */
60028 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
60029   if( !pVal ) return 0;
60030
60031   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
60032   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
60033   assert( (pVal->flags & MEM_RowSet)==0 );
60034
60035   if( pVal->flags&MEM_Null ){
60036     return 0;
60037   }
60038   assert( (MEM_Blob>>3) == MEM_Str );
60039   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
60040   ExpandBlob(pVal);
60041   if( pVal->flags&MEM_Str ){
60042     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
60043     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
60044       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
60045       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
60046         return 0;
60047       }
60048     }
60049     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
60050   }else{
60051     assert( (pVal->flags&MEM_Blob)==0 );
60052     sqlite3VdbeMemStringify(pVal, enc);
60053     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
60054   }
60055   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
60056               || pVal->db->mallocFailed );
60057   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
60058     return pVal->z;
60059   }else{
60060     return 0;
60061   }
60062 }
60063
60064 /*
60065 ** Create a new sqlite3_value object.
60066 */
60067 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
60068   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
60069   if( p ){
60070     p->flags = MEM_Null;
60071     p->type = SQLITE_NULL;
60072     p->db = db;
60073   }
60074   return p;
60075 }
60076
60077 /*
60078 ** Create a new sqlite3_value object, containing the value of pExpr.
60079 **
60080 ** This only works for very simple expressions that consist of one constant
60081 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
60082 ** be converted directly into a value, then the value is allocated and
60083 ** a pointer written to *ppVal. The caller is responsible for deallocating
60084 ** the value by passing it to sqlite3ValueFree() later on. If the expression
60085 ** cannot be converted to a value, then *ppVal is set to NULL.
60086 */
60087 SQLITE_PRIVATE int sqlite3ValueFromExpr(
60088   sqlite3 *db,              /* The database connection */
60089   Expr *pExpr,              /* The expression to evaluate */
60090   u8 enc,                   /* Encoding to use */
60091   u8 affinity,              /* Affinity to use */
60092   sqlite3_value **ppVal     /* Write the new value here */
60093 ){
60094   int op;
60095   char *zVal = 0;
60096   sqlite3_value *pVal = 0;
60097   int negInt = 1;
60098   const char *zNeg = "";
60099
60100   if( !pExpr ){
60101     *ppVal = 0;
60102     return SQLITE_OK;
60103   }
60104   op = pExpr->op;
60105
60106   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
60107   ** The ifdef here is to enable us to achieve 100% branch test coverage even
60108   ** when SQLITE_ENABLE_STAT3 is omitted.
60109   */
60110 #ifdef SQLITE_ENABLE_STAT3
60111   if( op==TK_REGISTER ) op = pExpr->op2;
60112 #else
60113   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
60114 #endif
60115
60116   /* Handle negative integers in a single step.  This is needed in the
60117   ** case when the value is -9223372036854775808.
60118   */
60119   if( op==TK_UMINUS
60120    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
60121     pExpr = pExpr->pLeft;
60122     op = pExpr->op;
60123     negInt = -1;
60124     zNeg = "-";
60125   }
60126
60127   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
60128     pVal = sqlite3ValueNew(db);
60129     if( pVal==0 ) goto no_mem;
60130     if( ExprHasProperty(pExpr, EP_IntValue) ){
60131       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
60132     }else{
60133       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
60134       if( zVal==0 ) goto no_mem;
60135       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
60136       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
60137     }
60138     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
60139       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
60140     }else{
60141       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
60142     }
60143     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
60144     if( enc!=SQLITE_UTF8 ){
60145       sqlite3VdbeChangeEncoding(pVal, enc);
60146     }
60147   }else if( op==TK_UMINUS ) {
60148     /* This branch happens for multiple negative signs.  Ex: -(-5) */
60149     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
60150       sqlite3VdbeMemNumerify(pVal);
60151       if( pVal->u.i==SMALLEST_INT64 ){
60152         pVal->flags &= MEM_Int;
60153         pVal->flags |= MEM_Real;
60154         pVal->r = (double)LARGEST_INT64;
60155       }else{
60156         pVal->u.i = -pVal->u.i;
60157       }
60158       pVal->r = -pVal->r;
60159       sqlite3ValueApplyAffinity(pVal, affinity, enc);
60160     }
60161   }else if( op==TK_NULL ){
60162     pVal = sqlite3ValueNew(db);
60163     if( pVal==0 ) goto no_mem;
60164   }
60165 #ifndef SQLITE_OMIT_BLOB_LITERAL
60166   else if( op==TK_BLOB ){
60167     int nVal;
60168     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
60169     assert( pExpr->u.zToken[1]=='\'' );
60170     pVal = sqlite3ValueNew(db);
60171     if( !pVal ) goto no_mem;
60172     zVal = &pExpr->u.zToken[2];
60173     nVal = sqlite3Strlen30(zVal)-1;
60174     assert( zVal[nVal]=='\'' );
60175     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
60176                          0, SQLITE_DYNAMIC);
60177   }
60178 #endif
60179
60180   if( pVal ){
60181     sqlite3VdbeMemStoreType(pVal);
60182   }
60183   *ppVal = pVal;
60184   return SQLITE_OK;
60185
60186 no_mem:
60187   db->mallocFailed = 1;
60188   sqlite3DbFree(db, zVal);
60189   sqlite3ValueFree(pVal);
60190   *ppVal = 0;
60191   return SQLITE_NOMEM;
60192 }
60193
60194 /*
60195 ** Change the string value of an sqlite3_value object
60196 */
60197 SQLITE_PRIVATE void sqlite3ValueSetStr(
60198   sqlite3_value *v,     /* Value to be set */
60199   int n,                /* Length of string z */
60200   const void *z,        /* Text of the new string */
60201   u8 enc,               /* Encoding to use */
60202   void (*xDel)(void*)   /* Destructor for the string */
60203 ){
60204   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
60205 }
60206
60207 /*
60208 ** Free an sqlite3_value object
60209 */
60210 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
60211   if( !v ) return;
60212   sqlite3VdbeMemRelease((Mem *)v);
60213   sqlite3DbFree(((Mem*)v)->db, v);
60214 }
60215
60216 /*
60217 ** Return the number of bytes in the sqlite3_value object assuming
60218 ** that it uses the encoding "enc"
60219 */
60220 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
60221   Mem *p = (Mem*)pVal;
60222   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
60223     if( p->flags & MEM_Zero ){
60224       return p->n + p->u.nZero;
60225     }else{
60226       return p->n;
60227     }
60228   }
60229   return 0;
60230 }
60231
60232 /************** End of vdbemem.c *********************************************/
60233 /************** Begin file vdbeaux.c *****************************************/
60234 /*
60235 ** 2003 September 6
60236 **
60237 ** The author disclaims copyright to this source code.  In place of
60238 ** a legal notice, here is a blessing:
60239 **
60240 **    May you do good and not evil.
60241 **    May you find forgiveness for yourself and forgive others.
60242 **    May you share freely, never taking more than you give.
60243 **
60244 *************************************************************************
60245 ** This file contains code used for creating, destroying, and populating
60246 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
60247 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
60248 ** But that file was getting too big so this subroutines were split out.
60249 */
60250
60251
60252
60253 /*
60254 ** When debugging the code generator in a symbolic debugger, one can
60255 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
60256 ** as they are added to the instruction stream.
60257 */
60258 #ifdef SQLITE_DEBUG
60259 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
60260 #endif
60261
60262
60263 /*
60264 ** Create a new virtual database engine.
60265 */
60266 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
60267   Vdbe *p;
60268   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
60269   if( p==0 ) return 0;
60270   p->db = db;
60271   if( db->pVdbe ){
60272     db->pVdbe->pPrev = p;
60273   }
60274   p->pNext = db->pVdbe;
60275   p->pPrev = 0;
60276   db->pVdbe = p;
60277   p->magic = VDBE_MAGIC_INIT;
60278   return p;
60279 }
60280
60281 /*
60282 ** Remember the SQL string for a prepared statement.
60283 */
60284 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
60285   assert( isPrepareV2==1 || isPrepareV2==0 );
60286   if( p==0 ) return;
60287 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
60288   if( !isPrepareV2 ) return;
60289 #endif
60290   assert( p->zSql==0 );
60291   p->zSql = sqlite3DbStrNDup(p->db, z, n);
60292   p->isPrepareV2 = (u8)isPrepareV2;
60293 }
60294
60295 /*
60296 ** Return the SQL associated with a prepared statement
60297 */
60298 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
60299   Vdbe *p = (Vdbe *)pStmt;
60300   return (p && p->isPrepareV2) ? p->zSql : 0;
60301 }
60302
60303 /*
60304 ** Swap all content between two VDBE structures.
60305 */
60306 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
60307   Vdbe tmp, *pTmp;
60308   char *zTmp;
60309   tmp = *pA;
60310   *pA = *pB;
60311   *pB = tmp;
60312   pTmp = pA->pNext;
60313   pA->pNext = pB->pNext;
60314   pB->pNext = pTmp;
60315   pTmp = pA->pPrev;
60316   pA->pPrev = pB->pPrev;
60317   pB->pPrev = pTmp;
60318   zTmp = pA->zSql;
60319   pA->zSql = pB->zSql;
60320   pB->zSql = zTmp;
60321   pB->isPrepareV2 = pA->isPrepareV2;
60322 }
60323
60324 #ifdef SQLITE_DEBUG
60325 /*
60326 ** Turn tracing on or off
60327 */
60328 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
60329   p->trace = trace;
60330 }
60331 #endif
60332
60333 /*
60334 ** Resize the Vdbe.aOp array so that it is at least one op larger than
60335 ** it was.
60336 **
60337 ** If an out-of-memory error occurs while resizing the array, return
60338 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
60339 ** unchanged (this is so that any opcodes already allocated can be
60340 ** correctly deallocated along with the rest of the Vdbe).
60341 */
60342 static int growOpArray(Vdbe *p){
60343   VdbeOp *pNew;
60344   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
60345   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
60346   if( pNew ){
60347     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
60348     p->aOp = pNew;
60349   }
60350   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
60351 }
60352
60353 /*
60354 ** Add a new instruction to the list of instructions current in the
60355 ** VDBE.  Return the address of the new instruction.
60356 **
60357 ** Parameters:
60358 **
60359 **    p               Pointer to the VDBE
60360 **
60361 **    op              The opcode for this instruction
60362 **
60363 **    p1, p2, p3      Operands
60364 **
60365 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
60366 ** the sqlite3VdbeChangeP4() function to change the value of the P4
60367 ** operand.
60368 */
60369 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
60370   int i;
60371   VdbeOp *pOp;
60372
60373   i = p->nOp;
60374   assert( p->magic==VDBE_MAGIC_INIT );
60375   assert( op>0 && op<0xff );
60376   if( p->nOpAlloc<=i ){
60377     if( growOpArray(p) ){
60378       return 1;
60379     }
60380   }
60381   p->nOp++;
60382   pOp = &p->aOp[i];
60383   pOp->opcode = (u8)op;
60384   pOp->p5 = 0;
60385   pOp->p1 = p1;
60386   pOp->p2 = p2;
60387   pOp->p3 = p3;
60388   pOp->p4.p = 0;
60389   pOp->p4type = P4_NOTUSED;
60390 #ifdef SQLITE_DEBUG
60391   pOp->zComment = 0;
60392   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
60393 #endif
60394 #ifdef VDBE_PROFILE
60395   pOp->cycles = 0;
60396   pOp->cnt = 0;
60397 #endif
60398   return i;
60399 }
60400 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
60401   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
60402 }
60403 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
60404   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
60405 }
60406 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
60407   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
60408 }
60409
60410
60411 /*
60412 ** Add an opcode that includes the p4 value as a pointer.
60413 */
60414 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
60415   Vdbe *p,            /* Add the opcode to this VM */
60416   int op,             /* The new opcode */
60417   int p1,             /* The P1 operand */
60418   int p2,             /* The P2 operand */
60419   int p3,             /* The P3 operand */
60420   const char *zP4,    /* The P4 operand */
60421   int p4type          /* P4 operand type */
60422 ){
60423   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60424   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
60425   return addr;
60426 }
60427
60428 /*
60429 ** Add an OP_ParseSchema opcode.  This routine is broken out from
60430 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
60431 ** as having been used.
60432 **
60433 ** The zWhere string must have been obtained from sqlite3_malloc().
60434 ** This routine will take ownership of the allocated memory.
60435 */
60436 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
60437   int j;
60438   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
60439   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
60440   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
60441 }
60442
60443 /*
60444 ** Add an opcode that includes the p4 value as an integer.
60445 */
60446 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
60447   Vdbe *p,            /* Add the opcode to this VM */
60448   int op,             /* The new opcode */
60449   int p1,             /* The P1 operand */
60450   int p2,             /* The P2 operand */
60451   int p3,             /* The P3 operand */
60452   int p4              /* The P4 operand as an integer */
60453 ){
60454   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60455   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
60456   return addr;
60457 }
60458
60459 /*
60460 ** Create a new symbolic label for an instruction that has yet to be
60461 ** coded.  The symbolic label is really just a negative number.  The
60462 ** label can be used as the P2 value of an operation.  Later, when
60463 ** the label is resolved to a specific address, the VDBE will scan
60464 ** through its operation list and change all values of P2 which match
60465 ** the label into the resolved address.
60466 **
60467 ** The VDBE knows that a P2 value is a label because labels are
60468 ** always negative and P2 values are suppose to be non-negative.
60469 ** Hence, a negative P2 value is a label that has yet to be resolved.
60470 **
60471 ** Zero is returned if a malloc() fails.
60472 */
60473 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
60474   int i = p->nLabel++;
60475   assert( p->magic==VDBE_MAGIC_INIT );
60476   if( (i & (i-1))==0 ){
60477     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
60478                                        (i*2+1)*sizeof(p->aLabel[0]));
60479   }
60480   if( p->aLabel ){
60481     p->aLabel[i] = -1;
60482   }
60483   return -1-i;
60484 }
60485
60486 /*
60487 ** Resolve label "x" to be the address of the next instruction to
60488 ** be inserted.  The parameter "x" must have been obtained from
60489 ** a prior call to sqlite3VdbeMakeLabel().
60490 */
60491 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
60492   int j = -1-x;
60493   assert( p->magic==VDBE_MAGIC_INIT );
60494   assert( j>=0 && j<p->nLabel );
60495   if( p->aLabel ){
60496     p->aLabel[j] = p->nOp;
60497   }
60498 }
60499
60500 /*
60501 ** Mark the VDBE as one that can only be run one time.
60502 */
60503 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
60504   p->runOnlyOnce = 1;
60505 }
60506
60507 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
60508
60509 /*
60510 ** The following type and function are used to iterate through all opcodes
60511 ** in a Vdbe main program and each of the sub-programs (triggers) it may
60512 ** invoke directly or indirectly. It should be used as follows:
60513 **
60514 **   Op *pOp;
60515 **   VdbeOpIter sIter;
60516 **
60517 **   memset(&sIter, 0, sizeof(sIter));
60518 **   sIter.v = v;                            // v is of type Vdbe*
60519 **   while( (pOp = opIterNext(&sIter)) ){
60520 **     // Do something with pOp
60521 **   }
60522 **   sqlite3DbFree(v->db, sIter.apSub);
60523 **
60524 */
60525 typedef struct VdbeOpIter VdbeOpIter;
60526 struct VdbeOpIter {
60527   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
60528   SubProgram **apSub;        /* Array of subprograms */
60529   int nSub;                  /* Number of entries in apSub */
60530   int iAddr;                 /* Address of next instruction to return */
60531   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
60532 };
60533 static Op *opIterNext(VdbeOpIter *p){
60534   Vdbe *v = p->v;
60535   Op *pRet = 0;
60536   Op *aOp;
60537   int nOp;
60538
60539   if( p->iSub<=p->nSub ){
60540
60541     if( p->iSub==0 ){
60542       aOp = v->aOp;
60543       nOp = v->nOp;
60544     }else{
60545       aOp = p->apSub[p->iSub-1]->aOp;
60546       nOp = p->apSub[p->iSub-1]->nOp;
60547     }
60548     assert( p->iAddr<nOp );
60549
60550     pRet = &aOp[p->iAddr];
60551     p->iAddr++;
60552     if( p->iAddr==nOp ){
60553       p->iSub++;
60554       p->iAddr = 0;
60555     }
60556
60557     if( pRet->p4type==P4_SUBPROGRAM ){
60558       int nByte = (p->nSub+1)*sizeof(SubProgram*);
60559       int j;
60560       for(j=0; j<p->nSub; j++){
60561         if( p->apSub[j]==pRet->p4.pProgram ) break;
60562       }
60563       if( j==p->nSub ){
60564         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
60565         if( !p->apSub ){
60566           pRet = 0;
60567         }else{
60568           p->apSub[p->nSub++] = pRet->p4.pProgram;
60569         }
60570       }
60571     }
60572   }
60573
60574   return pRet;
60575 }
60576
60577 /*
60578 ** Check if the program stored in the VM associated with pParse may
60579 ** throw an ABORT exception (causing the statement, but not entire transaction
60580 ** to be rolled back). This condition is true if the main program or any
60581 ** sub-programs contains any of the following:
60582 **
60583 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60584 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60585 **   *  OP_Destroy
60586 **   *  OP_VUpdate
60587 **   *  OP_VRename
60588 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
60589 **
60590 ** Then check that the value of Parse.mayAbort is true if an
60591 ** ABORT may be thrown, or false otherwise. Return true if it does
60592 ** match, or false otherwise. This function is intended to be used as
60593 ** part of an assert statement in the compiler. Similar to:
60594 **
60595 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
60596 */
60597 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
60598   int hasAbort = 0;
60599   Op *pOp;
60600   VdbeOpIter sIter;
60601   memset(&sIter, 0, sizeof(sIter));
60602   sIter.v = v;
60603
60604   while( (pOp = opIterNext(&sIter))!=0 ){
60605     int opcode = pOp->opcode;
60606     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
60607 #ifndef SQLITE_OMIT_FOREIGN_KEY
60608      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
60609 #endif
60610      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
60611       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
60612     ){
60613       hasAbort = 1;
60614       break;
60615     }
60616   }
60617   sqlite3DbFree(v->db, sIter.apSub);
60618
60619   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
60620   ** If malloc failed, then the while() loop above may not have iterated
60621   ** through all opcodes and hasAbort may be set incorrectly. Return
60622   ** true for this case to prevent the assert() in the callers frame
60623   ** from failing.  */
60624   return ( v->db->mallocFailed || hasAbort==mayAbort );
60625 }
60626 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
60627
60628 /*
60629 ** Loop through the program looking for P2 values that are negative
60630 ** on jump instructions.  Each such value is a label.  Resolve the
60631 ** label by setting the P2 value to its correct non-zero value.
60632 **
60633 ** This routine is called once after all opcodes have been inserted.
60634 **
60635 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
60636 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
60637 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
60638 **
60639 ** The Op.opflags field is set on all opcodes.
60640 */
60641 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
60642   int i;
60643   int nMaxArgs = *pMaxFuncArgs;
60644   Op *pOp;
60645   int *aLabel = p->aLabel;
60646   p->readOnly = 1;
60647   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
60648     u8 opcode = pOp->opcode;
60649
60650     pOp->opflags = sqlite3OpcodeProperty[opcode];
60651     if( opcode==OP_Function || opcode==OP_AggStep ){
60652       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
60653     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
60654       p->readOnly = 0;
60655 #ifndef SQLITE_OMIT_VIRTUALTABLE
60656     }else if( opcode==OP_VUpdate ){
60657       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
60658     }else if( opcode==OP_VFilter ){
60659       int n;
60660       assert( p->nOp - i >= 3 );
60661       assert( pOp[-1].opcode==OP_Integer );
60662       n = pOp[-1].p1;
60663       if( n>nMaxArgs ) nMaxArgs = n;
60664 #endif
60665     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
60666       pOp->p4.xAdvance = sqlite3BtreeNext;
60667       pOp->p4type = P4_ADVANCE;
60668     }else if( opcode==OP_Prev ){
60669       pOp->p4.xAdvance = sqlite3BtreePrevious;
60670       pOp->p4type = P4_ADVANCE;
60671     }
60672
60673     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
60674       assert( -1-pOp->p2<p->nLabel );
60675       pOp->p2 = aLabel[-1-pOp->p2];
60676     }
60677   }
60678   sqlite3DbFree(p->db, p->aLabel);
60679   p->aLabel = 0;
60680
60681   *pMaxFuncArgs = nMaxArgs;
60682 }
60683
60684 /*
60685 ** Return the address of the next instruction to be inserted.
60686 */
60687 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
60688   assert( p->magic==VDBE_MAGIC_INIT );
60689   return p->nOp;
60690 }
60691
60692 /*
60693 ** This function returns a pointer to the array of opcodes associated with
60694 ** the Vdbe passed as the first argument. It is the callers responsibility
60695 ** to arrange for the returned array to be eventually freed using the
60696 ** vdbeFreeOpArray() function.
60697 **
60698 ** Before returning, *pnOp is set to the number of entries in the returned
60699 ** array. Also, *pnMaxArg is set to the larger of its current value and
60700 ** the number of entries in the Vdbe.apArg[] array required to execute the
60701 ** returned program.
60702 */
60703 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
60704   VdbeOp *aOp = p->aOp;
60705   assert( aOp && !p->db->mallocFailed );
60706
60707   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
60708   assert( p->btreeMask==0 );
60709
60710   resolveP2Values(p, pnMaxArg);
60711   *pnOp = p->nOp;
60712   p->aOp = 0;
60713   return aOp;
60714 }
60715
60716 /*
60717 ** Add a whole list of operations to the operation stack.  Return the
60718 ** address of the first operation added.
60719 */
60720 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60721   int addr;
60722   assert( p->magic==VDBE_MAGIC_INIT );
60723   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60724     return 0;
60725   }
60726   addr = p->nOp;
60727   if( ALWAYS(nOp>0) ){
60728     int i;
60729     VdbeOpList const *pIn = aOp;
60730     for(i=0; i<nOp; i++, pIn++){
60731       int p2 = pIn->p2;
60732       VdbeOp *pOut = &p->aOp[i+addr];
60733       pOut->opcode = pIn->opcode;
60734       pOut->p1 = pIn->p1;
60735       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60736         pOut->p2 = addr + ADDR(p2);
60737       }else{
60738         pOut->p2 = p2;
60739       }
60740       pOut->p3 = pIn->p3;
60741       pOut->p4type = P4_NOTUSED;
60742       pOut->p4.p = 0;
60743       pOut->p5 = 0;
60744 #ifdef SQLITE_DEBUG
60745       pOut->zComment = 0;
60746       if( sqlite3VdbeAddopTrace ){
60747         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60748       }
60749 #endif
60750     }
60751     p->nOp += nOp;
60752   }
60753   return addr;
60754 }
60755
60756 /*
60757 ** Change the value of the P1 operand for a specific instruction.
60758 ** This routine is useful when a large program is loaded from a
60759 ** static array using sqlite3VdbeAddOpList but we want to make a
60760 ** few minor changes to the program.
60761 */
60762 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60763   assert( p!=0 );
60764   if( ((u32)p->nOp)>addr ){
60765     p->aOp[addr].p1 = val;
60766   }
60767 }
60768
60769 /*
60770 ** Change the value of the P2 operand for a specific instruction.
60771 ** This routine is useful for setting a jump destination.
60772 */
60773 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60774   assert( p!=0 );
60775   if( ((u32)p->nOp)>addr ){
60776     p->aOp[addr].p2 = val;
60777   }
60778 }
60779
60780 /*
60781 ** Change the value of the P3 operand for a specific instruction.
60782 */
60783 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60784   assert( p!=0 );
60785   if( ((u32)p->nOp)>addr ){
60786     p->aOp[addr].p3 = val;
60787   }
60788 }
60789
60790 /*
60791 ** Change the value of the P5 operand for the most recently
60792 ** added operation.
60793 */
60794 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
60795   assert( p!=0 );
60796   if( p->aOp ){
60797     assert( p->nOp>0 );
60798     p->aOp[p->nOp-1].p5 = val;
60799   }
60800 }
60801
60802 /*
60803 ** Change the P2 operand of instruction addr so that it points to
60804 ** the address of the next instruction to be coded.
60805 */
60806 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
60807   assert( addr>=0 || p->db->mallocFailed );
60808   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
60809 }
60810
60811
60812 /*
60813 ** If the input FuncDef structure is ephemeral, then free it.  If
60814 ** the FuncDef is not ephermal, then do nothing.
60815 */
60816 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
60817   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
60818     sqlite3DbFree(db, pDef);
60819   }
60820 }
60821
60822 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
60823
60824 /*
60825 ** Delete a P4 value if necessary.
60826 */
60827 static void freeP4(sqlite3 *db, int p4type, void *p4){
60828   if( p4 ){
60829     assert( db );
60830     switch( p4type ){
60831       case P4_REAL:
60832       case P4_INT64:
60833       case P4_DYNAMIC:
60834       case P4_KEYINFO:
60835       case P4_INTARRAY:
60836       case P4_KEYINFO_HANDOFF: {
60837         sqlite3DbFree(db, p4);
60838         break;
60839       }
60840       case P4_MPRINTF: {
60841         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
60842         break;
60843       }
60844       case P4_VDBEFUNC: {
60845         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
60846         freeEphemeralFunction(db, pVdbeFunc->pFunc);
60847         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
60848         sqlite3DbFree(db, pVdbeFunc);
60849         break;
60850       }
60851       case P4_FUNCDEF: {
60852         freeEphemeralFunction(db, (FuncDef*)p4);
60853         break;
60854       }
60855       case P4_MEM: {
60856         if( db->pnBytesFreed==0 ){
60857           sqlite3ValueFree((sqlite3_value*)p4);
60858         }else{
60859           Mem *p = (Mem*)p4;
60860           sqlite3DbFree(db, p->zMalloc);
60861           sqlite3DbFree(db, p);
60862         }
60863         break;
60864       }
60865       case P4_VTAB : {
60866         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
60867         break;
60868       }
60869     }
60870   }
60871 }
60872
60873 /*
60874 ** Free the space allocated for aOp and any p4 values allocated for the
60875 ** opcodes contained within. If aOp is not NULL it is assumed to contain
60876 ** nOp entries.
60877 */
60878 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
60879   if( aOp ){
60880     Op *pOp;
60881     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60882       freeP4(db, pOp->p4type, pOp->p4.p);
60883 #ifdef SQLITE_DEBUG
60884       sqlite3DbFree(db, pOp->zComment);
60885 #endif
60886     }
60887   }
60888   sqlite3DbFree(db, aOp);
60889 }
60890
60891 /*
60892 ** Link the SubProgram object passed as the second argument into the linked
60893 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60894 ** objects when the VM is no longer required.
60895 */
60896 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60897   p->pNext = pVdbe->pProgram;
60898   pVdbe->pProgram = p;
60899 }
60900
60901 /*
60902 ** Change the opcode at addr into OP_Noop
60903 */
60904 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
60905   if( p->aOp ){
60906     VdbeOp *pOp = &p->aOp[addr];
60907     sqlite3 *db = p->db;
60908     freeP4(db, pOp->p4type, pOp->p4.p);
60909     memset(pOp, 0, sizeof(pOp[0]));
60910     pOp->opcode = OP_Noop;
60911   }
60912 }
60913
60914 /*
60915 ** Change the value of the P4 operand for a specific instruction.
60916 ** This routine is useful when a large program is loaded from a
60917 ** static array using sqlite3VdbeAddOpList but we want to make a
60918 ** few minor changes to the program.
60919 **
60920 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60921 ** the string is made into memory obtained from sqlite3_malloc().
60922 ** A value of n==0 means copy bytes of zP4 up to and including the
60923 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
60924 **
60925 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60926 ** A copy is made of the KeyInfo structure into memory obtained from
60927 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
60928 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60929 ** stored in memory that the caller has obtained from sqlite3_malloc. The
60930 ** caller should not free the allocation, it will be freed when the Vdbe is
60931 ** finalized.
60932 **
60933 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60934 ** to a string or structure that is guaranteed to exist for the lifetime of
60935 ** the Vdbe. In these cases we can just copy the pointer.
60936 **
60937 ** If addr<0 then change P4 on the most recently inserted instruction.
60938 */
60939 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60940   Op *pOp;
60941   sqlite3 *db;
60942   assert( p!=0 );
60943   db = p->db;
60944   assert( p->magic==VDBE_MAGIC_INIT );
60945   if( p->aOp==0 || db->mallocFailed ){
60946     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60947       freeP4(db, n, (void*)*(char**)&zP4);
60948     }
60949     return;
60950   }
60951   assert( p->nOp>0 );
60952   assert( addr<p->nOp );
60953   if( addr<0 ){
60954     addr = p->nOp - 1;
60955   }
60956   pOp = &p->aOp[addr];
60957   assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
60958   freeP4(db, pOp->p4type, pOp->p4.p);
60959   pOp->p4.p = 0;
60960   if( n==P4_INT32 ){
60961     /* Note: this cast is safe, because the origin data point was an int
60962     ** that was cast to a (const char *). */
60963     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
60964     pOp->p4type = P4_INT32;
60965   }else if( zP4==0 ){
60966     pOp->p4.p = 0;
60967     pOp->p4type = P4_NOTUSED;
60968   }else if( n==P4_KEYINFO ){
60969     KeyInfo *pKeyInfo;
60970     int nField, nByte;
60971
60972     nField = ((KeyInfo*)zP4)->nField;
60973     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
60974     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
60975     pOp->p4.pKeyInfo = pKeyInfo;
60976     if( pKeyInfo ){
60977       u8 *aSortOrder;
60978       memcpy((char*)pKeyInfo, zP4, nByte - nField);
60979       aSortOrder = pKeyInfo->aSortOrder;
60980       assert( aSortOrder!=0 );
60981       pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
60982       memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
60983       pOp->p4type = P4_KEYINFO;
60984     }else{
60985       p->db->mallocFailed = 1;
60986       pOp->p4type = P4_NOTUSED;
60987     }
60988   }else if( n==P4_KEYINFO_HANDOFF ){
60989     pOp->p4.p = (void*)zP4;
60990     pOp->p4type = P4_KEYINFO;
60991   }else if( n==P4_VTAB ){
60992     pOp->p4.p = (void*)zP4;
60993     pOp->p4type = P4_VTAB;
60994     sqlite3VtabLock((VTable *)zP4);
60995     assert( ((VTable *)zP4)->db==p->db );
60996   }else if( n<0 ){
60997     pOp->p4.p = (void*)zP4;
60998     pOp->p4type = (signed char)n;
60999   }else{
61000     if( n==0 ) n = sqlite3Strlen30(zP4);
61001     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
61002     pOp->p4type = P4_DYNAMIC;
61003   }
61004 }
61005
61006 #ifndef NDEBUG
61007 /*
61008 ** Change the comment on the most recently coded instruction.  Or
61009 ** insert a No-op and add the comment to that new instruction.  This
61010 ** makes the code easier to read during debugging.  None of this happens
61011 ** in a production build.
61012 */
61013 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
61014   assert( p->nOp>0 || p->aOp==0 );
61015   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
61016   if( p->nOp ){
61017     assert( p->aOp );
61018     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
61019     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
61020   }
61021 }
61022 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
61023   va_list ap;
61024   if( p ){
61025     va_start(ap, zFormat);
61026     vdbeVComment(p, zFormat, ap);
61027     va_end(ap);
61028   }
61029 }
61030 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
61031   va_list ap;
61032   if( p ){
61033     sqlite3VdbeAddOp0(p, OP_Noop);
61034     va_start(ap, zFormat);
61035     vdbeVComment(p, zFormat, ap);
61036     va_end(ap);
61037   }
61038 }
61039 #endif  /* NDEBUG */
61040
61041 /*
61042 ** Return the opcode for a given address.  If the address is -1, then
61043 ** return the most recently inserted opcode.
61044 **
61045 ** If a memory allocation error has occurred prior to the calling of this
61046 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
61047 ** is readable but not writable, though it is cast to a writable value.
61048 ** The return of a dummy opcode allows the call to continue functioning
61049 ** after a OOM fault without having to check to see if the return from
61050 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
61051 ** dummy will never be written to.  This is verified by code inspection and
61052 ** by running with Valgrind.
61053 **
61054 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
61055 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
61056 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
61057 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
61058 ** having to double-check to make sure that the result is non-negative. But
61059 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
61060 ** check the value of p->nOp-1 before continuing.
61061 */
61062 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
61063   /* C89 specifies that the constant "dummy" will be initialized to all
61064   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
61065   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
61066   assert( p->magic==VDBE_MAGIC_INIT );
61067   if( addr<0 ){
61068 #ifdef SQLITE_OMIT_TRACE
61069     if( p->nOp==0 ) return (VdbeOp*)&dummy;
61070 #endif
61071     addr = p->nOp - 1;
61072   }
61073   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
61074   if( p->db->mallocFailed ){
61075     return (VdbeOp*)&dummy;
61076   }else{
61077     return &p->aOp[addr];
61078   }
61079 }
61080
61081 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
61082      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
61083 /*
61084 ** Compute a string that describes the P4 parameter for an opcode.
61085 ** Use zTemp for any required temporary buffer space.
61086 */
61087 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
61088   char *zP4 = zTemp;
61089   assert( nTemp>=20 );
61090   switch( pOp->p4type ){
61091     case P4_KEYINFO_STATIC:
61092     case P4_KEYINFO: {
61093       int i, j;
61094       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
61095       assert( pKeyInfo->aSortOrder!=0 );
61096       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
61097       i = sqlite3Strlen30(zTemp);
61098       for(j=0; j<pKeyInfo->nField; j++){
61099         CollSeq *pColl = pKeyInfo->aColl[j];
61100         const char *zColl = pColl ? pColl->zName : "nil";
61101         int n = sqlite3Strlen30(zColl);
61102         if( i+n>nTemp-6 ){
61103           memcpy(&zTemp[i],",...",4);
61104           break;
61105         }
61106         zTemp[i++] = ',';
61107         if( pKeyInfo->aSortOrder[j] ){
61108           zTemp[i++] = '-';
61109         }
61110         memcpy(&zTemp[i], zColl, n+1);
61111         i += n;
61112       }
61113       zTemp[i++] = ')';
61114       zTemp[i] = 0;
61115       assert( i<nTemp );
61116       break;
61117     }
61118     case P4_COLLSEQ: {
61119       CollSeq *pColl = pOp->p4.pColl;
61120       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
61121       break;
61122     }
61123     case P4_FUNCDEF: {
61124       FuncDef *pDef = pOp->p4.pFunc;
61125       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
61126       break;
61127     }
61128     case P4_INT64: {
61129       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
61130       break;
61131     }
61132     case P4_INT32: {
61133       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
61134       break;
61135     }
61136     case P4_REAL: {
61137       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
61138       break;
61139     }
61140     case P4_MEM: {
61141       Mem *pMem = pOp->p4.pMem;
61142       if( pMem->flags & MEM_Str ){
61143         zP4 = pMem->z;
61144       }else if( pMem->flags & MEM_Int ){
61145         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
61146       }else if( pMem->flags & MEM_Real ){
61147         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
61148       }else if( pMem->flags & MEM_Null ){
61149         sqlite3_snprintf(nTemp, zTemp, "NULL");
61150       }else{
61151         assert( pMem->flags & MEM_Blob );
61152         zP4 = "(blob)";
61153       }
61154       break;
61155     }
61156 #ifndef SQLITE_OMIT_VIRTUALTABLE
61157     case P4_VTAB: {
61158       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
61159       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
61160       break;
61161     }
61162 #endif
61163     case P4_INTARRAY: {
61164       sqlite3_snprintf(nTemp, zTemp, "intarray");
61165       break;
61166     }
61167     case P4_SUBPROGRAM: {
61168       sqlite3_snprintf(nTemp, zTemp, "program");
61169       break;
61170     }
61171     case P4_ADVANCE: {
61172       zTemp[0] = 0;
61173       break;
61174     }
61175     default: {
61176       zP4 = pOp->p4.z;
61177       if( zP4==0 ){
61178         zP4 = zTemp;
61179         zTemp[0] = 0;
61180       }
61181     }
61182   }
61183   assert( zP4!=0 );
61184   return zP4;
61185 }
61186 #endif
61187
61188 /*
61189 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
61190 **
61191 ** The prepared statements need to know in advance the complete set of
61192 ** attached databases that will be use.  A mask of these databases
61193 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
61194 ** p->btreeMask of databases that will require a lock.
61195 */
61196 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
61197   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
61198   assert( i<(int)sizeof(p->btreeMask)*8 );
61199   p->btreeMask |= ((yDbMask)1)<<i;
61200   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
61201     p->lockMask |= ((yDbMask)1)<<i;
61202   }
61203 }
61204
61205 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
61206 /*
61207 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
61208 ** this routine obtains the mutex associated with each BtShared structure
61209 ** that may be accessed by the VM passed as an argument. In doing so it also
61210 ** sets the BtShared.db member of each of the BtShared structures, ensuring
61211 ** that the correct busy-handler callback is invoked if required.
61212 **
61213 ** If SQLite is not threadsafe but does support shared-cache mode, then
61214 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
61215 ** of all of BtShared structures accessible via the database handle
61216 ** associated with the VM.
61217 **
61218 ** If SQLite is not threadsafe and does not support shared-cache mode, this
61219 ** function is a no-op.
61220 **
61221 ** The p->btreeMask field is a bitmask of all btrees that the prepared
61222 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
61223 ** corresponding to btrees that use shared cache.  Then the runtime of
61224 ** this routine is N*N.  But as N is rarely more than 1, this should not
61225 ** be a problem.
61226 */
61227 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
61228   int i;
61229   yDbMask mask;
61230   sqlite3 *db;
61231   Db *aDb;
61232   int nDb;
61233   if( p->lockMask==0 ) return;  /* The common case */
61234   db = p->db;
61235   aDb = db->aDb;
61236   nDb = db->nDb;
61237   for(i=0, mask=1; i<nDb; i++, mask += mask){
61238     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
61239       sqlite3BtreeEnter(aDb[i].pBt);
61240     }
61241   }
61242 }
61243 #endif
61244
61245 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
61246 /*
61247 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
61248 */
61249 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
61250   int i;
61251   yDbMask mask;
61252   sqlite3 *db;
61253   Db *aDb;
61254   int nDb;
61255   if( p->lockMask==0 ) return;  /* The common case */
61256   db = p->db;
61257   aDb = db->aDb;
61258   nDb = db->nDb;
61259   for(i=0, mask=1; i<nDb; i++, mask += mask){
61260     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
61261       sqlite3BtreeLeave(aDb[i].pBt);
61262     }
61263   }
61264 }
61265 #endif
61266
61267 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
61268 /*
61269 ** Print a single opcode.  This routine is used for debugging only.
61270 */
61271 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
61272   char *zP4;
61273   char zPtr[50];
61274   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
61275   if( pOut==0 ) pOut = stdout;
61276   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
61277   fprintf(pOut, zFormat1, pc,
61278       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
61279 #ifdef SQLITE_DEBUG
61280       pOp->zComment ? pOp->zComment : ""
61281 #else
61282       ""
61283 #endif
61284   );
61285   fflush(pOut);
61286 }
61287 #endif
61288
61289 /*
61290 ** Release an array of N Mem elements
61291 */
61292 static void releaseMemArray(Mem *p, int N){
61293   if( p && N ){
61294     Mem *pEnd;
61295     sqlite3 *db = p->db;
61296     u8 malloc_failed = db->mallocFailed;
61297     if( db->pnBytesFreed ){
61298       for(pEnd=&p[N]; p<pEnd; p++){
61299         sqlite3DbFree(db, p->zMalloc);
61300       }
61301       return;
61302     }
61303     for(pEnd=&p[N]; p<pEnd; p++){
61304       assert( (&p[1])==pEnd || p[0].db==p[1].db );
61305
61306       /* This block is really an inlined version of sqlite3VdbeMemRelease()
61307       ** that takes advantage of the fact that the memory cell value is
61308       ** being set to NULL after releasing any dynamic resources.
61309       **
61310       ** The justification for duplicating code is that according to
61311       ** callgrind, this causes a certain test case to hit the CPU 4.7
61312       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
61313       ** sqlite3MemRelease() were called from here. With -O2, this jumps
61314       ** to 6.6 percent. The test case is inserting 1000 rows into a table
61315       ** with no indexes using a single prepared INSERT statement, bind()
61316       ** and reset(). Inserts are grouped into a transaction.
61317       */
61318       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
61319         sqlite3VdbeMemRelease(p);
61320       }else if( p->zMalloc ){
61321         sqlite3DbFree(db, p->zMalloc);
61322         p->zMalloc = 0;
61323       }
61324
61325       p->flags = MEM_Invalid;
61326     }
61327     db->mallocFailed = malloc_failed;
61328   }
61329 }
61330
61331 /*
61332 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
61333 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
61334 */
61335 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
61336   int i;
61337   Mem *aMem = VdbeFrameMem(p);
61338   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
61339   for(i=0; i<p->nChildCsr; i++){
61340     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
61341   }
61342   releaseMemArray(aMem, p->nChildMem);
61343   sqlite3DbFree(p->v->db, p);
61344 }
61345
61346 #ifndef SQLITE_OMIT_EXPLAIN
61347 /*
61348 ** Give a listing of the program in the virtual machine.
61349 **
61350 ** The interface is the same as sqlite3VdbeExec().  But instead of
61351 ** running the code, it invokes the callback once for each instruction.
61352 ** This feature is used to implement "EXPLAIN".
61353 **
61354 ** When p->explain==1, each instruction is listed.  When
61355 ** p->explain==2, only OP_Explain instructions are listed and these
61356 ** are shown in a different format.  p->explain==2 is used to implement
61357 ** EXPLAIN QUERY PLAN.
61358 **
61359 ** When p->explain==1, first the main program is listed, then each of
61360 ** the trigger subprograms are listed one by one.
61361 */
61362 SQLITE_PRIVATE int sqlite3VdbeList(
61363   Vdbe *p                   /* The VDBE */
61364 ){
61365   int nRow;                            /* Stop when row count reaches this */
61366   int nSub = 0;                        /* Number of sub-vdbes seen so far */
61367   SubProgram **apSub = 0;              /* Array of sub-vdbes */
61368   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
61369   sqlite3 *db = p->db;                 /* The database connection */
61370   int i;                               /* Loop counter */
61371   int rc = SQLITE_OK;                  /* Return code */
61372   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
61373
61374   assert( p->explain );
61375   assert( p->magic==VDBE_MAGIC_RUN );
61376   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
61377
61378   /* Even though this opcode does not use dynamic strings for
61379   ** the result, result columns may become dynamic if the user calls
61380   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
61381   */
61382   releaseMemArray(pMem, 8);
61383   p->pResultSet = 0;
61384
61385   if( p->rc==SQLITE_NOMEM ){
61386     /* This happens if a malloc() inside a call to sqlite3_column_text() or
61387     ** sqlite3_column_text16() failed.  */
61388     db->mallocFailed = 1;
61389     return SQLITE_ERROR;
61390   }
61391
61392   /* When the number of output rows reaches nRow, that means the
61393   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
61394   ** nRow is the sum of the number of rows in the main program, plus
61395   ** the sum of the number of rows in all trigger subprograms encountered
61396   ** so far.  The nRow value will increase as new trigger subprograms are
61397   ** encountered, but p->pc will eventually catch up to nRow.
61398   */
61399   nRow = p->nOp;
61400   if( p->explain==1 ){
61401     /* The first 8 memory cells are used for the result set.  So we will
61402     ** commandeer the 9th cell to use as storage for an array of pointers
61403     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
61404     ** cells.  */
61405     assert( p->nMem>9 );
61406     pSub = &p->aMem[9];
61407     if( pSub->flags&MEM_Blob ){
61408       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
61409       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
61410       nSub = pSub->n/sizeof(Vdbe*);
61411       apSub = (SubProgram **)pSub->z;
61412     }
61413     for(i=0; i<nSub; i++){
61414       nRow += apSub[i]->nOp;
61415     }
61416   }
61417
61418   do{
61419     i = p->pc++;
61420   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
61421   if( i>=nRow ){
61422     p->rc = SQLITE_OK;
61423     rc = SQLITE_DONE;
61424   }else if( db->u1.isInterrupted ){
61425     p->rc = SQLITE_INTERRUPT;
61426     rc = SQLITE_ERROR;
61427     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
61428   }else{
61429     char *z;
61430     Op *pOp;
61431     if( i<p->nOp ){
61432       /* The output line number is small enough that we are still in the
61433       ** main program. */
61434       pOp = &p->aOp[i];
61435     }else{
61436       /* We are currently listing subprograms.  Figure out which one and
61437       ** pick up the appropriate opcode. */
61438       int j;
61439       i -= p->nOp;
61440       for(j=0; i>=apSub[j]->nOp; j++){
61441         i -= apSub[j]->nOp;
61442       }
61443       pOp = &apSub[j]->aOp[i];
61444     }
61445     if( p->explain==1 ){
61446       pMem->flags = MEM_Int;
61447       pMem->type = SQLITE_INTEGER;
61448       pMem->u.i = i;                                /* Program counter */
61449       pMem++;
61450
61451       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
61452       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
61453       assert( pMem->z!=0 );
61454       pMem->n = sqlite3Strlen30(pMem->z);
61455       pMem->type = SQLITE_TEXT;
61456       pMem->enc = SQLITE_UTF8;
61457       pMem++;
61458
61459       /* When an OP_Program opcode is encounter (the only opcode that has
61460       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
61461       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
61462       ** has not already been seen.
61463       */
61464       if( pOp->p4type==P4_SUBPROGRAM ){
61465         int nByte = (nSub+1)*sizeof(SubProgram*);
61466         int j;
61467         for(j=0; j<nSub; j++){
61468           if( apSub[j]==pOp->p4.pProgram ) break;
61469         }
61470         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
61471           apSub = (SubProgram **)pSub->z;
61472           apSub[nSub++] = pOp->p4.pProgram;
61473           pSub->flags |= MEM_Blob;
61474           pSub->n = nSub*sizeof(SubProgram*);
61475         }
61476       }
61477     }
61478
61479     pMem->flags = MEM_Int;
61480     pMem->u.i = pOp->p1;                          /* P1 */
61481     pMem->type = SQLITE_INTEGER;
61482     pMem++;
61483
61484     pMem->flags = MEM_Int;
61485     pMem->u.i = pOp->p2;                          /* P2 */
61486     pMem->type = SQLITE_INTEGER;
61487     pMem++;
61488
61489     pMem->flags = MEM_Int;
61490     pMem->u.i = pOp->p3;                          /* P3 */
61491     pMem->type = SQLITE_INTEGER;
61492     pMem++;
61493
61494     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
61495       assert( p->db->mallocFailed );
61496       return SQLITE_ERROR;
61497     }
61498     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61499     z = displayP4(pOp, pMem->z, 32);
61500     if( z!=pMem->z ){
61501       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
61502     }else{
61503       assert( pMem->z!=0 );
61504       pMem->n = sqlite3Strlen30(pMem->z);
61505       pMem->enc = SQLITE_UTF8;
61506     }
61507     pMem->type = SQLITE_TEXT;
61508     pMem++;
61509
61510     if( p->explain==1 ){
61511       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
61512         assert( p->db->mallocFailed );
61513         return SQLITE_ERROR;
61514       }
61515       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61516       pMem->n = 2;
61517       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
61518       pMem->type = SQLITE_TEXT;
61519       pMem->enc = SQLITE_UTF8;
61520       pMem++;
61521
61522 #ifdef SQLITE_DEBUG
61523       if( pOp->zComment ){
61524         pMem->flags = MEM_Str|MEM_Term;
61525         pMem->z = pOp->zComment;
61526         pMem->n = sqlite3Strlen30(pMem->z);
61527         pMem->enc = SQLITE_UTF8;
61528         pMem->type = SQLITE_TEXT;
61529       }else
61530 #endif
61531       {
61532         pMem->flags = MEM_Null;                       /* Comment */
61533         pMem->type = SQLITE_NULL;
61534       }
61535     }
61536
61537     p->nResColumn = 8 - 4*(p->explain-1);
61538     p->pResultSet = &p->aMem[1];
61539     p->rc = SQLITE_OK;
61540     rc = SQLITE_ROW;
61541   }
61542   return rc;
61543 }
61544 #endif /* SQLITE_OMIT_EXPLAIN */
61545
61546 #ifdef SQLITE_DEBUG
61547 /*
61548 ** Print the SQL that was used to generate a VDBE program.
61549 */
61550 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
61551   int nOp = p->nOp;
61552   VdbeOp *pOp;
61553   if( nOp<1 ) return;
61554   pOp = &p->aOp[0];
61555   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61556     const char *z = pOp->p4.z;
61557     while( sqlite3Isspace(*z) ) z++;
61558     printf("SQL: [%s]\n", z);
61559   }
61560 }
61561 #endif
61562
61563 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
61564 /*
61565 ** Print an IOTRACE message showing SQL content.
61566 */
61567 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
61568   int nOp = p->nOp;
61569   VdbeOp *pOp;
61570   if( sqlite3IoTrace==0 ) return;
61571   if( nOp<1 ) return;
61572   pOp = &p->aOp[0];
61573   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61574     int i, j;
61575     char z[1000];
61576     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
61577     for(i=0; sqlite3Isspace(z[i]); i++){}
61578     for(j=0; z[i]; i++){
61579       if( sqlite3Isspace(z[i]) ){
61580         if( z[i-1]!=' ' ){
61581           z[j++] = ' ';
61582         }
61583       }else{
61584         z[j++] = z[i];
61585       }
61586     }
61587     z[j] = 0;
61588     sqlite3IoTrace("SQL %s\n", z);
61589   }
61590 }
61591 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
61592
61593 /*
61594 ** Allocate space from a fixed size buffer and return a pointer to
61595 ** that space.  If insufficient space is available, return NULL.
61596 **
61597 ** The pBuf parameter is the initial value of a pointer which will
61598 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
61599 ** NULL, it means that memory space has already been allocated and that
61600 ** this routine should not allocate any new memory.  When pBuf is not
61601 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
61602 ** is NULL.
61603 **
61604 ** nByte is the number of bytes of space needed.
61605 **
61606 ** *ppFrom points to available space and pEnd points to the end of the
61607 ** available space.  When space is allocated, *ppFrom is advanced past
61608 ** the end of the allocated space.
61609 **
61610 ** *pnByte is a counter of the number of bytes of space that have failed
61611 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
61612 ** request, then increment *pnByte by the amount of the request.
61613 */
61614 static void *allocSpace(
61615   void *pBuf,          /* Where return pointer will be stored */
61616   int nByte,           /* Number of bytes to allocate */
61617   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
61618   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
61619   int *pnByte          /* If allocation cannot be made, increment *pnByte */
61620 ){
61621   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
61622   if( pBuf ) return pBuf;
61623   nByte = ROUND8(nByte);
61624   if( &(*ppFrom)[nByte] <= pEnd ){
61625     pBuf = (void*)*ppFrom;
61626     *ppFrom += nByte;
61627   }else{
61628     *pnByte += nByte;
61629   }
61630   return pBuf;
61631 }
61632
61633 /*
61634 ** Rewind the VDBE back to the beginning in preparation for
61635 ** running it.
61636 */
61637 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
61638 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
61639   int i;
61640 #endif
61641   assert( p!=0 );
61642   assert( p->magic==VDBE_MAGIC_INIT );
61643
61644   /* There should be at least one opcode.
61645   */
61646   assert( p->nOp>0 );
61647
61648   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
61649   p->magic = VDBE_MAGIC_RUN;
61650
61651 #ifdef SQLITE_DEBUG
61652   for(i=1; i<p->nMem; i++){
61653     assert( p->aMem[i].db==p->db );
61654   }
61655 #endif
61656   p->pc = -1;
61657   p->rc = SQLITE_OK;
61658   p->errorAction = OE_Abort;
61659   p->magic = VDBE_MAGIC_RUN;
61660   p->nChange = 0;
61661   p->cacheCtr = 1;
61662   p->minWriteFileFormat = 255;
61663   p->iStatement = 0;
61664   p->nFkConstraint = 0;
61665 #ifdef VDBE_PROFILE
61666   for(i=0; i<p->nOp; i++){
61667     p->aOp[i].cnt = 0;
61668     p->aOp[i].cycles = 0;
61669   }
61670 #endif
61671 }
61672
61673 /*
61674 ** Prepare a virtual machine for execution for the first time after
61675 ** creating the virtual machine.  This involves things such
61676 ** as allocating stack space and initializing the program counter.
61677 ** After the VDBE has be prepped, it can be executed by one or more
61678 ** calls to sqlite3VdbeExec().
61679 **
61680 ** This function may be called exact once on a each virtual machine.
61681 ** After this routine is called the VM has been "packaged" and is ready
61682 ** to run.  After this routine is called, futher calls to
61683 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
61684 ** the Vdbe from the Parse object that helped generate it so that the
61685 ** the Vdbe becomes an independent entity and the Parse object can be
61686 ** destroyed.
61687 **
61688 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
61689 ** to its initial state after it has been run.
61690 */
61691 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
61692   Vdbe *p,                       /* The VDBE */
61693   Parse *pParse                  /* Parsing context */
61694 ){
61695   sqlite3 *db;                   /* The database connection */
61696   int nVar;                      /* Number of parameters */
61697   int nMem;                      /* Number of VM memory registers */
61698   int nCursor;                   /* Number of cursors required */
61699   int nArg;                      /* Number of arguments in subprograms */
61700   int nOnce;                     /* Number of OP_Once instructions */
61701   int n;                         /* Loop counter */
61702   u8 *zCsr;                      /* Memory available for allocation */
61703   u8 *zEnd;                      /* First byte past allocated memory */
61704   int nByte;                     /* How much extra memory is needed */
61705
61706   assert( p!=0 );
61707   assert( p->nOp>0 );
61708   assert( pParse!=0 );
61709   assert( p->magic==VDBE_MAGIC_INIT );
61710   db = p->db;
61711   assert( db->mallocFailed==0 );
61712   nVar = pParse->nVar;
61713   nMem = pParse->nMem;
61714   nCursor = pParse->nTab;
61715   nArg = pParse->nMaxArg;
61716   nOnce = pParse->nOnce;
61717   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
61718
61719   /* For each cursor required, also allocate a memory cell. Memory
61720   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61721   ** the vdbe program. Instead they are used to allocate space for
61722   ** VdbeCursor/BtCursor structures. The blob of memory associated with
61723   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61724   ** stores the blob of memory associated with cursor 1, etc.
61725   **
61726   ** See also: allocateCursor().
61727   */
61728   nMem += nCursor;
61729
61730   /* Allocate space for memory registers, SQL variables, VDBE cursors and
61731   ** an array to marshal SQL function arguments in.
61732   */
61733   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61734   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61735
61736   resolveP2Values(p, &nArg);
61737   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61738   if( pParse->explain && nMem<10 ){
61739     nMem = 10;
61740   }
61741   memset(zCsr, 0, zEnd-zCsr);
61742   zCsr += (zCsr - (u8*)0)&7;
61743   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61744   p->expired = 0;
61745
61746   /* Memory for registers, parameters, cursor, etc, is allocated in two
61747   ** passes.  On the first pass, we try to reuse unused space at the
61748   ** end of the opcode array.  If we are unable to satisfy all memory
61749   ** requirements by reusing the opcode array tail, then the second
61750   ** pass will fill in the rest using a fresh allocation.
61751   **
61752   ** This two-pass approach that reuses as much memory as possible from
61753   ** the leftover space at the end of the opcode array can significantly
61754   ** reduce the amount of memory held by a prepared statement.
61755   */
61756   do {
61757     nByte = 0;
61758     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61759     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61760     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61761     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61762     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61763                           &zCsr, zEnd, &nByte);
61764     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
61765     if( nByte ){
61766       p->pFree = sqlite3DbMallocZero(db, nByte);
61767     }
61768     zCsr = p->pFree;
61769     zEnd = &zCsr[nByte];
61770   }while( nByte && !db->mallocFailed );
61771
61772   p->nCursor = (u16)nCursor;
61773   p->nOnceFlag = nOnce;
61774   if( p->aVar ){
61775     p->nVar = (ynVar)nVar;
61776     for(n=0; n<nVar; n++){
61777       p->aVar[n].flags = MEM_Null;
61778       p->aVar[n].db = db;
61779     }
61780   }
61781   if( p->azVar ){
61782     p->nzVar = pParse->nzVar;
61783     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61784     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61785   }
61786   if( p->aMem ){
61787     p->aMem--;                      /* aMem[] goes from 1..nMem */
61788     p->nMem = nMem;                 /*       not from 0..nMem-1 */
61789     for(n=1; n<=nMem; n++){
61790       p->aMem[n].flags = MEM_Invalid;
61791       p->aMem[n].db = db;
61792     }
61793   }
61794   p->explain = pParse->explain;
61795   sqlite3VdbeRewind(p);
61796 }
61797
61798 /*
61799 ** Close a VDBE cursor and release all the resources that cursor
61800 ** happens to hold.
61801 */
61802 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61803   if( pCx==0 ){
61804     return;
61805   }
61806   sqlite3VdbeSorterClose(p->db, pCx);
61807   if( pCx->pBt ){
61808     sqlite3BtreeClose(pCx->pBt);
61809     /* The pCx->pCursor will be close automatically, if it exists, by
61810     ** the call above. */
61811   }else if( pCx->pCursor ){
61812     sqlite3BtreeCloseCursor(pCx->pCursor);
61813   }
61814 #ifndef SQLITE_OMIT_VIRTUALTABLE
61815   if( pCx->pVtabCursor ){
61816     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61817     const sqlite3_module *pModule = pCx->pModule;
61818     p->inVtabMethod = 1;
61819     pModule->xClose(pVtabCursor);
61820     p->inVtabMethod = 0;
61821   }
61822 #endif
61823 }
61824
61825 /*
61826 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61827 ** is used, for example, when a trigger sub-program is halted to restore
61828 ** control to the main program.
61829 */
61830 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
61831   Vdbe *v = pFrame->v;
61832   v->aOnceFlag = pFrame->aOnceFlag;
61833   v->nOnceFlag = pFrame->nOnceFlag;
61834   v->aOp = pFrame->aOp;
61835   v->nOp = pFrame->nOp;
61836   v->aMem = pFrame->aMem;
61837   v->nMem = pFrame->nMem;
61838   v->apCsr = pFrame->apCsr;
61839   v->nCursor = pFrame->nCursor;
61840   v->db->lastRowid = pFrame->lastRowid;
61841   v->nChange = pFrame->nChange;
61842   return pFrame->pc;
61843 }
61844
61845 /*
61846 ** Close all cursors.
61847 **
61848 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
61849 ** cell array. This is necessary as the memory cell array may contain
61850 ** pointers to VdbeFrame objects, which may in turn contain pointers to
61851 ** open cursors.
61852 */
61853 static void closeAllCursors(Vdbe *p){
61854   if( p->pFrame ){
61855     VdbeFrame *pFrame;
61856     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61857     sqlite3VdbeFrameRestore(pFrame);
61858   }
61859   p->pFrame = 0;
61860   p->nFrame = 0;
61861
61862   if( p->apCsr ){
61863     int i;
61864     for(i=0; i<p->nCursor; i++){
61865       VdbeCursor *pC = p->apCsr[i];
61866       if( pC ){
61867         sqlite3VdbeFreeCursor(p, pC);
61868         p->apCsr[i] = 0;
61869       }
61870     }
61871   }
61872   if( p->aMem ){
61873     releaseMemArray(&p->aMem[1], p->nMem);
61874   }
61875   while( p->pDelFrame ){
61876     VdbeFrame *pDel = p->pDelFrame;
61877     p->pDelFrame = pDel->pParent;
61878     sqlite3VdbeFrameDelete(pDel);
61879   }
61880 }
61881
61882 /*
61883 ** Clean up the VM after execution.
61884 **
61885 ** This routine will automatically close any cursors, lists, and/or
61886 ** sorters that were left open.  It also deletes the values of
61887 ** variables in the aVar[] array.
61888 */
61889 static void Cleanup(Vdbe *p){
61890   sqlite3 *db = p->db;
61891
61892 #ifdef SQLITE_DEBUG
61893   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
61894   ** Vdbe.aMem[] arrays have already been cleaned up.  */
61895   int i;
61896   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
61897   if( p->aMem ){
61898     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
61899   }
61900 #endif
61901
61902   sqlite3DbFree(db, p->zErrMsg);
61903   p->zErrMsg = 0;
61904   p->pResultSet = 0;
61905 }
61906
61907 /*
61908 ** Set the number of result columns that will be returned by this SQL
61909 ** statement. This is now set at compile time, rather than during
61910 ** execution of the vdbe program so that sqlite3_column_count() can
61911 ** be called on an SQL statement before sqlite3_step().
61912 */
61913 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
61914   Mem *pColName;
61915   int n;
61916   sqlite3 *db = p->db;
61917
61918   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61919   sqlite3DbFree(db, p->aColName);
61920   n = nResColumn*COLNAME_N;
61921   p->nResColumn = (u16)nResColumn;
61922   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
61923   if( p->aColName==0 ) return;
61924   while( n-- > 0 ){
61925     pColName->flags = MEM_Null;
61926     pColName->db = p->db;
61927     pColName++;
61928   }
61929 }
61930
61931 /*
61932 ** Set the name of the idx'th column to be returned by the SQL statement.
61933 ** zName must be a pointer to a nul terminated string.
61934 **
61935 ** This call must be made after a call to sqlite3VdbeSetNumCols().
61936 **
61937 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
61938 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
61939 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
61940 */
61941 SQLITE_PRIVATE int sqlite3VdbeSetColName(
61942   Vdbe *p,                         /* Vdbe being configured */
61943   int idx,                         /* Index of column zName applies to */
61944   int var,                         /* One of the COLNAME_* constants */
61945   const char *zName,               /* Pointer to buffer containing name */
61946   void (*xDel)(void*)              /* Memory management strategy for zName */
61947 ){
61948   int rc;
61949   Mem *pColName;
61950   assert( idx<p->nResColumn );
61951   assert( var<COLNAME_N );
61952   if( p->db->mallocFailed ){
61953     assert( !zName || xDel!=SQLITE_DYNAMIC );
61954     return SQLITE_NOMEM;
61955   }
61956   assert( p->aColName!=0 );
61957   pColName = &(p->aColName[idx+var*p->nResColumn]);
61958   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
61959   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61960   return rc;
61961 }
61962
61963 /*
61964 ** A read or write transaction may or may not be active on database handle
61965 ** db. If a transaction is active, commit it. If there is a
61966 ** write-transaction spanning more than one database file, this routine
61967 ** takes care of the master journal trickery.
61968 */
61969 static int vdbeCommit(sqlite3 *db, Vdbe *p){
61970   int i;
61971   int nTrans = 0;  /* Number of databases with an active write-transaction */
61972   int rc = SQLITE_OK;
61973   int needXcommit = 0;
61974
61975 #ifdef SQLITE_OMIT_VIRTUALTABLE
61976   /* With this option, sqlite3VtabSync() is defined to be simply
61977   ** SQLITE_OK so p is not used.
61978   */
61979   UNUSED_PARAMETER(p);
61980 #endif
61981
61982   /* Before doing anything else, call the xSync() callback for any
61983   ** virtual module tables written in this transaction. This has to
61984   ** be done before determining whether a master journal file is
61985   ** required, as an xSync() callback may add an attached database
61986   ** to the transaction.
61987   */
61988   rc = sqlite3VtabSync(db, &p->zErrMsg);
61989
61990   /* This loop determines (a) if the commit hook should be invoked and
61991   ** (b) how many database files have open write transactions, not
61992   ** including the temp database. (b) is important because if more than
61993   ** one database file has an open write transaction, a master journal
61994   ** file is required for an atomic commit.
61995   */
61996   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61997     Btree *pBt = db->aDb[i].pBt;
61998     if( sqlite3BtreeIsInTrans(pBt) ){
61999       needXcommit = 1;
62000       if( i!=1 ) nTrans++;
62001       sqlite3BtreeEnter(pBt);
62002       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
62003       sqlite3BtreeLeave(pBt);
62004     }
62005   }
62006   if( rc!=SQLITE_OK ){
62007     return rc;
62008   }
62009
62010   /* If there are any write-transactions at all, invoke the commit hook */
62011   if( needXcommit && db->xCommitCallback ){
62012     rc = db->xCommitCallback(db->pCommitArg);
62013     if( rc ){
62014       return SQLITE_CONSTRAINT;
62015     }
62016   }
62017
62018   /* The simple case - no more than one database file (not counting the
62019   ** TEMP database) has a transaction active.   There is no need for the
62020   ** master-journal.
62021   **
62022   ** If the return value of sqlite3BtreeGetFilename() is a zero length
62023   ** string, it means the main database is :memory: or a temp file.  In
62024   ** that case we do not support atomic multi-file commits, so use the
62025   ** simple case then too.
62026   */
62027   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
62028    || nTrans<=1
62029   ){
62030     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
62031       Btree *pBt = db->aDb[i].pBt;
62032       if( pBt ){
62033         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
62034       }
62035     }
62036
62037     /* Do the commit only if all databases successfully complete phase 1.
62038     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
62039     ** IO error while deleting or truncating a journal file. It is unlikely,
62040     ** but could happen. In this case abandon processing and return the error.
62041     */
62042     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
62043       Btree *pBt = db->aDb[i].pBt;
62044       if( pBt ){
62045         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
62046       }
62047     }
62048     if( rc==SQLITE_OK ){
62049       sqlite3VtabCommit(db);
62050     }
62051   }
62052
62053   /* The complex case - There is a multi-file write-transaction active.
62054   ** This requires a master journal file to ensure the transaction is
62055   ** committed atomicly.
62056   */
62057 #ifndef SQLITE_OMIT_DISKIO
62058   else{
62059     sqlite3_vfs *pVfs = db->pVfs;
62060     int needSync = 0;
62061     char *zMaster = 0;   /* File-name for the master journal */
62062     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
62063     sqlite3_file *pMaster = 0;
62064     i64 offset = 0;
62065     int res;
62066     int retryCount = 0;
62067     int nMainFile;
62068
62069     /* Select a master journal file name */
62070     nMainFile = sqlite3Strlen30(zMainFile);
62071     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
62072     if( zMaster==0 ) return SQLITE_NOMEM;
62073     do {
62074       u32 iRandom;
62075       if( retryCount ){
62076         if( retryCount>100 ){
62077           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
62078           sqlite3OsDelete(pVfs, zMaster, 0);
62079           break;
62080         }else if( retryCount==1 ){
62081           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
62082         }
62083       }
62084       retryCount++;
62085       sqlite3_randomness(sizeof(iRandom), &iRandom);
62086       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
62087                                (iRandom>>8)&0xffffff, iRandom&0xff);
62088       /* The antipenultimate character of the master journal name must
62089       ** be "9" to avoid name collisions when using 8+3 filenames. */
62090       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
62091       sqlite3FileSuffix3(zMainFile, zMaster);
62092       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
62093     }while( rc==SQLITE_OK && res );
62094     if( rc==SQLITE_OK ){
62095       /* Open the master journal. */
62096       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
62097           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
62098           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
62099       );
62100     }
62101     if( rc!=SQLITE_OK ){
62102       sqlite3DbFree(db, zMaster);
62103       return rc;
62104     }
62105
62106     /* Write the name of each database file in the transaction into the new
62107     ** master journal file. If an error occurs at this point close
62108     ** and delete the master journal file. All the individual journal files
62109     ** still have 'null' as the master journal pointer, so they will roll
62110     ** back independently if a failure occurs.
62111     */
62112     for(i=0; i<db->nDb; i++){
62113       Btree *pBt = db->aDb[i].pBt;
62114       if( sqlite3BtreeIsInTrans(pBt) ){
62115         char const *zFile = sqlite3BtreeGetJournalname(pBt);
62116         if( zFile==0 ){
62117           continue;  /* Ignore TEMP and :memory: databases */
62118         }
62119         assert( zFile[0]!=0 );
62120         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
62121           needSync = 1;
62122         }
62123         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
62124         offset += sqlite3Strlen30(zFile)+1;
62125         if( rc!=SQLITE_OK ){
62126           sqlite3OsCloseFree(pMaster);
62127           sqlite3OsDelete(pVfs, zMaster, 0);
62128           sqlite3DbFree(db, zMaster);
62129           return rc;
62130         }
62131       }
62132     }
62133
62134     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
62135     ** flag is set this is not required.
62136     */
62137     if( needSync
62138      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
62139      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
62140     ){
62141       sqlite3OsCloseFree(pMaster);
62142       sqlite3OsDelete(pVfs, zMaster, 0);
62143       sqlite3DbFree(db, zMaster);
62144       return rc;
62145     }
62146
62147     /* Sync all the db files involved in the transaction. The same call
62148     ** sets the master journal pointer in each individual journal. If
62149     ** an error occurs here, do not delete the master journal file.
62150     **
62151     ** If the error occurs during the first call to
62152     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
62153     ** master journal file will be orphaned. But we cannot delete it,
62154     ** in case the master journal file name was written into the journal
62155     ** file before the failure occurred.
62156     */
62157     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
62158       Btree *pBt = db->aDb[i].pBt;
62159       if( pBt ){
62160         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
62161       }
62162     }
62163     sqlite3OsCloseFree(pMaster);
62164     assert( rc!=SQLITE_BUSY );
62165     if( rc!=SQLITE_OK ){
62166       sqlite3DbFree(db, zMaster);
62167       return rc;
62168     }
62169
62170     /* Delete the master journal file. This commits the transaction. After
62171     ** doing this the directory is synced again before any individual
62172     ** transaction files are deleted.
62173     */
62174     rc = sqlite3OsDelete(pVfs, zMaster, 1);
62175     sqlite3DbFree(db, zMaster);
62176     zMaster = 0;
62177     if( rc ){
62178       return rc;
62179     }
62180
62181     /* All files and directories have already been synced, so the following
62182     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
62183     ** deleting or truncating journals. If something goes wrong while
62184     ** this is happening we don't really care. The integrity of the
62185     ** transaction is already guaranteed, but some stray 'cold' journals
62186     ** may be lying around. Returning an error code won't help matters.
62187     */
62188     disable_simulated_io_errors();
62189     sqlite3BeginBenignMalloc();
62190     for(i=0; i<db->nDb; i++){
62191       Btree *pBt = db->aDb[i].pBt;
62192       if( pBt ){
62193         sqlite3BtreeCommitPhaseTwo(pBt, 1);
62194       }
62195     }
62196     sqlite3EndBenignMalloc();
62197     enable_simulated_io_errors();
62198
62199     sqlite3VtabCommit(db);
62200   }
62201 #endif
62202
62203   return rc;
62204 }
62205
62206 /*
62207 ** This routine checks that the sqlite3.activeVdbeCnt count variable
62208 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
62209 ** currently active. An assertion fails if the two counts do not match.
62210 ** This is an internal self-check only - it is not an essential processing
62211 ** step.
62212 **
62213 ** This is a no-op if NDEBUG is defined.
62214 */
62215 #ifndef NDEBUG
62216 static void checkActiveVdbeCnt(sqlite3 *db){
62217   Vdbe *p;
62218   int cnt = 0;
62219   int nWrite = 0;
62220   p = db->pVdbe;
62221   while( p ){
62222     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
62223       cnt++;
62224       if( p->readOnly==0 ) nWrite++;
62225     }
62226     p = p->pNext;
62227   }
62228   assert( cnt==db->activeVdbeCnt );
62229   assert( nWrite==db->writeVdbeCnt );
62230 }
62231 #else
62232 #define checkActiveVdbeCnt(x)
62233 #endif
62234
62235 /*
62236 ** If the Vdbe passed as the first argument opened a statement-transaction,
62237 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
62238 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
62239 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
62240 ** statement transaction is commtted.
62241 **
62242 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
62243 ** Otherwise SQLITE_OK.
62244 */
62245 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
62246   sqlite3 *const db = p->db;
62247   int rc = SQLITE_OK;
62248
62249   /* If p->iStatement is greater than zero, then this Vdbe opened a
62250   ** statement transaction that should be closed here. The only exception
62251   ** is that an IO error may have occured, causing an emergency rollback.
62252   ** In this case (db->nStatement==0), and there is nothing to do.
62253   */
62254   if( db->nStatement && p->iStatement ){
62255     int i;
62256     const int iSavepoint = p->iStatement-1;
62257
62258     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
62259     assert( db->nStatement>0 );
62260     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
62261
62262     for(i=0; i<db->nDb; i++){
62263       int rc2 = SQLITE_OK;
62264       Btree *pBt = db->aDb[i].pBt;
62265       if( pBt ){
62266         if( eOp==SAVEPOINT_ROLLBACK ){
62267           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
62268         }
62269         if( rc2==SQLITE_OK ){
62270           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
62271         }
62272         if( rc==SQLITE_OK ){
62273           rc = rc2;
62274         }
62275       }
62276     }
62277     db->nStatement--;
62278     p->iStatement = 0;
62279
62280     if( rc==SQLITE_OK ){
62281       if( eOp==SAVEPOINT_ROLLBACK ){
62282         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
62283       }
62284       if( rc==SQLITE_OK ){
62285         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
62286       }
62287     }
62288
62289     /* If the statement transaction is being rolled back, also restore the
62290     ** database handles deferred constraint counter to the value it had when
62291     ** the statement transaction was opened.  */
62292     if( eOp==SAVEPOINT_ROLLBACK ){
62293       db->nDeferredCons = p->nStmtDefCons;
62294     }
62295   }
62296   return rc;
62297 }
62298
62299 /*
62300 ** This function is called when a transaction opened by the database
62301 ** handle associated with the VM passed as an argument is about to be
62302 ** committed. If there are outstanding deferred foreign key constraint
62303 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
62304 **
62305 ** If there are outstanding FK violations and this function returns
62306 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
62307 ** an error message to it. Then return SQLITE_ERROR.
62308 */
62309 #ifndef SQLITE_OMIT_FOREIGN_KEY
62310 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
62311   sqlite3 *db = p->db;
62312   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
62313     p->rc = SQLITE_CONSTRAINT;
62314     p->errorAction = OE_Abort;
62315     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
62316     return SQLITE_ERROR;
62317   }
62318   return SQLITE_OK;
62319 }
62320 #endif
62321
62322 /*
62323 ** This routine is called the when a VDBE tries to halt.  If the VDBE
62324 ** has made changes and is in autocommit mode, then commit those
62325 ** changes.  If a rollback is needed, then do the rollback.
62326 **
62327 ** This routine is the only way to move the state of a VM from
62328 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
62329 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
62330 **
62331 ** Return an error code.  If the commit could not complete because of
62332 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
62333 ** means the close did not happen and needs to be repeated.
62334 */
62335 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
62336   int rc;                         /* Used to store transient return codes */
62337   sqlite3 *db = p->db;
62338
62339   /* This function contains the logic that determines if a statement or
62340   ** transaction will be committed or rolled back as a result of the
62341   ** execution of this virtual machine.
62342   **
62343   ** If any of the following errors occur:
62344   **
62345   **     SQLITE_NOMEM
62346   **     SQLITE_IOERR
62347   **     SQLITE_FULL
62348   **     SQLITE_INTERRUPT
62349   **
62350   ** Then the internal cache might have been left in an inconsistent
62351   ** state.  We need to rollback the statement transaction, if there is
62352   ** one, or the complete transaction if there is no statement transaction.
62353   */
62354
62355   if( p->db->mallocFailed ){
62356     p->rc = SQLITE_NOMEM;
62357   }
62358   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
62359   closeAllCursors(p);
62360   if( p->magic!=VDBE_MAGIC_RUN ){
62361     return SQLITE_OK;
62362   }
62363   checkActiveVdbeCnt(db);
62364
62365   /* No commit or rollback needed if the program never started */
62366   if( p->pc>=0 ){
62367     int mrc;   /* Primary error code from p->rc */
62368     int eStatementOp = 0;
62369     int isSpecialError;            /* Set to true if a 'special' error */
62370
62371     /* Lock all btrees used by the statement */
62372     sqlite3VdbeEnter(p);
62373
62374     /* Check for one of the special errors */
62375     mrc = p->rc & 0xff;
62376     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
62377     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
62378                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
62379     if( isSpecialError ){
62380       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
62381       ** no rollback is necessary. Otherwise, at least a savepoint
62382       ** transaction must be rolled back to restore the database to a
62383       ** consistent state.
62384       **
62385       ** Even if the statement is read-only, it is important to perform
62386       ** a statement or transaction rollback operation. If the error
62387       ** occured while writing to the journal, sub-journal or database
62388       ** file as part of an effort to free up cache space (see function
62389       ** pagerStress() in pager.c), the rollback is required to restore
62390       ** the pager to a consistent state.
62391       */
62392       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
62393         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
62394           eStatementOp = SAVEPOINT_ROLLBACK;
62395         }else{
62396           /* We are forced to roll back the active transaction. Before doing
62397           ** so, abort any other statements this handle currently has active.
62398           */
62399           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62400           sqlite3CloseSavepoints(db);
62401           db->autoCommit = 1;
62402         }
62403       }
62404     }
62405
62406     /* Check for immediate foreign key violations. */
62407     if( p->rc==SQLITE_OK ){
62408       sqlite3VdbeCheckFk(p, 0);
62409     }
62410
62411     /* If the auto-commit flag is set and this is the only active writer
62412     ** VM, then we do either a commit or rollback of the current transaction.
62413     **
62414     ** Note: This block also runs if one of the special errors handled
62415     ** above has occurred.
62416     */
62417     if( !sqlite3VtabInSync(db)
62418      && db->autoCommit
62419      && db->writeVdbeCnt==(p->readOnly==0)
62420     ){
62421       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
62422         rc = sqlite3VdbeCheckFk(p, 1);
62423         if( rc!=SQLITE_OK ){
62424           if( NEVER(p->readOnly) ){
62425             sqlite3VdbeLeave(p);
62426             return SQLITE_ERROR;
62427           }
62428           rc = SQLITE_CONSTRAINT;
62429         }else{
62430           /* The auto-commit flag is true, the vdbe program was successful
62431           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
62432           ** key constraints to hold up the transaction. This means a commit
62433           ** is required. */
62434           rc = vdbeCommit(db, p);
62435         }
62436         if( rc==SQLITE_BUSY && p->readOnly ){
62437           sqlite3VdbeLeave(p);
62438           return SQLITE_BUSY;
62439         }else if( rc!=SQLITE_OK ){
62440           p->rc = rc;
62441           sqlite3RollbackAll(db, SQLITE_OK);
62442         }else{
62443           db->nDeferredCons = 0;
62444           sqlite3CommitInternalChanges(db);
62445         }
62446       }else{
62447         sqlite3RollbackAll(db, SQLITE_OK);
62448       }
62449       db->nStatement = 0;
62450     }else if( eStatementOp==0 ){
62451       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
62452         eStatementOp = SAVEPOINT_RELEASE;
62453       }else if( p->errorAction==OE_Abort ){
62454         eStatementOp = SAVEPOINT_ROLLBACK;
62455       }else{
62456         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62457         sqlite3CloseSavepoints(db);
62458         db->autoCommit = 1;
62459       }
62460     }
62461
62462     /* If eStatementOp is non-zero, then a statement transaction needs to
62463     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
62464     ** do so. If this operation returns an error, and the current statement
62465     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
62466     ** current statement error code.
62467     */
62468     if( eStatementOp ){
62469       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
62470       if( rc ){
62471         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
62472           p->rc = rc;
62473           sqlite3DbFree(db, p->zErrMsg);
62474           p->zErrMsg = 0;
62475         }
62476         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62477         sqlite3CloseSavepoints(db);
62478         db->autoCommit = 1;
62479       }
62480     }
62481
62482     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
62483     ** has been rolled back, update the database connection change-counter.
62484     */
62485     if( p->changeCntOn ){
62486       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
62487         sqlite3VdbeSetChanges(db, p->nChange);
62488       }else{
62489         sqlite3VdbeSetChanges(db, 0);
62490       }
62491       p->nChange = 0;
62492     }
62493
62494     /* Release the locks */
62495     sqlite3VdbeLeave(p);
62496   }
62497
62498   /* We have successfully halted and closed the VM.  Record this fact. */
62499   if( p->pc>=0 ){
62500     db->activeVdbeCnt--;
62501     if( !p->readOnly ){
62502       db->writeVdbeCnt--;
62503     }
62504     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
62505   }
62506   p->magic = VDBE_MAGIC_HALT;
62507   checkActiveVdbeCnt(db);
62508   if( p->db->mallocFailed ){
62509     p->rc = SQLITE_NOMEM;
62510   }
62511
62512   /* If the auto-commit flag is set to true, then any locks that were held
62513   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
62514   ** to invoke any required unlock-notify callbacks.
62515   */
62516   if( db->autoCommit ){
62517     sqlite3ConnectionUnlocked(db);
62518   }
62519
62520   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
62521   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
62522 }
62523
62524
62525 /*
62526 ** Each VDBE holds the result of the most recent sqlite3_step() call
62527 ** in p->rc.  This routine sets that result back to SQLITE_OK.
62528 */
62529 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
62530   p->rc = SQLITE_OK;
62531 }
62532
62533 /*
62534 ** Copy the error code and error message belonging to the VDBE passed
62535 ** as the first argument to its database handle (so that they will be
62536 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
62537 **
62538 ** This function does not clear the VDBE error code or message, just
62539 ** copies them to the database handle.
62540 */
62541 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
62542   sqlite3 *db = p->db;
62543   int rc = p->rc;
62544   if( p->zErrMsg ){
62545     u8 mallocFailed = db->mallocFailed;
62546     sqlite3BeginBenignMalloc();
62547     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62548     sqlite3EndBenignMalloc();
62549     db->mallocFailed = mallocFailed;
62550     db->errCode = rc;
62551   }else{
62552     sqlite3Error(db, rc, 0);
62553   }
62554   return rc;
62555 }
62556
62557 #ifdef SQLITE_ENABLE_SQLLOG
62558 /*
62559 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
62560 ** invoke it.
62561 */
62562 static void vdbeInvokeSqllog(Vdbe *v){
62563   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
62564     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
62565     assert( v->db->init.busy==0 );
62566     if( zExpanded ){
62567       sqlite3GlobalConfig.xSqllog(
62568           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
62569       );
62570       sqlite3DbFree(v->db, zExpanded);
62571     }
62572   }
62573 }
62574 #else
62575 # define vdbeInvokeSqllog(x)
62576 #endif
62577
62578 /*
62579 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
62580 ** Write any error messages into *pzErrMsg.  Return the result code.
62581 **
62582 ** After this routine is run, the VDBE should be ready to be executed
62583 ** again.
62584 **
62585 ** To look at it another way, this routine resets the state of the
62586 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
62587 ** VDBE_MAGIC_INIT.
62588 */
62589 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
62590   sqlite3 *db;
62591   db = p->db;
62592
62593   /* If the VM did not run to completion or if it encountered an
62594   ** error, then it might not have been halted properly.  So halt
62595   ** it now.
62596   */
62597   sqlite3VdbeHalt(p);
62598
62599   /* If the VDBE has be run even partially, then transfer the error code
62600   ** and error message from the VDBE into the main database structure.  But
62601   ** if the VDBE has just been set to run but has not actually executed any
62602   ** instructions yet, leave the main database error information unchanged.
62603   */
62604   if( p->pc>=0 ){
62605     vdbeInvokeSqllog(p);
62606     sqlite3VdbeTransferError(p);
62607     sqlite3DbFree(db, p->zErrMsg);
62608     p->zErrMsg = 0;
62609     if( p->runOnlyOnce ) p->expired = 1;
62610   }else if( p->rc && p->expired ){
62611     /* The expired flag was set on the VDBE before the first call
62612     ** to sqlite3_step(). For consistency (since sqlite3_step() was
62613     ** called), set the database error in this case as well.
62614     */
62615     sqlite3Error(db, p->rc, 0);
62616     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62617     sqlite3DbFree(db, p->zErrMsg);
62618     p->zErrMsg = 0;
62619   }
62620
62621   /* Reclaim all memory used by the VDBE
62622   */
62623   Cleanup(p);
62624
62625   /* Save profiling information from this VDBE run.
62626   */
62627 #ifdef VDBE_PROFILE
62628   {
62629     FILE *out = fopen("vdbe_profile.out", "a");
62630     if( out ){
62631       int i;
62632       fprintf(out, "---- ");
62633       for(i=0; i<p->nOp; i++){
62634         fprintf(out, "%02x", p->aOp[i].opcode);
62635       }
62636       fprintf(out, "\n");
62637       for(i=0; i<p->nOp; i++){
62638         fprintf(out, "%6d %10lld %8lld ",
62639            p->aOp[i].cnt,
62640            p->aOp[i].cycles,
62641            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
62642         );
62643         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
62644       }
62645       fclose(out);
62646     }
62647   }
62648 #endif
62649   p->magic = VDBE_MAGIC_INIT;
62650   return p->rc & db->errMask;
62651 }
62652
62653 /*
62654 ** Clean up and delete a VDBE after execution.  Return an integer which is
62655 ** the result code.  Write any error message text into *pzErrMsg.
62656 */
62657 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
62658   int rc = SQLITE_OK;
62659   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
62660     rc = sqlite3VdbeReset(p);
62661     assert( (rc & p->db->errMask)==rc );
62662   }
62663   sqlite3VdbeDelete(p);
62664   return rc;
62665 }
62666
62667 /*
62668 ** Call the destructor for each auxdata entry in pVdbeFunc for which
62669 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
62670 ** are always destroyed.  To destroy all auxdata entries, call this
62671 ** routine with mask==0.
62672 */
62673 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
62674   int i;
62675   for(i=0; i<pVdbeFunc->nAux; i++){
62676     struct AuxData *pAux = &pVdbeFunc->apAux[i];
62677     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
62678       if( pAux->xDelete ){
62679         pAux->xDelete(pAux->pAux);
62680       }
62681       pAux->pAux = 0;
62682     }
62683   }
62684 }
62685
62686 /*
62687 ** Free all memory associated with the Vdbe passed as the second argument,
62688 ** except for object itself, which is preserved.
62689 **
62690 ** The difference between this function and sqlite3VdbeDelete() is that
62691 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
62692 ** the database connection and frees the object itself.
62693 */
62694 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
62695   SubProgram *pSub, *pNext;
62696   int i;
62697   assert( p->db==0 || p->db==db );
62698   releaseMemArray(p->aVar, p->nVar);
62699   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62700   for(pSub=p->pProgram; pSub; pSub=pNext){
62701     pNext = pSub->pNext;
62702     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
62703     sqlite3DbFree(db, pSub);
62704   }
62705   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
62706   vdbeFreeOpArray(db, p->aOp, p->nOp);
62707   sqlite3DbFree(db, p->aLabel);
62708   sqlite3DbFree(db, p->aColName);
62709   sqlite3DbFree(db, p->zSql);
62710   sqlite3DbFree(db, p->pFree);
62711 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
62712   sqlite3_free(p->zExplain);
62713   sqlite3DbFree(db, p->pExplain);
62714 #endif
62715 }
62716
62717 /*
62718 ** Delete an entire VDBE.
62719 */
62720 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
62721   sqlite3 *db;
62722
62723   if( NEVER(p==0) ) return;
62724   db = p->db;
62725   assert( sqlite3_mutex_held(db->mutex) );
62726   sqlite3VdbeClearObject(db, p);
62727   if( p->pPrev ){
62728     p->pPrev->pNext = p->pNext;
62729   }else{
62730     assert( db->pVdbe==p );
62731     db->pVdbe = p->pNext;
62732   }
62733   if( p->pNext ){
62734     p->pNext->pPrev = p->pPrev;
62735   }
62736   p->magic = VDBE_MAGIC_DEAD;
62737   p->db = 0;
62738   sqlite3DbFree(db, p);
62739 }
62740
62741 /*
62742 ** Make sure the cursor p is ready to read or write the row to which it
62743 ** was last positioned.  Return an error code if an OOM fault or I/O error
62744 ** prevents us from positioning the cursor to its correct position.
62745 **
62746 ** If a MoveTo operation is pending on the given cursor, then do that
62747 ** MoveTo now.  If no move is pending, check to see if the row has been
62748 ** deleted out from under the cursor and if it has, mark the row as
62749 ** a NULL row.
62750 **
62751 ** If the cursor is already pointing to the correct row and that row has
62752 ** not been deleted out from under the cursor, then this routine is a no-op.
62753 */
62754 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
62755   if( p->deferredMoveto ){
62756     int res, rc;
62757 #ifdef SQLITE_TEST
62758     extern int sqlite3_search_count;
62759 #endif
62760     assert( p->isTable );
62761     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62762     if( rc ) return rc;
62763     p->lastRowid = p->movetoTarget;
62764     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
62765     p->rowidIsValid = 1;
62766 #ifdef SQLITE_TEST
62767     sqlite3_search_count++;
62768 #endif
62769     p->deferredMoveto = 0;
62770     p->cacheStatus = CACHE_STALE;
62771   }else if( ALWAYS(p->pCursor) ){
62772     int hasMoved;
62773     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62774     if( rc ) return rc;
62775     if( hasMoved ){
62776       p->cacheStatus = CACHE_STALE;
62777       p->nullRow = 1;
62778     }
62779   }
62780   return SQLITE_OK;
62781 }
62782
62783 /*
62784 ** The following functions:
62785 **
62786 ** sqlite3VdbeSerialType()
62787 ** sqlite3VdbeSerialTypeLen()
62788 ** sqlite3VdbeSerialLen()
62789 ** sqlite3VdbeSerialPut()
62790 ** sqlite3VdbeSerialGet()
62791 **
62792 ** encapsulate the code that serializes values for storage in SQLite
62793 ** data and index records. Each serialized value consists of a
62794 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62795 ** integer, stored as a varint.
62796 **
62797 ** In an SQLite index record, the serial type is stored directly before
62798 ** the blob of data that it corresponds to. In a table record, all serial
62799 ** types are stored at the start of the record, and the blobs of data at
62800 ** the end. Hence these functions allow the caller to handle the
62801 ** serial-type and data blob seperately.
62802 **
62803 ** The following table describes the various storage classes for data:
62804 **
62805 **   serial type        bytes of data      type
62806 **   --------------     ---------------    ---------------
62807 **      0                     0            NULL
62808 **      1                     1            signed integer
62809 **      2                     2            signed integer
62810 **      3                     3            signed integer
62811 **      4                     4            signed integer
62812 **      5                     6            signed integer
62813 **      6                     8            signed integer
62814 **      7                     8            IEEE float
62815 **      8                     0            Integer constant 0
62816 **      9                     0            Integer constant 1
62817 **     10,11                               reserved for expansion
62818 **    N>=12 and even       (N-12)/2        BLOB
62819 **    N>=13 and odd        (N-13)/2        text
62820 **
62821 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62822 ** of SQLite will not understand those serial types.
62823 */
62824
62825 /*
62826 ** Return the serial-type for the value stored in pMem.
62827 */
62828 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
62829   int flags = pMem->flags;
62830   int n;
62831
62832   if( flags&MEM_Null ){
62833     return 0;
62834   }
62835   if( flags&MEM_Int ){
62836     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62837 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62838     i64 i = pMem->u.i;
62839     u64 u;
62840     if( i<0 ){
62841       if( i<(-MAX_6BYTE) ) return 6;
62842       /* Previous test prevents:  u = -(-9223372036854775808) */
62843       u = -i;
62844     }else{
62845       u = i;
62846     }
62847     if( u<=127 ){
62848       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
62849     }
62850     if( u<=32767 ) return 2;
62851     if( u<=8388607 ) return 3;
62852     if( u<=2147483647 ) return 4;
62853     if( u<=MAX_6BYTE ) return 5;
62854     return 6;
62855   }
62856   if( flags&MEM_Real ){
62857     return 7;
62858   }
62859   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62860   n = pMem->n;
62861   if( flags & MEM_Zero ){
62862     n += pMem->u.nZero;
62863   }
62864   assert( n>=0 );
62865   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62866 }
62867
62868 /*
62869 ** Return the length of the data corresponding to the supplied serial-type.
62870 */
62871 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
62872   if( serial_type>=12 ){
62873     return (serial_type-12)/2;
62874   }else{
62875     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62876     return aSize[serial_type];
62877   }
62878 }
62879
62880 /*
62881 ** If we are on an architecture with mixed-endian floating
62882 ** points (ex: ARM7) then swap the lower 4 bytes with the
62883 ** upper 4 bytes.  Return the result.
62884 **
62885 ** For most architectures, this is a no-op.
62886 **
62887 ** (later):  It is reported to me that the mixed-endian problem
62888 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
62889 ** that early versions of GCC stored the two words of a 64-bit
62890 ** float in the wrong order.  And that error has been propagated
62891 ** ever since.  The blame is not necessarily with GCC, though.
62892 ** GCC might have just copying the problem from a prior compiler.
62893 ** I am also told that newer versions of GCC that follow a different
62894 ** ABI get the byte order right.
62895 **
62896 ** Developers using SQLite on an ARM7 should compile and run their
62897 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
62898 ** enabled, some asserts below will ensure that the byte order of
62899 ** floating point values is correct.
62900 **
62901 ** (2007-08-30)  Frank van Vugt has studied this problem closely
62902 ** and has send his findings to the SQLite developers.  Frank
62903 ** writes that some Linux kernels offer floating point hardware
62904 ** emulation that uses only 32-bit mantissas instead of a full
62905 ** 48-bits as required by the IEEE standard.  (This is the
62906 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
62907 ** byte swapping becomes very complicated.  To avoid problems,
62908 ** the necessary byte swapping is carried out using a 64-bit integer
62909 ** rather than a 64-bit float.  Frank assures us that the code here
62910 ** works for him.  We, the developers, have no way to independently
62911 ** verify this, but Frank seems to know what he is talking about
62912 ** so we trust him.
62913 */
62914 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
62915 static u64 floatSwap(u64 in){
62916   union {
62917     u64 r;
62918     u32 i[2];
62919   } u;
62920   u32 t;
62921
62922   u.r = in;
62923   t = u.i[0];
62924   u.i[0] = u.i[1];
62925   u.i[1] = t;
62926   return u.r;
62927 }
62928 # define swapMixedEndianFloat(X)  X = floatSwap(X)
62929 #else
62930 # define swapMixedEndianFloat(X)
62931 #endif
62932
62933 /*
62934 ** Write the serialized data blob for the value stored in pMem into
62935 ** buf. It is assumed that the caller has allocated sufficient space.
62936 ** Return the number of bytes written.
62937 **
62938 ** nBuf is the amount of space left in buf[].  nBuf must always be
62939 ** large enough to hold the entire field.  Except, if the field is
62940 ** a blob with a zero-filled tail, then buf[] might be just the right
62941 ** size to hold everything except for the zero-filled tail.  If buf[]
62942 ** is only big enough to hold the non-zero prefix, then only write that
62943 ** prefix into buf[].  But if buf[] is large enough to hold both the
62944 ** prefix and the tail then write the prefix and set the tail to all
62945 ** zeros.
62946 **
62947 ** Return the number of bytes actually written into buf[].  The number
62948 ** of bytes in the zero-filled tail is included in the return value only
62949 ** if those bytes were zeroed in buf[].
62950 */
62951 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62952   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
62953   u32 len;
62954
62955   /* Integer and Real */
62956   if( serial_type<=7 && serial_type>0 ){
62957     u64 v;
62958     u32 i;
62959     if( serial_type==7 ){
62960       assert( sizeof(v)==sizeof(pMem->r) );
62961       memcpy(&v, &pMem->r, sizeof(v));
62962       swapMixedEndianFloat(v);
62963     }else{
62964       v = pMem->u.i;
62965     }
62966     len = i = sqlite3VdbeSerialTypeLen(serial_type);
62967     assert( len<=(u32)nBuf );
62968     while( i-- ){
62969       buf[i] = (u8)(v&0xFF);
62970       v >>= 8;
62971     }
62972     return len;
62973   }
62974
62975   /* String or blob */
62976   if( serial_type>=12 ){
62977     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62978              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
62979     assert( pMem->n<=nBuf );
62980     len = pMem->n;
62981     memcpy(buf, pMem->z, len);
62982     if( pMem->flags & MEM_Zero ){
62983       len += pMem->u.nZero;
62984       assert( nBuf>=0 );
62985       if( len > (u32)nBuf ){
62986         len = (u32)nBuf;
62987       }
62988       memset(&buf[pMem->n], 0, len-pMem->n);
62989     }
62990     return len;
62991   }
62992
62993   /* NULL or constants 0 or 1 */
62994   return 0;
62995 }
62996
62997 /*
62998 ** Deserialize the data blob pointed to by buf as serial type serial_type
62999 ** and store the result in pMem.  Return the number of bytes read.
63000 */
63001 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
63002   const unsigned char *buf,     /* Buffer to deserialize from */
63003   u32 serial_type,              /* Serial type to deserialize */
63004   Mem *pMem                     /* Memory cell to write value into */
63005 ){
63006   switch( serial_type ){
63007     case 10:   /* Reserved for future use */
63008     case 11:   /* Reserved for future use */
63009     case 0: {  /* NULL */
63010       pMem->flags = MEM_Null;
63011       break;
63012     }
63013     case 1: { /* 1-byte signed integer */
63014       pMem->u.i = (signed char)buf[0];
63015       pMem->flags = MEM_Int;
63016       return 1;
63017     }
63018     case 2: { /* 2-byte signed integer */
63019       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
63020       pMem->flags = MEM_Int;
63021       return 2;
63022     }
63023     case 3: { /* 3-byte signed integer */
63024       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
63025       pMem->flags = MEM_Int;
63026       return 3;
63027     }
63028     case 4: { /* 4-byte signed integer */
63029       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
63030       pMem->flags = MEM_Int;
63031       return 4;
63032     }
63033     case 5: { /* 6-byte signed integer */
63034       u64 x = (((signed char)buf[0])<<8) | buf[1];
63035       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
63036       x = (x<<32) | y;
63037       pMem->u.i = *(i64*)&x;
63038       pMem->flags = MEM_Int;
63039       return 6;
63040     }
63041     case 6:   /* 8-byte signed integer */
63042     case 7: { /* IEEE floating point */
63043       u64 x;
63044       u32 y;
63045 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
63046       /* Verify that integers and floating point values use the same
63047       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
63048       ** defined that 64-bit floating point values really are mixed
63049       ** endian.
63050       */
63051       static const u64 t1 = ((u64)0x3ff00000)<<32;
63052       static const double r1 = 1.0;
63053       u64 t2 = t1;
63054       swapMixedEndianFloat(t2);
63055       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
63056 #endif
63057
63058       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
63059       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
63060       x = (x<<32) | y;
63061       if( serial_type==6 ){
63062         pMem->u.i = *(i64*)&x;
63063         pMem->flags = MEM_Int;
63064       }else{
63065         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
63066         swapMixedEndianFloat(x);
63067         memcpy(&pMem->r, &x, sizeof(x));
63068         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
63069       }
63070       return 8;
63071     }
63072     case 8:    /* Integer 0 */
63073     case 9: {  /* Integer 1 */
63074       pMem->u.i = serial_type-8;
63075       pMem->flags = MEM_Int;
63076       return 0;
63077     }
63078     default: {
63079       u32 len = (serial_type-12)/2;
63080       pMem->z = (char *)buf;
63081       pMem->n = len;
63082       pMem->xDel = 0;
63083       if( serial_type&0x01 ){
63084         pMem->flags = MEM_Str | MEM_Ephem;
63085       }else{
63086         pMem->flags = MEM_Blob | MEM_Ephem;
63087       }
63088       return len;
63089     }
63090   }
63091   return 0;
63092 }
63093
63094 /*
63095 ** This routine is used to allocate sufficient space for an UnpackedRecord
63096 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
63097 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
63098 **
63099 ** The space is either allocated using sqlite3DbMallocRaw() or from within
63100 ** the unaligned buffer passed via the second and third arguments (presumably
63101 ** stack space). If the former, then *ppFree is set to a pointer that should
63102 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
63103 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
63104 ** before returning.
63105 **
63106 ** If an OOM error occurs, NULL is returned.
63107 */
63108 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
63109   KeyInfo *pKeyInfo,              /* Description of the record */
63110   char *pSpace,                   /* Unaligned space available */
63111   int szSpace,                    /* Size of pSpace[] in bytes */
63112   char **ppFree                   /* OUT: Caller should free this pointer */
63113 ){
63114   UnpackedRecord *p;              /* Unpacked record to return */
63115   int nOff;                       /* Increment pSpace by nOff to align it */
63116   int nByte;                      /* Number of bytes required for *p */
63117
63118   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
63119   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
63120   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
63121   */
63122   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
63123   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
63124   if( nByte>szSpace+nOff ){
63125     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
63126     *ppFree = (char *)p;
63127     if( !p ) return 0;
63128   }else{
63129     p = (UnpackedRecord*)&pSpace[nOff];
63130     *ppFree = 0;
63131   }
63132
63133   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
63134   assert( pKeyInfo->aSortOrder!=0 );
63135   p->pKeyInfo = pKeyInfo;
63136   p->nField = pKeyInfo->nField + 1;
63137   return p;
63138 }
63139
63140 /*
63141 ** Given the nKey-byte encoding of a record in pKey[], populate the
63142 ** UnpackedRecord structure indicated by the fourth argument with the
63143 ** contents of the decoded record.
63144 */
63145 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
63146   KeyInfo *pKeyInfo,     /* Information about the record format */
63147   int nKey,              /* Size of the binary record */
63148   const void *pKey,      /* The binary record */
63149   UnpackedRecord *p      /* Populate this structure before returning. */
63150 ){
63151   const unsigned char *aKey = (const unsigned char *)pKey;
63152   int d;
63153   u32 idx;                        /* Offset in aKey[] to read from */
63154   u16 u;                          /* Unsigned loop counter */
63155   u32 szHdr;
63156   Mem *pMem = p->aMem;
63157
63158   p->flags = 0;
63159   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63160   idx = getVarint32(aKey, szHdr);
63161   d = szHdr;
63162   u = 0;
63163   while( idx<szHdr && u<p->nField && d<=nKey ){
63164     u32 serial_type;
63165
63166     idx += getVarint32(&aKey[idx], serial_type);
63167     pMem->enc = pKeyInfo->enc;
63168     pMem->db = pKeyInfo->db;
63169     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
63170     pMem->zMalloc = 0;
63171     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
63172     pMem++;
63173     u++;
63174   }
63175   assert( u<=pKeyInfo->nField + 1 );
63176   p->nField = u;
63177 }
63178
63179 /*
63180 ** This function compares the two table rows or index records
63181 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
63182 ** or positive integer if key1 is less than, equal to or
63183 ** greater than key2.  The {nKey1, pKey1} key must be a blob
63184 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
63185 ** key must be a parsed key such as obtained from
63186 ** sqlite3VdbeParseRecord.
63187 **
63188 ** Key1 and Key2 do not have to contain the same number of fields.
63189 ** The key with fewer fields is usually compares less than the
63190 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
63191 ** and the common prefixes are equal, then key1 is less than key2.
63192 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
63193 ** equal, then the keys are considered to be equal and
63194 ** the parts beyond the common prefix are ignored.
63195 */
63196 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
63197   int nKey1, const void *pKey1, /* Left key */
63198   UnpackedRecord *pPKey2        /* Right key */
63199 ){
63200   int d1;            /* Offset into aKey[] of next data element */
63201   u32 idx1;          /* Offset into aKey[] of next header element */
63202   u32 szHdr1;        /* Number of bytes in header */
63203   int i = 0;
63204   int nField;
63205   int rc = 0;
63206   const unsigned char *aKey1 = (const unsigned char *)pKey1;
63207   KeyInfo *pKeyInfo;
63208   Mem mem1;
63209
63210   pKeyInfo = pPKey2->pKeyInfo;
63211   mem1.enc = pKeyInfo->enc;
63212   mem1.db = pKeyInfo->db;
63213   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
63214   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
63215
63216   /* Compilers may complain that mem1.u.i is potentially uninitialized.
63217   ** We could initialize it, as shown here, to silence those complaints.
63218   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
63219   ** the unnecessary initialization has a measurable negative performance
63220   ** impact, since this routine is a very high runner.  And so, we choose
63221   ** to ignore the compiler warnings and leave this variable uninitialized.
63222   */
63223   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
63224
63225   idx1 = getVarint32(aKey1, szHdr1);
63226   d1 = szHdr1;
63227   nField = pKeyInfo->nField;
63228   assert( pKeyInfo->aSortOrder!=0 );
63229   while( idx1<szHdr1 && i<pPKey2->nField ){
63230     u32 serial_type1;
63231
63232     /* Read the serial types for the next element in each key. */
63233     idx1 += getVarint32( aKey1+idx1, serial_type1 );
63234     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
63235
63236     /* Extract the values to be compared.
63237     */
63238     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
63239
63240     /* Do the comparison
63241     */
63242     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
63243                            i<nField ? pKeyInfo->aColl[i] : 0);
63244     if( rc!=0 ){
63245       assert( mem1.zMalloc==0 );  /* See comment below */
63246
63247       /* Invert the result if we are using DESC sort order. */
63248       if( i<nField && pKeyInfo->aSortOrder[i] ){
63249         rc = -rc;
63250       }
63251
63252       /* If the PREFIX_SEARCH flag is set and all fields except the final
63253       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
63254       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
63255       ** This is used by the OP_IsUnique opcode.
63256       */
63257       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
63258         assert( idx1==szHdr1 && rc );
63259         assert( mem1.flags & MEM_Int );
63260         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
63261         pPKey2->rowid = mem1.u.i;
63262       }
63263
63264       return rc;
63265     }
63266     i++;
63267   }
63268
63269   /* No memory allocation is ever used on mem1.  Prove this using
63270   ** the following assert().  If the assert() fails, it indicates a
63271   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
63272   */
63273   assert( mem1.zMalloc==0 );
63274
63275   /* rc==0 here means that one of the keys ran out of fields and
63276   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
63277   ** flag is set, then break the tie by treating key2 as larger.
63278   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
63279   ** are considered to be equal.  Otherwise, the longer key is the
63280   ** larger.  As it happens, the pPKey2 will always be the longer
63281   ** if there is a difference.
63282   */
63283   assert( rc==0 );
63284   if( pPKey2->flags & UNPACKED_INCRKEY ){
63285     rc = -1;
63286   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
63287     /* Leave rc==0 */
63288   }else if( idx1<szHdr1 ){
63289     rc = 1;
63290   }
63291   return rc;
63292 }
63293
63294
63295 /*
63296 ** pCur points at an index entry created using the OP_MakeRecord opcode.
63297 ** Read the rowid (the last field in the record) and store it in *rowid.
63298 ** Return SQLITE_OK if everything works, or an error code otherwise.
63299 **
63300 ** pCur might be pointing to text obtained from a corrupt database file.
63301 ** So the content cannot be trusted.  Do appropriate checks on the content.
63302 */
63303 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
63304   i64 nCellKey = 0;
63305   int rc;
63306   u32 szHdr;        /* Size of the header */
63307   u32 typeRowid;    /* Serial type of the rowid */
63308   u32 lenRowid;     /* Size of the rowid */
63309   Mem m, v;
63310
63311   UNUSED_PARAMETER(db);
63312
63313   /* Get the size of the index entry.  Only indices entries of less
63314   ** than 2GiB are support - anything large must be database corruption.
63315   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
63316   ** this code can safely assume that nCellKey is 32-bits
63317   */
63318   assert( sqlite3BtreeCursorIsValid(pCur) );
63319   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63320   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
63321   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
63322
63323   /* Read in the complete content of the index entry */
63324   memset(&m, 0, sizeof(m));
63325   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
63326   if( rc ){
63327     return rc;
63328   }
63329
63330   /* The index entry must begin with a header size */
63331   (void)getVarint32((u8*)m.z, szHdr);
63332   testcase( szHdr==3 );
63333   testcase( szHdr==m.n );
63334   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
63335     goto idx_rowid_corruption;
63336   }
63337
63338   /* The last field of the index should be an integer - the ROWID.
63339   ** Verify that the last entry really is an integer. */
63340   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
63341   testcase( typeRowid==1 );
63342   testcase( typeRowid==2 );
63343   testcase( typeRowid==3 );
63344   testcase( typeRowid==4 );
63345   testcase( typeRowid==5 );
63346   testcase( typeRowid==6 );
63347   testcase( typeRowid==8 );
63348   testcase( typeRowid==9 );
63349   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
63350     goto idx_rowid_corruption;
63351   }
63352   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
63353   testcase( (u32)m.n==szHdr+lenRowid );
63354   if( unlikely((u32)m.n<szHdr+lenRowid) ){
63355     goto idx_rowid_corruption;
63356   }
63357
63358   /* Fetch the integer off the end of the index record */
63359   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
63360   *rowid = v.u.i;
63361   sqlite3VdbeMemRelease(&m);
63362   return SQLITE_OK;
63363
63364   /* Jump here if database corruption is detected after m has been
63365   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
63366 idx_rowid_corruption:
63367   testcase( m.zMalloc!=0 );
63368   sqlite3VdbeMemRelease(&m);
63369   return SQLITE_CORRUPT_BKPT;
63370 }
63371
63372 /*
63373 ** Compare the key of the index entry that cursor pC is pointing to against
63374 ** the key string in pUnpacked.  Write into *pRes a number
63375 ** that is negative, zero, or positive if pC is less than, equal to,
63376 ** or greater than pUnpacked.  Return SQLITE_OK on success.
63377 **
63378 ** pUnpacked is either created without a rowid or is truncated so that it
63379 ** omits the rowid at the end.  The rowid at the end of the index entry
63380 ** is ignored as well.  Hence, this routine only compares the prefixes
63381 ** of the keys prior to the final rowid, not the entire key.
63382 */
63383 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
63384   VdbeCursor *pC,             /* The cursor to compare against */
63385   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
63386   int *res                    /* Write the comparison result here */
63387 ){
63388   i64 nCellKey = 0;
63389   int rc;
63390   BtCursor *pCur = pC->pCursor;
63391   Mem m;
63392
63393   assert( sqlite3BtreeCursorIsValid(pCur) );
63394   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63395   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
63396   /* nCellKey will always be between 0 and 0xffffffff because of the say
63397   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
63398   if( nCellKey<=0 || nCellKey>0x7fffffff ){
63399     *res = 0;
63400     return SQLITE_CORRUPT_BKPT;
63401   }
63402   memset(&m, 0, sizeof(m));
63403   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
63404   if( rc ){
63405     return rc;
63406   }
63407   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
63408   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
63409   sqlite3VdbeMemRelease(&m);
63410   return SQLITE_OK;
63411 }
63412
63413 /*
63414 ** This routine sets the value to be returned by subsequent calls to
63415 ** sqlite3_changes() on the database handle 'db'.
63416 */
63417 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
63418   assert( sqlite3_mutex_held(db->mutex) );
63419   db->nChange = nChange;
63420   db->nTotalChange += nChange;
63421 }
63422
63423 /*
63424 ** Set a flag in the vdbe to update the change counter when it is finalised
63425 ** or reset.
63426 */
63427 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
63428   v->changeCntOn = 1;
63429 }
63430
63431 /*
63432 ** Mark every prepared statement associated with a database connection
63433 ** as expired.
63434 **
63435 ** An expired statement means that recompilation of the statement is
63436 ** recommend.  Statements expire when things happen that make their
63437 ** programs obsolete.  Removing user-defined functions or collating
63438 ** sequences, or changing an authorization function are the types of
63439 ** things that make prepared statements obsolete.
63440 */
63441 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
63442   Vdbe *p;
63443   for(p = db->pVdbe; p; p=p->pNext){
63444     p->expired = 1;
63445   }
63446 }
63447
63448 /*
63449 ** Return the database associated with the Vdbe.
63450 */
63451 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
63452   return v->db;
63453 }
63454
63455 /*
63456 ** Return a pointer to an sqlite3_value structure containing the value bound
63457 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
63458 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
63459 ** constants) to the value before returning it.
63460 **
63461 ** The returned value must be freed by the caller using sqlite3ValueFree().
63462 */
63463 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
63464   assert( iVar>0 );
63465   if( v ){
63466     Mem *pMem = &v->aVar[iVar-1];
63467     if( 0==(pMem->flags & MEM_Null) ){
63468       sqlite3_value *pRet = sqlite3ValueNew(v->db);
63469       if( pRet ){
63470         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
63471         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
63472         sqlite3VdbeMemStoreType((Mem *)pRet);
63473       }
63474       return pRet;
63475     }
63476   }
63477   return 0;
63478 }
63479
63480 /*
63481 ** Configure SQL variable iVar so that binding a new value to it signals
63482 ** to sqlite3_reoptimize() that re-preparing the statement may result
63483 ** in a better query plan.
63484 */
63485 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
63486   assert( iVar>0 );
63487   if( iVar>32 ){
63488     v->expmask = 0xffffffff;
63489   }else{
63490     v->expmask |= ((u32)1 << (iVar-1));
63491   }
63492 }
63493
63494 /************** End of vdbeaux.c *********************************************/
63495 /************** Begin file vdbeapi.c *****************************************/
63496 /*
63497 ** 2004 May 26
63498 **
63499 ** The author disclaims copyright to this source code.  In place of
63500 ** a legal notice, here is a blessing:
63501 **
63502 **    May you do good and not evil.
63503 **    May you find forgiveness for yourself and forgive others.
63504 **    May you share freely, never taking more than you give.
63505 **
63506 *************************************************************************
63507 **
63508 ** This file contains code use to implement APIs that are part of the
63509 ** VDBE.
63510 */
63511
63512 #ifndef SQLITE_OMIT_DEPRECATED
63513 /*
63514 ** Return TRUE (non-zero) of the statement supplied as an argument needs
63515 ** to be recompiled.  A statement needs to be recompiled whenever the
63516 ** execution environment changes in a way that would alter the program
63517 ** that sqlite3_prepare() generates.  For example, if new functions or
63518 ** collating sequences are registered or if an authorizer function is
63519 ** added or changed.
63520 */
63521 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
63522   Vdbe *p = (Vdbe*)pStmt;
63523   return p==0 || p->expired;
63524 }
63525 #endif
63526
63527 /*
63528 ** Check on a Vdbe to make sure it has not been finalized.  Log
63529 ** an error and return true if it has been finalized (or is otherwise
63530 ** invalid).  Return false if it is ok.
63531 */
63532 static int vdbeSafety(Vdbe *p){
63533   if( p->db==0 ){
63534     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
63535     return 1;
63536   }else{
63537     return 0;
63538   }
63539 }
63540 static int vdbeSafetyNotNull(Vdbe *p){
63541   if( p==0 ){
63542     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
63543     return 1;
63544   }else{
63545     return vdbeSafety(p);
63546   }
63547 }
63548
63549 /*
63550 ** The following routine destroys a virtual machine that is created by
63551 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
63552 ** success/failure code that describes the result of executing the virtual
63553 ** machine.
63554 **
63555 ** This routine sets the error code and string returned by
63556 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63557 */
63558 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
63559   int rc;
63560   if( pStmt==0 ){
63561     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
63562     ** pointer is a harmless no-op. */
63563     rc = SQLITE_OK;
63564   }else{
63565     Vdbe *v = (Vdbe*)pStmt;
63566     sqlite3 *db = v->db;
63567     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
63568     sqlite3_mutex_enter(db->mutex);
63569     rc = sqlite3VdbeFinalize(v);
63570     rc = sqlite3ApiExit(db, rc);
63571     sqlite3LeaveMutexAndCloseZombie(db);
63572   }
63573   return rc;
63574 }
63575
63576 /*
63577 ** Terminate the current execution of an SQL statement and reset it
63578 ** back to its starting state so that it can be reused. A success code from
63579 ** the prior execution is returned.
63580 **
63581 ** This routine sets the error code and string returned by
63582 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63583 */
63584 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
63585   int rc;
63586   if( pStmt==0 ){
63587     rc = SQLITE_OK;
63588   }else{
63589     Vdbe *v = (Vdbe*)pStmt;
63590     sqlite3_mutex_enter(v->db->mutex);
63591     rc = sqlite3VdbeReset(v);
63592     sqlite3VdbeRewind(v);
63593     assert( (rc & (v->db->errMask))==rc );
63594     rc = sqlite3ApiExit(v->db, rc);
63595     sqlite3_mutex_leave(v->db->mutex);
63596   }
63597   return rc;
63598 }
63599
63600 /*
63601 ** Set all the parameters in the compiled SQL statement to NULL.
63602 */
63603 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
63604   int i;
63605   int rc = SQLITE_OK;
63606   Vdbe *p = (Vdbe*)pStmt;
63607 #if SQLITE_THREADSAFE
63608   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
63609 #endif
63610   sqlite3_mutex_enter(mutex);
63611   for(i=0; i<p->nVar; i++){
63612     sqlite3VdbeMemRelease(&p->aVar[i]);
63613     p->aVar[i].flags = MEM_Null;
63614   }
63615   if( p->isPrepareV2 && p->expmask ){
63616     p->expired = 1;
63617   }
63618   sqlite3_mutex_leave(mutex);
63619   return rc;
63620 }
63621
63622
63623 /**************************** sqlite3_value_  *******************************
63624 ** The following routines extract information from a Mem or sqlite3_value
63625 ** structure.
63626 */
63627 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
63628   Mem *p = (Mem*)pVal;
63629   if( p->flags & (MEM_Blob|MEM_Str) ){
63630     sqlite3VdbeMemExpandBlob(p);
63631     p->flags &= ~MEM_Str;
63632     p->flags |= MEM_Blob;
63633     return p->n ? p->z : 0;
63634   }else{
63635     return sqlite3_value_text(pVal);
63636   }
63637 }
63638 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
63639   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
63640 }
63641 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
63642   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
63643 }
63644 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
63645   return sqlite3VdbeRealValue((Mem*)pVal);
63646 }
63647 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
63648   return (int)sqlite3VdbeIntValue((Mem*)pVal);
63649 }
63650 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
63651   return sqlite3VdbeIntValue((Mem*)pVal);
63652 }
63653 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
63654   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
63655 }
63656 #ifndef SQLITE_OMIT_UTF16
63657 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
63658   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
63659 }
63660 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
63661   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
63662 }
63663 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
63664   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
63665 }
63666 #endif /* SQLITE_OMIT_UTF16 */
63667 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
63668   return pVal->type;
63669 }
63670
63671 /**************************** sqlite3_result_  *******************************
63672 ** The following routines are used by user-defined functions to specify
63673 ** the function result.
63674 **
63675 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
63676 ** result as a string or blob but if the string or blob is too large, it
63677 ** then sets the error code to SQLITE_TOOBIG
63678 */
63679 static void setResultStrOrError(
63680   sqlite3_context *pCtx,  /* Function context */
63681   const char *z,          /* String pointer */
63682   int n,                  /* Bytes in string, or negative */
63683   u8 enc,                 /* Encoding of z.  0 for BLOBs */
63684   void (*xDel)(void*)     /* Destructor function */
63685 ){
63686   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
63687     sqlite3_result_error_toobig(pCtx);
63688   }
63689 }
63690 SQLITE_API void sqlite3_result_blob(
63691   sqlite3_context *pCtx,
63692   const void *z,
63693   int n,
63694   void (*xDel)(void *)
63695 ){
63696   assert( n>=0 );
63697   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63698   setResultStrOrError(pCtx, z, n, 0, xDel);
63699 }
63700 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
63701   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63702   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
63703 }
63704 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
63705   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63706   pCtx->isError = SQLITE_ERROR;
63707   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
63708 }
63709 #ifndef SQLITE_OMIT_UTF16
63710 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
63711   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63712   pCtx->isError = SQLITE_ERROR;
63713   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
63714 }
63715 #endif
63716 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
63717   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63718   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
63719 }
63720 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
63721   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63722   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
63723 }
63724 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
63725   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63726   sqlite3VdbeMemSetNull(&pCtx->s);
63727 }
63728 SQLITE_API void sqlite3_result_text(
63729   sqlite3_context *pCtx,
63730   const char *z,
63731   int n,
63732   void (*xDel)(void *)
63733 ){
63734   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63735   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
63736 }
63737 #ifndef SQLITE_OMIT_UTF16
63738 SQLITE_API void sqlite3_result_text16(
63739   sqlite3_context *pCtx,
63740   const void *z,
63741   int n,
63742   void (*xDel)(void *)
63743 ){
63744   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63745   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
63746 }
63747 SQLITE_API void sqlite3_result_text16be(
63748   sqlite3_context *pCtx,
63749   const void *z,
63750   int n,
63751   void (*xDel)(void *)
63752 ){
63753   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63754   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
63755 }
63756 SQLITE_API void sqlite3_result_text16le(
63757   sqlite3_context *pCtx,
63758   const void *z,
63759   int n,
63760   void (*xDel)(void *)
63761 ){
63762   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63763   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
63764 }
63765 #endif /* SQLITE_OMIT_UTF16 */
63766 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
63767   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63768   sqlite3VdbeMemCopy(&pCtx->s, pValue);
63769 }
63770 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
63771   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63772   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
63773 }
63774 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
63775   pCtx->isError = errCode;
63776   if( pCtx->s.flags & MEM_Null ){
63777     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
63778                          SQLITE_UTF8, SQLITE_STATIC);
63779   }
63780 }
63781
63782 /* Force an SQLITE_TOOBIG error. */
63783 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
63784   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63785   pCtx->isError = SQLITE_TOOBIG;
63786   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
63787                        SQLITE_UTF8, SQLITE_STATIC);
63788 }
63789
63790 /* An SQLITE_NOMEM error. */
63791 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
63792   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63793   sqlite3VdbeMemSetNull(&pCtx->s);
63794   pCtx->isError = SQLITE_NOMEM;
63795   pCtx->s.db->mallocFailed = 1;
63796 }
63797
63798 /*
63799 ** This function is called after a transaction has been committed. It
63800 ** invokes callbacks registered with sqlite3_wal_hook() as required.
63801 */
63802 static int doWalCallbacks(sqlite3 *db){
63803   int rc = SQLITE_OK;
63804 #ifndef SQLITE_OMIT_WAL
63805   int i;
63806   for(i=0; i<db->nDb; i++){
63807     Btree *pBt = db->aDb[i].pBt;
63808     if( pBt ){
63809       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
63810       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
63811         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63812       }
63813     }
63814   }
63815 #endif
63816   return rc;
63817 }
63818
63819 /*
63820 ** Execute the statement pStmt, either until a row of data is ready, the
63821 ** statement is completely executed or an error occurs.
63822 **
63823 ** This routine implements the bulk of the logic behind the sqlite_step()
63824 ** API.  The only thing omitted is the automatic recompile if a
63825 ** schema change has occurred.  That detail is handled by the
63826 ** outer sqlite3_step() wrapper procedure.
63827 */
63828 static int sqlite3Step(Vdbe *p){
63829   sqlite3 *db;
63830   int rc;
63831
63832   assert(p);
63833   if( p->magic!=VDBE_MAGIC_RUN ){
63834     /* We used to require that sqlite3_reset() be called before retrying
63835     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
63836     ** with version 3.7.0, we changed this so that sqlite3_reset() would
63837     ** be called automatically instead of throwing the SQLITE_MISUSE error.
63838     ** This "automatic-reset" change is not technically an incompatibility,
63839     ** since any application that receives an SQLITE_MISUSE is broken by
63840     ** definition.
63841     **
63842     ** Nevertheless, some published applications that were originally written
63843     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
63844     ** returns, and those were broken by the automatic-reset change.  As a
63845     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
63846     ** legacy behavior of returning SQLITE_MISUSE for cases where the
63847     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
63848     ** or SQLITE_BUSY error.
63849     */
63850 #ifdef SQLITE_OMIT_AUTORESET
63851     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
63852       sqlite3_reset((sqlite3_stmt*)p);
63853     }else{
63854       return SQLITE_MISUSE_BKPT;
63855     }
63856 #else
63857     sqlite3_reset((sqlite3_stmt*)p);
63858 #endif
63859   }
63860
63861   /* Check that malloc() has not failed. If it has, return early. */
63862   db = p->db;
63863   if( db->mallocFailed ){
63864     p->rc = SQLITE_NOMEM;
63865     return SQLITE_NOMEM;
63866   }
63867
63868   if( p->pc<=0 && p->expired ){
63869     p->rc = SQLITE_SCHEMA;
63870     rc = SQLITE_ERROR;
63871     goto end_of_step;
63872   }
63873   if( p->pc<0 ){
63874     /* If there are no other statements currently running, then
63875     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
63876     ** from interrupting a statement that has not yet started.
63877     */
63878     if( db->activeVdbeCnt==0 ){
63879       db->u1.isInterrupted = 0;
63880     }
63881
63882     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
63883
63884 #ifndef SQLITE_OMIT_TRACE
63885     if( db->xProfile && !db->init.busy ){
63886       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63887     }
63888 #endif
63889
63890     db->activeVdbeCnt++;
63891     if( p->readOnly==0 ) db->writeVdbeCnt++;
63892     p->pc = 0;
63893   }
63894 #ifndef SQLITE_OMIT_EXPLAIN
63895   if( p->explain ){
63896     rc = sqlite3VdbeList(p);
63897   }else
63898 #endif /* SQLITE_OMIT_EXPLAIN */
63899   {
63900     db->vdbeExecCnt++;
63901     rc = sqlite3VdbeExec(p);
63902     db->vdbeExecCnt--;
63903   }
63904
63905 #ifndef SQLITE_OMIT_TRACE
63906   /* Invoke the profile callback if there is one
63907   */
63908   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
63909     sqlite3_int64 iNow;
63910     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
63911     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63912   }
63913 #endif
63914
63915   if( rc==SQLITE_DONE ){
63916     assert( p->rc==SQLITE_OK );
63917     p->rc = doWalCallbacks(db);
63918     if( p->rc!=SQLITE_OK ){
63919       rc = SQLITE_ERROR;
63920     }
63921   }
63922
63923   db->errCode = rc;
63924   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
63925     p->rc = SQLITE_NOMEM;
63926   }
63927 end_of_step:
63928   /* At this point local variable rc holds the value that should be
63929   ** returned if this statement was compiled using the legacy
63930   ** sqlite3_prepare() interface. According to the docs, this can only
63931   ** be one of the values in the first assert() below. Variable p->rc
63932   ** contains the value that would be returned if sqlite3_finalize()
63933   ** were called on statement p.
63934   */
63935   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
63936        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
63937   );
63938   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
63939   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
63940     /* If this statement was prepared using sqlite3_prepare_v2(), and an
63941     ** error has occured, then return the error code in p->rc to the
63942     ** caller. Set the error code in the database handle to the same value.
63943     */
63944     rc = sqlite3VdbeTransferError(p);
63945   }
63946   return (rc&db->errMask);
63947 }
63948
63949 /*
63950 ** The maximum number of times that a statement will try to reparse
63951 ** itself before giving up and returning SQLITE_SCHEMA.
63952 */
63953 #ifndef SQLITE_MAX_SCHEMA_RETRY
63954 # define SQLITE_MAX_SCHEMA_RETRY 5
63955 #endif
63956
63957 /*
63958 ** This is the top-level implementation of sqlite3_step().  Call
63959 ** sqlite3Step() to do most of the work.  If a schema error occurs,
63960 ** call sqlite3Reprepare() and try again.
63961 */
63962 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
63963   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
63964   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
63965   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
63966   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
63967   sqlite3 *db;             /* The database connection */
63968
63969   if( vdbeSafetyNotNull(v) ){
63970     return SQLITE_MISUSE_BKPT;
63971   }
63972   db = v->db;
63973   sqlite3_mutex_enter(db->mutex);
63974   v->doingRerun = 0;
63975   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
63976          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
63977          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
63978     sqlite3_reset(pStmt);
63979     v->doingRerun = 1;
63980     assert( v->expired==0 );
63981   }
63982   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63983     /* This case occurs after failing to recompile an sql statement.
63984     ** The error message from the SQL compiler has already been loaded
63985     ** into the database handle. This block copies the error message
63986     ** from the database handle into the statement and sets the statement
63987     ** program counter to 0 to ensure that when the statement is
63988     ** finalized or reset the parser error message is available via
63989     ** sqlite3_errmsg() and sqlite3_errcode().
63990     */
63991     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
63992     sqlite3DbFree(db, v->zErrMsg);
63993     if( !db->mallocFailed ){
63994       v->zErrMsg = sqlite3DbStrDup(db, zErr);
63995       v->rc = rc2;
63996     } else {
63997       v->zErrMsg = 0;
63998       v->rc = rc = SQLITE_NOMEM;
63999     }
64000   }
64001   rc = sqlite3ApiExit(db, rc);
64002   sqlite3_mutex_leave(db->mutex);
64003   return rc;
64004 }
64005
64006 /*
64007 ** Extract the user data from a sqlite3_context structure and return a
64008 ** pointer to it.
64009 */
64010 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
64011   assert( p && p->pFunc );
64012   return p->pFunc->pUserData;
64013 }
64014
64015 /*
64016 ** Extract the user data from a sqlite3_context structure and return a
64017 ** pointer to it.
64018 **
64019 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
64020 ** returns a copy of the pointer to the database connection (the 1st
64021 ** parameter) of the sqlite3_create_function() and
64022 ** sqlite3_create_function16() routines that originally registered the
64023 ** application defined function.
64024 */
64025 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
64026   assert( p && p->pFunc );
64027   return p->s.db;
64028 }
64029
64030 /*
64031 ** The following is the implementation of an SQL function that always
64032 ** fails with an error message stating that the function is used in the
64033 ** wrong context.  The sqlite3_overload_function() API might construct
64034 ** SQL function that use this routine so that the functions will exist
64035 ** for name resolution but are actually overloaded by the xFindFunction
64036 ** method of virtual tables.
64037 */
64038 SQLITE_PRIVATE void sqlite3InvalidFunction(
64039   sqlite3_context *context,  /* The function calling context */
64040   int NotUsed,               /* Number of arguments to the function */
64041   sqlite3_value **NotUsed2   /* Value of each argument */
64042 ){
64043   const char *zName = context->pFunc->zName;
64044   char *zErr;
64045   UNUSED_PARAMETER2(NotUsed, NotUsed2);
64046   zErr = sqlite3_mprintf(
64047       "unable to use function %s in the requested context", zName);
64048   sqlite3_result_error(context, zErr, -1);
64049   sqlite3_free(zErr);
64050 }
64051
64052 /*
64053 ** Allocate or return the aggregate context for a user function.  A new
64054 ** context is allocated on the first call.  Subsequent calls return the
64055 ** same context that was returned on prior calls.
64056 */
64057 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
64058   Mem *pMem;
64059   assert( p && p->pFunc && p->pFunc->xStep );
64060   assert( sqlite3_mutex_held(p->s.db->mutex) );
64061   pMem = p->pMem;
64062   testcase( nByte<0 );
64063   if( (pMem->flags & MEM_Agg)==0 ){
64064     if( nByte<=0 ){
64065       sqlite3VdbeMemReleaseExternal(pMem);
64066       pMem->flags = MEM_Null;
64067       pMem->z = 0;
64068     }else{
64069       sqlite3VdbeMemGrow(pMem, nByte, 0);
64070       pMem->flags = MEM_Agg;
64071       pMem->u.pDef = p->pFunc;
64072       if( pMem->z ){
64073         memset(pMem->z, 0, nByte);
64074       }
64075     }
64076   }
64077   return (void*)pMem->z;
64078 }
64079
64080 /*
64081 ** Return the auxilary data pointer, if any, for the iArg'th argument to
64082 ** the user-function defined by pCtx.
64083 */
64084 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
64085   VdbeFunc *pVdbeFunc;
64086
64087   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64088   pVdbeFunc = pCtx->pVdbeFunc;
64089   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
64090     return 0;
64091   }
64092   return pVdbeFunc->apAux[iArg].pAux;
64093 }
64094
64095 /*
64096 ** Set the auxilary data pointer and delete function, for the iArg'th
64097 ** argument to the user-function defined by pCtx. Any previous value is
64098 ** deleted by calling the delete function specified when it was set.
64099 */
64100 SQLITE_API void sqlite3_set_auxdata(
64101   sqlite3_context *pCtx,
64102   int iArg,
64103   void *pAux,
64104   void (*xDelete)(void*)
64105 ){
64106   struct AuxData *pAuxData;
64107   VdbeFunc *pVdbeFunc;
64108   if( iArg<0 ) goto failed;
64109
64110   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64111   pVdbeFunc = pCtx->pVdbeFunc;
64112   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
64113     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
64114     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
64115     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
64116     if( !pVdbeFunc ){
64117       goto failed;
64118     }
64119     pCtx->pVdbeFunc = pVdbeFunc;
64120     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
64121     pVdbeFunc->nAux = iArg+1;
64122     pVdbeFunc->pFunc = pCtx->pFunc;
64123   }
64124
64125   pAuxData = &pVdbeFunc->apAux[iArg];
64126   if( pAuxData->pAux && pAuxData->xDelete ){
64127     pAuxData->xDelete(pAuxData->pAux);
64128   }
64129   pAuxData->pAux = pAux;
64130   pAuxData->xDelete = xDelete;
64131   return;
64132
64133 failed:
64134   if( xDelete ){
64135     xDelete(pAux);
64136   }
64137 }
64138
64139 #ifndef SQLITE_OMIT_DEPRECATED
64140 /*
64141 ** Return the number of times the Step function of a aggregate has been
64142 ** called.
64143 **
64144 ** This function is deprecated.  Do not use it for new code.  It is
64145 ** provide only to avoid breaking legacy code.  New aggregate function
64146 ** implementations should keep their own counts within their aggregate
64147 ** context.
64148 */
64149 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
64150   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
64151   return p->pMem->n;
64152 }
64153 #endif
64154
64155 /*
64156 ** Return the number of columns in the result set for the statement pStmt.
64157 */
64158 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
64159   Vdbe *pVm = (Vdbe *)pStmt;
64160   return pVm ? pVm->nResColumn : 0;
64161 }
64162
64163 /*
64164 ** Return the number of values available from the current row of the
64165 ** currently executing statement pStmt.
64166 */
64167 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
64168   Vdbe *pVm = (Vdbe *)pStmt;
64169   if( pVm==0 || pVm->pResultSet==0 ) return 0;
64170   return pVm->nResColumn;
64171 }
64172
64173
64174 /*
64175 ** Check to see if column iCol of the given statement is valid.  If
64176 ** it is, return a pointer to the Mem for the value of that column.
64177 ** If iCol is not valid, return a pointer to a Mem which has a value
64178 ** of NULL.
64179 */
64180 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
64181   Vdbe *pVm;
64182   Mem *pOut;
64183
64184   pVm = (Vdbe *)pStmt;
64185   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
64186     sqlite3_mutex_enter(pVm->db->mutex);
64187     pOut = &pVm->pResultSet[i];
64188   }else{
64189     /* If the value passed as the second argument is out of range, return
64190     ** a pointer to the following static Mem object which contains the
64191     ** value SQL NULL. Even though the Mem structure contains an element
64192     ** of type i64, on certain architectures (x86) with certain compiler
64193     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
64194     ** instead of an 8-byte one. This all works fine, except that when
64195     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
64196     ** that a Mem structure is located on an 8-byte boundary. To prevent
64197     ** these assert()s from failing, when building with SQLITE_DEBUG defined
64198     ** using gcc, we force nullMem to be 8-byte aligned using the magical
64199     ** __attribute__((aligned(8))) macro.  */
64200     static const Mem nullMem
64201 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
64202       __attribute__((aligned(8)))
64203 #endif
64204       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
64205 #ifdef SQLITE_DEBUG
64206          0, 0,  /* pScopyFrom, pFiller */
64207 #endif
64208          0, 0 };
64209
64210     if( pVm && ALWAYS(pVm->db) ){
64211       sqlite3_mutex_enter(pVm->db->mutex);
64212       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
64213     }
64214     pOut = (Mem*)&nullMem;
64215   }
64216   return pOut;
64217 }
64218
64219 /*
64220 ** This function is called after invoking an sqlite3_value_XXX function on a
64221 ** column value (i.e. a value returned by evaluating an SQL expression in the
64222 ** select list of a SELECT statement) that may cause a malloc() failure. If
64223 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
64224 ** code of statement pStmt set to SQLITE_NOMEM.
64225 **
64226 ** Specifically, this is called from within:
64227 **
64228 **     sqlite3_column_int()
64229 **     sqlite3_column_int64()
64230 **     sqlite3_column_text()
64231 **     sqlite3_column_text16()
64232 **     sqlite3_column_real()
64233 **     sqlite3_column_bytes()
64234 **     sqlite3_column_bytes16()
64235 **     sqiite3_column_blob()
64236 */
64237 static void columnMallocFailure(sqlite3_stmt *pStmt)
64238 {
64239   /* If malloc() failed during an encoding conversion within an
64240   ** sqlite3_column_XXX API, then set the return code of the statement to
64241   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
64242   ** and _finalize() will return NOMEM.
64243   */
64244   Vdbe *p = (Vdbe *)pStmt;
64245   if( p ){
64246     p->rc = sqlite3ApiExit(p->db, p->rc);
64247     sqlite3_mutex_leave(p->db->mutex);
64248   }
64249 }
64250
64251 /**************************** sqlite3_column_  *******************************
64252 ** The following routines are used to access elements of the current row
64253 ** in the result set.
64254 */
64255 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
64256   const void *val;
64257   val = sqlite3_value_blob( columnMem(pStmt,i) );
64258   /* Even though there is no encoding conversion, value_blob() might
64259   ** need to call malloc() to expand the result of a zeroblob()
64260   ** expression.
64261   */
64262   columnMallocFailure(pStmt);
64263   return val;
64264 }
64265 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
64266   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
64267   columnMallocFailure(pStmt);
64268   return val;
64269 }
64270 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
64271   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
64272   columnMallocFailure(pStmt);
64273   return val;
64274 }
64275 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
64276   double val = sqlite3_value_double( columnMem(pStmt,i) );
64277   columnMallocFailure(pStmt);
64278   return val;
64279 }
64280 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
64281   int val = sqlite3_value_int( columnMem(pStmt,i) );
64282   columnMallocFailure(pStmt);
64283   return val;
64284 }
64285 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
64286   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
64287   columnMallocFailure(pStmt);
64288   return val;
64289 }
64290 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
64291   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
64292   columnMallocFailure(pStmt);
64293   return val;
64294 }
64295 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
64296   Mem *pOut = columnMem(pStmt, i);
64297   if( pOut->flags&MEM_Static ){
64298     pOut->flags &= ~MEM_Static;
64299     pOut->flags |= MEM_Ephem;
64300   }
64301   columnMallocFailure(pStmt);
64302   return (sqlite3_value *)pOut;
64303 }
64304 #ifndef SQLITE_OMIT_UTF16
64305 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
64306   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
64307   columnMallocFailure(pStmt);
64308   return val;
64309 }
64310 #endif /* SQLITE_OMIT_UTF16 */
64311 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
64312   int iType = sqlite3_value_type( columnMem(pStmt,i) );
64313   columnMallocFailure(pStmt);
64314   return iType;
64315 }
64316
64317 /* The following function is experimental and subject to change or
64318 ** removal */
64319 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
64320 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
64321 **}
64322 */
64323
64324 /*
64325 ** Convert the N-th element of pStmt->pColName[] into a string using
64326 ** xFunc() then return that string.  If N is out of range, return 0.
64327 **
64328 ** There are up to 5 names for each column.  useType determines which
64329 ** name is returned.  Here are the names:
64330 **
64331 **    0      The column name as it should be displayed for output
64332 **    1      The datatype name for the column
64333 **    2      The name of the database that the column derives from
64334 **    3      The name of the table that the column derives from
64335 **    4      The name of the table column that the result column derives from
64336 **
64337 ** If the result is not a simple column reference (if it is an expression
64338 ** or a constant) then useTypes 2, 3, and 4 return NULL.
64339 */
64340 static const void *columnName(
64341   sqlite3_stmt *pStmt,
64342   int N,
64343   const void *(*xFunc)(Mem*),
64344   int useType
64345 ){
64346   const void *ret = 0;
64347   Vdbe *p = (Vdbe *)pStmt;
64348   int n;
64349   sqlite3 *db = p->db;
64350
64351   assert( db!=0 );
64352   n = sqlite3_column_count(pStmt);
64353   if( N<n && N>=0 ){
64354     N += useType*n;
64355     sqlite3_mutex_enter(db->mutex);
64356     assert( db->mallocFailed==0 );
64357     ret = xFunc(&p->aColName[N]);
64358      /* A malloc may have failed inside of the xFunc() call. If this
64359     ** is the case, clear the mallocFailed flag and return NULL.
64360     */
64361     if( db->mallocFailed ){
64362       db->mallocFailed = 0;
64363       ret = 0;
64364     }
64365     sqlite3_mutex_leave(db->mutex);
64366   }
64367   return ret;
64368 }
64369
64370 /*
64371 ** Return the name of the Nth column of the result set returned by SQL
64372 ** statement pStmt.
64373 */
64374 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
64375   return columnName(
64376       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
64377 }
64378 #ifndef SQLITE_OMIT_UTF16
64379 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
64380   return columnName(
64381       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
64382 }
64383 #endif
64384
64385 /*
64386 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
64387 ** not define OMIT_DECLTYPE.
64388 */
64389 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
64390 # error "Must not define both SQLITE_OMIT_DECLTYPE \
64391          and SQLITE_ENABLE_COLUMN_METADATA"
64392 #endif
64393
64394 #ifndef SQLITE_OMIT_DECLTYPE
64395 /*
64396 ** Return the column declaration type (if applicable) of the 'i'th column
64397 ** of the result set of SQL statement pStmt.
64398 */
64399 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
64400   return columnName(
64401       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
64402 }
64403 #ifndef SQLITE_OMIT_UTF16
64404 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
64405   return columnName(
64406       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
64407 }
64408 #endif /* SQLITE_OMIT_UTF16 */
64409 #endif /* SQLITE_OMIT_DECLTYPE */
64410
64411 #ifdef SQLITE_ENABLE_COLUMN_METADATA
64412 /*
64413 ** Return the name of the database from which a result column derives.
64414 ** NULL is returned if the result column is an expression or constant or
64415 ** anything else which is not an unabiguous reference to a database column.
64416 */
64417 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
64418   return columnName(
64419       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
64420 }
64421 #ifndef SQLITE_OMIT_UTF16
64422 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
64423   return columnName(
64424       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
64425 }
64426 #endif /* SQLITE_OMIT_UTF16 */
64427
64428 /*
64429 ** Return the name of the table from which a result column derives.
64430 ** NULL is returned if the result column is an expression or constant or
64431 ** anything else which is not an unabiguous reference to a database column.
64432 */
64433 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
64434   return columnName(
64435       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
64436 }
64437 #ifndef SQLITE_OMIT_UTF16
64438 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
64439   return columnName(
64440       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
64441 }
64442 #endif /* SQLITE_OMIT_UTF16 */
64443
64444 /*
64445 ** Return the name of the table column from which a result column derives.
64446 ** NULL is returned if the result column is an expression or constant or
64447 ** anything else which is not an unabiguous reference to a database column.
64448 */
64449 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
64450   return columnName(
64451       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
64452 }
64453 #ifndef SQLITE_OMIT_UTF16
64454 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
64455   return columnName(
64456       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
64457 }
64458 #endif /* SQLITE_OMIT_UTF16 */
64459 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
64460
64461
64462 /******************************* sqlite3_bind_  ***************************
64463 **
64464 ** Routines used to attach values to wildcards in a compiled SQL statement.
64465 */
64466 /*
64467 ** Unbind the value bound to variable i in virtual machine p. This is the
64468 ** the same as binding a NULL value to the column. If the "i" parameter is
64469 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
64470 **
64471 ** A successful evaluation of this routine acquires the mutex on p.
64472 ** the mutex is released if any kind of error occurs.
64473 **
64474 ** The error code stored in database p->db is overwritten with the return
64475 ** value in any case.
64476 */
64477 static int vdbeUnbind(Vdbe *p, int i){
64478   Mem *pVar;
64479   if( vdbeSafetyNotNull(p) ){
64480     return SQLITE_MISUSE_BKPT;
64481   }
64482   sqlite3_mutex_enter(p->db->mutex);
64483   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
64484     sqlite3Error(p->db, SQLITE_MISUSE, 0);
64485     sqlite3_mutex_leave(p->db->mutex);
64486     sqlite3_log(SQLITE_MISUSE,
64487         "bind on a busy prepared statement: [%s]", p->zSql);
64488     return SQLITE_MISUSE_BKPT;
64489   }
64490   if( i<1 || i>p->nVar ){
64491     sqlite3Error(p->db, SQLITE_RANGE, 0);
64492     sqlite3_mutex_leave(p->db->mutex);
64493     return SQLITE_RANGE;
64494   }
64495   i--;
64496   pVar = &p->aVar[i];
64497   sqlite3VdbeMemRelease(pVar);
64498   pVar->flags = MEM_Null;
64499   sqlite3Error(p->db, SQLITE_OK, 0);
64500
64501   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
64502   ** binding a new value to this variable invalidates the current query plan.
64503   **
64504   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
64505   ** parameter in the WHERE clause might influence the choice of query plan
64506   ** for a statement, then the statement will be automatically recompiled,
64507   ** as if there had been a schema change, on the first sqlite3_step() call
64508   ** following any change to the bindings of that parameter.
64509   */
64510   if( p->isPrepareV2 &&
64511      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
64512   ){
64513     p->expired = 1;
64514   }
64515   return SQLITE_OK;
64516 }
64517
64518 /*
64519 ** Bind a text or BLOB value.
64520 */
64521 static int bindText(
64522   sqlite3_stmt *pStmt,   /* The statement to bind against */
64523   int i,                 /* Index of the parameter to bind */
64524   const void *zData,     /* Pointer to the data to be bound */
64525   int nData,             /* Number of bytes of data to be bound */
64526   void (*xDel)(void*),   /* Destructor for the data */
64527   u8 encoding            /* Encoding for the data */
64528 ){
64529   Vdbe *p = (Vdbe *)pStmt;
64530   Mem *pVar;
64531   int rc;
64532
64533   rc = vdbeUnbind(p, i);
64534   if( rc==SQLITE_OK ){
64535     if( zData!=0 ){
64536       pVar = &p->aVar[i-1];
64537       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
64538       if( rc==SQLITE_OK && encoding!=0 ){
64539         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
64540       }
64541       sqlite3Error(p->db, rc, 0);
64542       rc = sqlite3ApiExit(p->db, rc);
64543     }
64544     sqlite3_mutex_leave(p->db->mutex);
64545   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
64546     xDel((void*)zData);
64547   }
64548   return rc;
64549 }
64550
64551
64552 /*
64553 ** Bind a blob value to an SQL statement variable.
64554 */
64555 SQLITE_API int sqlite3_bind_blob(
64556   sqlite3_stmt *pStmt,
64557   int i,
64558   const void *zData,
64559   int nData,
64560   void (*xDel)(void*)
64561 ){
64562   return bindText(pStmt, i, zData, nData, xDel, 0);
64563 }
64564 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
64565   int rc;
64566   Vdbe *p = (Vdbe *)pStmt;
64567   rc = vdbeUnbind(p, i);
64568   if( rc==SQLITE_OK ){
64569     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
64570     sqlite3_mutex_leave(p->db->mutex);
64571   }
64572   return rc;
64573 }
64574 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
64575   return sqlite3_bind_int64(p, i, (i64)iValue);
64576 }
64577 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
64578   int rc;
64579   Vdbe *p = (Vdbe *)pStmt;
64580   rc = vdbeUnbind(p, i);
64581   if( rc==SQLITE_OK ){
64582     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
64583     sqlite3_mutex_leave(p->db->mutex);
64584   }
64585   return rc;
64586 }
64587 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
64588   int rc;
64589   Vdbe *p = (Vdbe*)pStmt;
64590   rc = vdbeUnbind(p, i);
64591   if( rc==SQLITE_OK ){
64592     sqlite3_mutex_leave(p->db->mutex);
64593   }
64594   return rc;
64595 }
64596 SQLITE_API int sqlite3_bind_text(
64597   sqlite3_stmt *pStmt,
64598   int i,
64599   const char *zData,
64600   int nData,
64601   void (*xDel)(void*)
64602 ){
64603   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
64604 }
64605 #ifndef SQLITE_OMIT_UTF16
64606 SQLITE_API int sqlite3_bind_text16(
64607   sqlite3_stmt *pStmt,
64608   int i,
64609   const void *zData,
64610   int nData,
64611   void (*xDel)(void*)
64612 ){
64613   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
64614 }
64615 #endif /* SQLITE_OMIT_UTF16 */
64616 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
64617   int rc;
64618   switch( pValue->type ){
64619     case SQLITE_INTEGER: {
64620       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
64621       break;
64622     }
64623     case SQLITE_FLOAT: {
64624       rc = sqlite3_bind_double(pStmt, i, pValue->r);
64625       break;
64626     }
64627     case SQLITE_BLOB: {
64628       if( pValue->flags & MEM_Zero ){
64629         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
64630       }else{
64631         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
64632       }
64633       break;
64634     }
64635     case SQLITE_TEXT: {
64636       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
64637                               pValue->enc);
64638       break;
64639     }
64640     default: {
64641       rc = sqlite3_bind_null(pStmt, i);
64642       break;
64643     }
64644   }
64645   return rc;
64646 }
64647 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
64648   int rc;
64649   Vdbe *p = (Vdbe *)pStmt;
64650   rc = vdbeUnbind(p, i);
64651   if( rc==SQLITE_OK ){
64652     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
64653     sqlite3_mutex_leave(p->db->mutex);
64654   }
64655   return rc;
64656 }
64657
64658 /*
64659 ** Return the number of wildcards that can be potentially bound to.
64660 ** This routine is added to support DBD::SQLite.
64661 */
64662 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
64663   Vdbe *p = (Vdbe*)pStmt;
64664   return p ? p->nVar : 0;
64665 }
64666
64667 /*
64668 ** Return the name of a wildcard parameter.  Return NULL if the index
64669 ** is out of range or if the wildcard is unnamed.
64670 **
64671 ** The result is always UTF-8.
64672 */
64673 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
64674   Vdbe *p = (Vdbe*)pStmt;
64675   if( p==0 || i<1 || i>p->nzVar ){
64676     return 0;
64677   }
64678   return p->azVar[i-1];
64679 }
64680
64681 /*
64682 ** Given a wildcard parameter name, return the index of the variable
64683 ** with that name.  If there is no variable with the given name,
64684 ** return 0.
64685 */
64686 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
64687   int i;
64688   if( p==0 ){
64689     return 0;
64690   }
64691   if( zName ){
64692     for(i=0; i<p->nzVar; i++){
64693       const char *z = p->azVar[i];
64694       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
64695         return i+1;
64696       }
64697     }
64698   }
64699   return 0;
64700 }
64701 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
64702   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
64703 }
64704
64705 /*
64706 ** Transfer all bindings from the first statement over to the second.
64707 */
64708 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64709   Vdbe *pFrom = (Vdbe*)pFromStmt;
64710   Vdbe *pTo = (Vdbe*)pToStmt;
64711   int i;
64712   assert( pTo->db==pFrom->db );
64713   assert( pTo->nVar==pFrom->nVar );
64714   sqlite3_mutex_enter(pTo->db->mutex);
64715   for(i=0; i<pFrom->nVar; i++){
64716     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
64717   }
64718   sqlite3_mutex_leave(pTo->db->mutex);
64719   return SQLITE_OK;
64720 }
64721
64722 #ifndef SQLITE_OMIT_DEPRECATED
64723 /*
64724 ** Deprecated external interface.  Internal/core SQLite code
64725 ** should call sqlite3TransferBindings.
64726 **
64727 ** Is is misuse to call this routine with statements from different
64728 ** database connections.  But as this is a deprecated interface, we
64729 ** will not bother to check for that condition.
64730 **
64731 ** If the two statements contain a different number of bindings, then
64732 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
64733 ** SQLITE_OK is returned.
64734 */
64735 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64736   Vdbe *pFrom = (Vdbe*)pFromStmt;
64737   Vdbe *pTo = (Vdbe*)pToStmt;
64738   if( pFrom->nVar!=pTo->nVar ){
64739     return SQLITE_ERROR;
64740   }
64741   if( pTo->isPrepareV2 && pTo->expmask ){
64742     pTo->expired = 1;
64743   }
64744   if( pFrom->isPrepareV2 && pFrom->expmask ){
64745     pFrom->expired = 1;
64746   }
64747   return sqlite3TransferBindings(pFromStmt, pToStmt);
64748 }
64749 #endif
64750
64751 /*
64752 ** Return the sqlite3* database handle to which the prepared statement given
64753 ** in the argument belongs.  This is the same database handle that was
64754 ** the first argument to the sqlite3_prepare() that was used to create
64755 ** the statement in the first place.
64756 */
64757 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
64758   return pStmt ? ((Vdbe*)pStmt)->db : 0;
64759 }
64760
64761 /*
64762 ** Return true if the prepared statement is guaranteed to not modify the
64763 ** database.
64764 */
64765 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
64766   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64767 }
64768
64769 /*
64770 ** Return true if the prepared statement is in need of being reset.
64771 */
64772 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
64773   Vdbe *v = (Vdbe*)pStmt;
64774   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
64775 }
64776
64777 /*
64778 ** Return a pointer to the next prepared statement after pStmt associated
64779 ** with database connection pDb.  If pStmt is NULL, return the first
64780 ** prepared statement for the database connection.  Return NULL if there
64781 ** are no more.
64782 */
64783 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
64784   sqlite3_stmt *pNext;
64785   sqlite3_mutex_enter(pDb->mutex);
64786   if( pStmt==0 ){
64787     pNext = (sqlite3_stmt*)pDb->pVdbe;
64788   }else{
64789     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
64790   }
64791   sqlite3_mutex_leave(pDb->mutex);
64792   return pNext;
64793 }
64794
64795 /*
64796 ** Return the value of a status counter for a prepared statement
64797 */
64798 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
64799   Vdbe *pVdbe = (Vdbe*)pStmt;
64800   int v = pVdbe->aCounter[op-1];
64801   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64802   return v;
64803 }
64804
64805 /************** End of vdbeapi.c *********************************************/
64806 /************** Begin file vdbetrace.c ***************************************/
64807 /*
64808 ** 2009 November 25
64809 **
64810 ** The author disclaims copyright to this source code.  In place of
64811 ** a legal notice, here is a blessing:
64812 **
64813 **    May you do good and not evil.
64814 **    May you find forgiveness for yourself and forgive others.
64815 **    May you share freely, never taking more than you give.
64816 **
64817 *************************************************************************
64818 **
64819 ** This file contains code used to insert the values of host parameters
64820 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
64821 **
64822 ** The Vdbe parse-tree explainer is also found here.
64823 */
64824
64825 #ifndef SQLITE_OMIT_TRACE
64826
64827 /*
64828 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64829 ** bytes in this text up to but excluding the first character in
64830 ** a host parameter.  If the text contains no host parameters, return
64831 ** the total number of bytes in the text.
64832 */
64833 static int findNextHostParameter(const char *zSql, int *pnToken){
64834   int tokenType;
64835   int nTotal = 0;
64836   int n;
64837
64838   *pnToken = 0;
64839   while( zSql[0] ){
64840     n = sqlite3GetToken((u8*)zSql, &tokenType);
64841     assert( n>0 && tokenType!=TK_ILLEGAL );
64842     if( tokenType==TK_VARIABLE ){
64843       *pnToken = n;
64844       break;
64845     }
64846     nTotal += n;
64847     zSql += n;
64848   }
64849   return nTotal;
64850 }
64851
64852 /*
64853 ** This function returns a pointer to a nul-terminated string in memory
64854 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
64855 ** string contains a copy of zRawSql but with host parameters expanded to
64856 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
64857 ** then the returned string holds a copy of zRawSql with "-- " prepended
64858 ** to each line of text.
64859 **
64860 ** The calling function is responsible for making sure the memory returned
64861 ** is eventually freed.
64862 **
64863 ** ALGORITHM:  Scan the input string looking for host parameters in any of
64864 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
64865 ** string literals, quoted identifier names, and comments.  For text forms,
64866 ** the host parameter index is found by scanning the perpared
64867 ** statement for the corresponding OP_Variable opcode.  Once the host
64868 ** parameter index is known, locate the value in p->aVar[].  Then render
64869 ** the value as a literal in place of the host parameter name.
64870 */
64871 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
64872   Vdbe *p,                 /* The prepared statement being evaluated */
64873   const char *zRawSql      /* Raw text of the SQL statement */
64874 ){
64875   sqlite3 *db;             /* The database connection */
64876   int idx = 0;             /* Index of a host parameter */
64877   int nextIndex = 1;       /* Index of next ? host parameter */
64878   int n;                   /* Length of a token prefix */
64879   int nToken;              /* Length of the parameter token */
64880   int i;                   /* Loop counter */
64881   Mem *pVar;               /* Value of a host parameter */
64882   StrAccum out;            /* Accumulate the output here */
64883   char zBase[100];         /* Initial working space */
64884
64885   db = p->db;
64886   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
64887                       db->aLimit[SQLITE_LIMIT_LENGTH]);
64888   out.db = db;
64889   if( db->vdbeExecCnt>1 ){
64890     while( *zRawSql ){
64891       const char *zStart = zRawSql;
64892       while( *(zRawSql++)!='\n' && *zRawSql );
64893       sqlite3StrAccumAppend(&out, "-- ", 3);
64894       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64895     }
64896   }else{
64897     while( zRawSql[0] ){
64898       n = findNextHostParameter(zRawSql, &nToken);
64899       assert( n>0 );
64900       sqlite3StrAccumAppend(&out, zRawSql, n);
64901       zRawSql += n;
64902       assert( zRawSql[0] || nToken==0 );
64903       if( nToken==0 ) break;
64904       if( zRawSql[0]=='?' ){
64905         if( nToken>1 ){
64906           assert( sqlite3Isdigit(zRawSql[1]) );
64907           sqlite3GetInt32(&zRawSql[1], &idx);
64908         }else{
64909           idx = nextIndex;
64910         }
64911       }else{
64912         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64913         testcase( zRawSql[0]==':' );
64914         testcase( zRawSql[0]=='$' );
64915         testcase( zRawSql[0]=='@' );
64916         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
64917         assert( idx>0 );
64918       }
64919       zRawSql += nToken;
64920       nextIndex = idx + 1;
64921       assert( idx>0 && idx<=p->nVar );
64922       pVar = &p->aVar[idx-1];
64923       if( pVar->flags & MEM_Null ){
64924         sqlite3StrAccumAppend(&out, "NULL", 4);
64925       }else if( pVar->flags & MEM_Int ){
64926         sqlite3XPrintf(&out, "%lld", pVar->u.i);
64927       }else if( pVar->flags & MEM_Real ){
64928         sqlite3XPrintf(&out, "%!.15g", pVar->r);
64929       }else if( pVar->flags & MEM_Str ){
64930 #ifndef SQLITE_OMIT_UTF16
64931         u8 enc = ENC(db);
64932         if( enc!=SQLITE_UTF8 ){
64933           Mem utf8;
64934           memset(&utf8, 0, sizeof(utf8));
64935           utf8.db = db;
64936           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
64937           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
64938           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
64939           sqlite3VdbeMemRelease(&utf8);
64940         }else
64941 #endif
64942         {
64943           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
64944         }
64945       }else if( pVar->flags & MEM_Zero ){
64946         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64947       }else{
64948         assert( pVar->flags & MEM_Blob );
64949         sqlite3StrAccumAppend(&out, "x'", 2);
64950         for(i=0; i<pVar->n; i++){
64951           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64952         }
64953         sqlite3StrAccumAppend(&out, "'", 1);
64954       }
64955     }
64956   }
64957   return sqlite3StrAccumFinish(&out);
64958 }
64959
64960 #endif /* #ifndef SQLITE_OMIT_TRACE */
64961
64962 /*****************************************************************************
64963 ** The following code implements the data-structure explaining logic
64964 ** for the Vdbe.
64965 */
64966
64967 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
64968
64969 /*
64970 ** Allocate a new Explain object
64971 */
64972 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
64973   if( pVdbe ){
64974     Explain *p;
64975     sqlite3BeginBenignMalloc();
64976     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
64977     if( p ){
64978       p->pVdbe = pVdbe;
64979       sqlite3_free(pVdbe->pExplain);
64980       pVdbe->pExplain = p;
64981       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
64982                           SQLITE_MAX_LENGTH);
64983       p->str.useMalloc = 2;
64984     }else{
64985       sqlite3EndBenignMalloc();
64986     }
64987   }
64988 }
64989
64990 /*
64991 ** Return true if the Explain ends with a new-line.
64992 */
64993 static int endsWithNL(Explain *p){
64994   return p && p->str.zText && p->str.nChar
64995            && p->str.zText[p->str.nChar-1]=='\n';
64996 }
64997
64998 /*
64999 ** Append text to the indentation
65000 */
65001 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
65002   Explain *p;
65003   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
65004     va_list ap;
65005     if( p->nIndent && endsWithNL(p) ){
65006       int n = p->nIndent;
65007       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
65008       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
65009     }
65010     va_start(ap, zFormat);
65011     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
65012     va_end(ap);
65013   }
65014 }
65015
65016 /*
65017 ** Append a '\n' if there is not already one.
65018 */
65019 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
65020   Explain *p;
65021   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
65022     sqlite3StrAccumAppend(&p->str, "\n", 1);
65023   }
65024 }
65025
65026 /*
65027 ** Push a new indentation level.  Subsequent lines will be indented
65028 ** so that they begin at the current cursor position.
65029 */
65030 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
65031   Explain *p;
65032   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
65033     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
65034       const char *z = p->str.zText;
65035       int i = p->str.nChar-1;
65036       int x;
65037       while( i>=0 && z[i]!='\n' ){ i--; }
65038       x = (p->str.nChar - 1) - i;
65039       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
65040         x = p->aIndent[p->nIndent-1];
65041       }
65042       p->aIndent[p->nIndent] = x;
65043     }
65044     p->nIndent++;
65045   }
65046 }
65047
65048 /*
65049 ** Pop the indentation stack by one level.
65050 */
65051 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
65052   if( p && p->pExplain ) p->pExplain->nIndent--;
65053 }
65054
65055 /*
65056 ** Free the indentation structure
65057 */
65058 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
65059   if( pVdbe && pVdbe->pExplain ){
65060     sqlite3_free(pVdbe->zExplain);
65061     sqlite3ExplainNL(pVdbe);
65062     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
65063     sqlite3_free(pVdbe->pExplain);
65064     pVdbe->pExplain = 0;
65065     sqlite3EndBenignMalloc();
65066   }
65067 }
65068
65069 /*
65070 ** Return the explanation of a virtual machine.
65071 */
65072 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
65073   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
65074 }
65075 #endif /* defined(SQLITE_DEBUG) */
65076
65077 /************** End of vdbetrace.c *******************************************/
65078 /************** Begin file vdbe.c ********************************************/
65079 /*
65080 ** 2001 September 15
65081 **
65082 ** The author disclaims copyright to this source code.  In place of
65083 ** a legal notice, here is a blessing:
65084 **
65085 **    May you do good and not evil.
65086 **    May you find forgiveness for yourself and forgive others.
65087 **    May you share freely, never taking more than you give.
65088 **
65089 *************************************************************************
65090 ** The code in this file implements execution method of the
65091 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
65092 ** handles housekeeping details such as creating and deleting
65093 ** VDBE instances.  This file is solely interested in executing
65094 ** the VDBE program.
65095 **
65096 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
65097 ** to a VDBE.
65098 **
65099 ** The SQL parser generates a program which is then executed by
65100 ** the VDBE to do the work of the SQL statement.  VDBE programs are
65101 ** similar in form to assembly language.  The program consists of
65102 ** a linear sequence of operations.  Each operation has an opcode
65103 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
65104 ** is a null-terminated string.  Operand P5 is an unsigned character.
65105 ** Few opcodes use all 5 operands.
65106 **
65107 ** Computation results are stored on a set of registers numbered beginning
65108 ** with 1 and going up to Vdbe.nMem.  Each register can store
65109 ** either an integer, a null-terminated string, a floating point
65110 ** number, or the SQL "NULL" value.  An implicit conversion from one
65111 ** type to the other occurs as necessary.
65112 **
65113 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
65114 ** function which does the work of interpreting a VDBE program.
65115 ** But other routines are also provided to help in building up
65116 ** a program instruction by instruction.
65117 **
65118 ** Various scripts scan this source file in order to generate HTML
65119 ** documentation, headers files, or other derived files.  The formatting
65120 ** of the code in this file is, therefore, important.  See other comments
65121 ** in this file for details.  If in doubt, do not deviate from existing
65122 ** commenting and indentation practices when changing or adding code.
65123 */
65124
65125 /*
65126 ** Invoke this macro on memory cells just prior to changing the
65127 ** value of the cell.  This macro verifies that shallow copies are
65128 ** not misused.
65129 */
65130 #ifdef SQLITE_DEBUG
65131 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
65132 #else
65133 # define memAboutToChange(P,M)
65134 #endif
65135
65136 /*
65137 ** The following global variable is incremented every time a cursor
65138 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
65139 ** procedures use this information to make sure that indices are
65140 ** working correctly.  This variable has no function other than to
65141 ** help verify the correct operation of the library.
65142 */
65143 #ifdef SQLITE_TEST
65144 SQLITE_API int sqlite3_search_count = 0;
65145 #endif
65146
65147 /*
65148 ** When this global variable is positive, it gets decremented once before
65149 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
65150 ** field of the sqlite3 structure is set in order to simulate an interrupt.
65151 **
65152 ** This facility is used for testing purposes only.  It does not function
65153 ** in an ordinary build.
65154 */
65155 #ifdef SQLITE_TEST
65156 SQLITE_API int sqlite3_interrupt_count = 0;
65157 #endif
65158
65159 /*
65160 ** The next global variable is incremented each type the OP_Sort opcode
65161 ** is executed.  The test procedures use this information to make sure that
65162 ** sorting is occurring or not occurring at appropriate times.   This variable
65163 ** has no function other than to help verify the correct operation of the
65164 ** library.
65165 */
65166 #ifdef SQLITE_TEST
65167 SQLITE_API int sqlite3_sort_count = 0;
65168 #endif
65169
65170 /*
65171 ** The next global variable records the size of the largest MEM_Blob
65172 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
65173 ** use this information to make sure that the zero-blob functionality
65174 ** is working correctly.   This variable has no function other than to
65175 ** help verify the correct operation of the library.
65176 */
65177 #ifdef SQLITE_TEST
65178 SQLITE_API int sqlite3_max_blobsize = 0;
65179 static void updateMaxBlobsize(Mem *p){
65180   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
65181     sqlite3_max_blobsize = p->n;
65182   }
65183 }
65184 #endif
65185
65186 /*
65187 ** The next global variable is incremented each type the OP_Found opcode
65188 ** is executed. This is used to test whether or not the foreign key
65189 ** operation implemented using OP_FkIsZero is working. This variable
65190 ** has no function other than to help verify the correct operation of the
65191 ** library.
65192 */
65193 #ifdef SQLITE_TEST
65194 SQLITE_API int sqlite3_found_count = 0;
65195 #endif
65196
65197 /*
65198 ** Test a register to see if it exceeds the current maximum blob size.
65199 ** If it does, record the new maximum blob size.
65200 */
65201 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
65202 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
65203 #else
65204 # define UPDATE_MAX_BLOBSIZE(P)
65205 #endif
65206
65207 /*
65208 ** Convert the given register into a string if it isn't one
65209 ** already. Return non-zero if a malloc() fails.
65210 */
65211 #define Stringify(P, enc) \
65212    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
65213      { goto no_mem; }
65214
65215 /*
65216 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
65217 ** a pointer to a dynamically allocated string where some other entity
65218 ** is responsible for deallocating that string.  Because the register
65219 ** does not control the string, it might be deleted without the register
65220 ** knowing it.
65221 **
65222 ** This routine converts an ephemeral string into a dynamically allocated
65223 ** string that the register itself controls.  In other words, it
65224 ** converts an MEM_Ephem string into an MEM_Dyn string.
65225 */
65226 #define Deephemeralize(P) \
65227    if( ((P)->flags&MEM_Ephem)!=0 \
65228        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
65229
65230 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
65231 #ifdef SQLITE_OMIT_MERGE_SORT
65232 # define isSorter(x) 0
65233 #else
65234 # define isSorter(x) ((x)->pSorter!=0)
65235 #endif
65236
65237 /*
65238 ** Argument pMem points at a register that will be passed to a
65239 ** user-defined function or returned to the user as the result of a query.
65240 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
65241 ** routines.
65242 */
65243 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
65244   int flags = pMem->flags;
65245   if( flags & MEM_Null ){
65246     pMem->type = SQLITE_NULL;
65247   }
65248   else if( flags & MEM_Int ){
65249     pMem->type = SQLITE_INTEGER;
65250   }
65251   else if( flags & MEM_Real ){
65252     pMem->type = SQLITE_FLOAT;
65253   }
65254   else if( flags & MEM_Str ){
65255     pMem->type = SQLITE_TEXT;
65256   }else{
65257     pMem->type = SQLITE_BLOB;
65258   }
65259 }
65260
65261 /*
65262 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
65263 ** if we run out of memory.
65264 */
65265 static VdbeCursor *allocateCursor(
65266   Vdbe *p,              /* The virtual machine */
65267   int iCur,             /* Index of the new VdbeCursor */
65268   int nField,           /* Number of fields in the table or index */
65269   int iDb,              /* Database the cursor belongs to, or -1 */
65270   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
65271 ){
65272   /* Find the memory cell that will be used to store the blob of memory
65273   ** required for this VdbeCursor structure. It is convenient to use a
65274   ** vdbe memory cell to manage the memory allocation required for a
65275   ** VdbeCursor structure for the following reasons:
65276   **
65277   **   * Sometimes cursor numbers are used for a couple of different
65278   **     purposes in a vdbe program. The different uses might require
65279   **     different sized allocations. Memory cells provide growable
65280   **     allocations.
65281   **
65282   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
65283   **     be freed lazily via the sqlite3_release_memory() API. This
65284   **     minimizes the number of malloc calls made by the system.
65285   **
65286   ** Memory cells for cursors are allocated at the top of the address
65287   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
65288   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
65289   */
65290   Mem *pMem = &p->aMem[p->nMem-iCur];
65291
65292   int nByte;
65293   VdbeCursor *pCx = 0;
65294   nByte =
65295       ROUND8(sizeof(VdbeCursor)) +
65296       (isBtreeCursor?sqlite3BtreeCursorSize():0) +
65297       2*nField*sizeof(u32);
65298
65299   assert( iCur<p->nCursor );
65300   if( p->apCsr[iCur] ){
65301     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
65302     p->apCsr[iCur] = 0;
65303   }
65304   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
65305     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
65306     memset(pCx, 0, sizeof(VdbeCursor));
65307     pCx->iDb = iDb;
65308     pCx->nField = nField;
65309     if( nField ){
65310       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
65311     }
65312     if( isBtreeCursor ){
65313       pCx->pCursor = (BtCursor*)
65314           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
65315       sqlite3BtreeCursorZero(pCx->pCursor);
65316     }
65317   }
65318   return pCx;
65319 }
65320
65321 /*
65322 ** Try to convert a value into a numeric representation if we can
65323 ** do so without loss of information.  In other words, if the string
65324 ** looks like a number, convert it into a number.  If it does not
65325 ** look like a number, leave it alone.
65326 */
65327 static void applyNumericAffinity(Mem *pRec){
65328   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
65329     double rValue;
65330     i64 iValue;
65331     u8 enc = pRec->enc;
65332     if( (pRec->flags&MEM_Str)==0 ) return;
65333     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
65334     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
65335       pRec->u.i = iValue;
65336       pRec->flags |= MEM_Int;
65337     }else{
65338       pRec->r = rValue;
65339       pRec->flags |= MEM_Real;
65340     }
65341   }
65342 }
65343
65344 /*
65345 ** Processing is determine by the affinity parameter:
65346 **
65347 ** SQLITE_AFF_INTEGER:
65348 ** SQLITE_AFF_REAL:
65349 ** SQLITE_AFF_NUMERIC:
65350 **    Try to convert pRec to an integer representation or a
65351 **    floating-point representation if an integer representation
65352 **    is not possible.  Note that the integer representation is
65353 **    always preferred, even if the affinity is REAL, because
65354 **    an integer representation is more space efficient on disk.
65355 **
65356 ** SQLITE_AFF_TEXT:
65357 **    Convert pRec to a text representation.
65358 **
65359 ** SQLITE_AFF_NONE:
65360 **    No-op.  pRec is unchanged.
65361 */
65362 static void applyAffinity(
65363   Mem *pRec,          /* The value to apply affinity to */
65364   char affinity,      /* The affinity to be applied */
65365   u8 enc              /* Use this text encoding */
65366 ){
65367   if( affinity==SQLITE_AFF_TEXT ){
65368     /* Only attempt the conversion to TEXT if there is an integer or real
65369     ** representation (blob and NULL do not get converted) but no string
65370     ** representation.
65371     */
65372     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
65373       sqlite3VdbeMemStringify(pRec, enc);
65374     }
65375     pRec->flags &= ~(MEM_Real|MEM_Int);
65376   }else if( affinity!=SQLITE_AFF_NONE ){
65377     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
65378              || affinity==SQLITE_AFF_NUMERIC );
65379     applyNumericAffinity(pRec);
65380     if( pRec->flags & MEM_Real ){
65381       sqlite3VdbeIntegerAffinity(pRec);
65382     }
65383   }
65384 }
65385
65386 /*
65387 ** Try to convert the type of a function argument or a result column
65388 ** into a numeric representation.  Use either INTEGER or REAL whichever
65389 ** is appropriate.  But only do the conversion if it is possible without
65390 ** loss of information and return the revised type of the argument.
65391 */
65392 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
65393   Mem *pMem = (Mem*)pVal;
65394   if( pMem->type==SQLITE_TEXT ){
65395     applyNumericAffinity(pMem);
65396     sqlite3VdbeMemStoreType(pMem);
65397   }
65398   return pMem->type;
65399 }
65400
65401 /*
65402 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
65403 ** not the internal Mem* type.
65404 */
65405 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
65406   sqlite3_value *pVal,
65407   u8 affinity,
65408   u8 enc
65409 ){
65410   applyAffinity((Mem *)pVal, affinity, enc);
65411 }
65412
65413 #ifdef SQLITE_DEBUG
65414 /*
65415 ** Write a nice string representation of the contents of cell pMem
65416 ** into buffer zBuf, length nBuf.
65417 */
65418 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
65419   char *zCsr = zBuf;
65420   int f = pMem->flags;
65421
65422   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
65423
65424   if( f&MEM_Blob ){
65425     int i;
65426     char c;
65427     if( f & MEM_Dyn ){
65428       c = 'z';
65429       assert( (f & (MEM_Static|MEM_Ephem))==0 );
65430     }else if( f & MEM_Static ){
65431       c = 't';
65432       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65433     }else if( f & MEM_Ephem ){
65434       c = 'e';
65435       assert( (f & (MEM_Static|MEM_Dyn))==0 );
65436     }else{
65437       c = 's';
65438     }
65439
65440     sqlite3_snprintf(100, zCsr, "%c", c);
65441     zCsr += sqlite3Strlen30(zCsr);
65442     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
65443     zCsr += sqlite3Strlen30(zCsr);
65444     for(i=0; i<16 && i<pMem->n; i++){
65445       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
65446       zCsr += sqlite3Strlen30(zCsr);
65447     }
65448     for(i=0; i<16 && i<pMem->n; i++){
65449       char z = pMem->z[i];
65450       if( z<32 || z>126 ) *zCsr++ = '.';
65451       else *zCsr++ = z;
65452     }
65453
65454     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
65455     zCsr += sqlite3Strlen30(zCsr);
65456     if( f & MEM_Zero ){
65457       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
65458       zCsr += sqlite3Strlen30(zCsr);
65459     }
65460     *zCsr = '\0';
65461   }else if( f & MEM_Str ){
65462     int j, k;
65463     zBuf[0] = ' ';
65464     if( f & MEM_Dyn ){
65465       zBuf[1] = 'z';
65466       assert( (f & (MEM_Static|MEM_Ephem))==0 );
65467     }else if( f & MEM_Static ){
65468       zBuf[1] = 't';
65469       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65470     }else if( f & MEM_Ephem ){
65471       zBuf[1] = 'e';
65472       assert( (f & (MEM_Static|MEM_Dyn))==0 );
65473     }else{
65474       zBuf[1] = 's';
65475     }
65476     k = 2;
65477     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
65478     k += sqlite3Strlen30(&zBuf[k]);
65479     zBuf[k++] = '[';
65480     for(j=0; j<15 && j<pMem->n; j++){
65481       u8 c = pMem->z[j];
65482       if( c>=0x20 && c<0x7f ){
65483         zBuf[k++] = c;
65484       }else{
65485         zBuf[k++] = '.';
65486       }
65487     }
65488     zBuf[k++] = ']';
65489     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
65490     k += sqlite3Strlen30(&zBuf[k]);
65491     zBuf[k++] = 0;
65492   }
65493 }
65494 #endif
65495
65496 #ifdef SQLITE_DEBUG
65497 /*
65498 ** Print the value of a register for tracing purposes:
65499 */
65500 static void memTracePrint(FILE *out, Mem *p){
65501   if( p->flags & MEM_Invalid ){
65502     fprintf(out, " undefined");
65503   }else if( p->flags & MEM_Null ){
65504     fprintf(out, " NULL");
65505   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
65506     fprintf(out, " si:%lld", p->u.i);
65507   }else if( p->flags & MEM_Int ){
65508     fprintf(out, " i:%lld", p->u.i);
65509 #ifndef SQLITE_OMIT_FLOATING_POINT
65510   }else if( p->flags & MEM_Real ){
65511     fprintf(out, " r:%g", p->r);
65512 #endif
65513   }else if( p->flags & MEM_RowSet ){
65514     fprintf(out, " (rowset)");
65515   }else{
65516     char zBuf[200];
65517     sqlite3VdbeMemPrettyPrint(p, zBuf);
65518     fprintf(out, " ");
65519     fprintf(out, "%s", zBuf);
65520   }
65521 }
65522 static void registerTrace(FILE *out, int iReg, Mem *p){
65523   fprintf(out, "REG[%d] = ", iReg);
65524   memTracePrint(out, p);
65525   fprintf(out, "\n");
65526 }
65527 #endif
65528
65529 #ifdef SQLITE_DEBUG
65530 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
65531 #else
65532 #  define REGISTER_TRACE(R,M)
65533 #endif
65534
65535
65536 #ifdef VDBE_PROFILE
65537
65538 /*
65539 ** hwtime.h contains inline assembler code for implementing
65540 ** high-performance timing routines.
65541 */
65542 /************** Include hwtime.h in the middle of vdbe.c *********************/
65543 /************** Begin file hwtime.h ******************************************/
65544 /*
65545 ** 2008 May 27
65546 **
65547 ** The author disclaims copyright to this source code.  In place of
65548 ** a legal notice, here is a blessing:
65549 **
65550 **    May you do good and not evil.
65551 **    May you find forgiveness for yourself and forgive others.
65552 **    May you share freely, never taking more than you give.
65553 **
65554 ******************************************************************************
65555 **
65556 ** This file contains inline asm code for retrieving "high-performance"
65557 ** counters for x86 class CPUs.
65558 */
65559 #ifndef _HWTIME_H_
65560 #define _HWTIME_H_
65561
65562 /*
65563 ** The following routine only works on pentium-class (or newer) processors.
65564 ** It uses the RDTSC opcode to read the cycle count value out of the
65565 ** processor and returns that value.  This can be used for high-res
65566 ** profiling.
65567 */
65568 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
65569       (defined(i386) || defined(__i386__) || defined(_M_IX86))
65570
65571   #if defined(__GNUC__)
65572
65573   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65574      unsigned int lo, hi;
65575      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
65576      return (sqlite_uint64)hi << 32 | lo;
65577   }
65578
65579   #elif defined(_MSC_VER)
65580
65581   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
65582      __asm {
65583         rdtsc
65584         ret       ; return value at EDX:EAX
65585      }
65586   }
65587
65588   #endif
65589
65590 #elif (defined(__GNUC__) && defined(__x86_64__))
65591
65592   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65593       unsigned long val;
65594       __asm__ __volatile__ ("rdtsc" : "=A" (val));
65595       return val;
65596   }
65597
65598 #elif (defined(__GNUC__) && defined(__ppc__))
65599
65600   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65601       unsigned long long retval;
65602       unsigned long junk;
65603       __asm__ __volatile__ ("\n\
65604           1:      mftbu   %1\n\
65605                   mftb    %L0\n\
65606                   mftbu   %0\n\
65607                   cmpw    %0,%1\n\
65608                   bne     1b"
65609                   : "=r" (retval), "=r" (junk));
65610       return retval;
65611   }
65612
65613 #else
65614
65615   #error Need implementation of sqlite3Hwtime() for your platform.
65616
65617   /*
65618   ** To compile without implementing sqlite3Hwtime() for your platform,
65619   ** you can remove the above #error and use the following
65620   ** stub function.  You will lose timing support for many
65621   ** of the debugging and testing utilities, but it should at
65622   ** least compile and run.
65623   */
65624 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
65625
65626 #endif
65627
65628 #endif /* !defined(_HWTIME_H_) */
65629
65630 /************** End of hwtime.h **********************************************/
65631 /************** Continuing where we left off in vdbe.c ***********************/
65632
65633 #endif
65634
65635 /*
65636 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
65637 ** sqlite3_interrupt() routine has been called.  If it has been, then
65638 ** processing of the VDBE program is interrupted.
65639 **
65640 ** This macro added to every instruction that does a jump in order to
65641 ** implement a loop.  This test used to be on every single instruction,
65642 ** but that meant we more testing than we needed.  By only testing the
65643 ** flag on jump instructions, we get a (small) speed improvement.
65644 */
65645 #define CHECK_FOR_INTERRUPT \
65646    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
65647
65648
65649 #ifndef NDEBUG
65650 /*
65651 ** This function is only called from within an assert() expression. It
65652 ** checks that the sqlite3.nTransaction variable is correctly set to
65653 ** the number of non-transaction savepoints currently in the
65654 ** linked list starting at sqlite3.pSavepoint.
65655 **
65656 ** Usage:
65657 **
65658 **     assert( checkSavepointCount(db) );
65659 */
65660 static int checkSavepointCount(sqlite3 *db){
65661   int n = 0;
65662   Savepoint *p;
65663   for(p=db->pSavepoint; p; p=p->pNext) n++;
65664   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
65665   return 1;
65666 }
65667 #endif
65668
65669 /*
65670 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
65671 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
65672 ** in memory obtained from sqlite3DbMalloc).
65673 */
65674 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
65675   sqlite3 *db = p->db;
65676   sqlite3DbFree(db, p->zErrMsg);
65677   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
65678   sqlite3_free(pVtab->zErrMsg);
65679   pVtab->zErrMsg = 0;
65680 }
65681
65682
65683 /*
65684 ** Execute as much of a VDBE program as we can then return.
65685 **
65686 ** sqlite3VdbeMakeReady() must be called before this routine in order to
65687 ** close the program with a final OP_Halt and to set up the callbacks
65688 ** and the error message pointer.
65689 **
65690 ** Whenever a row or result data is available, this routine will either
65691 ** invoke the result callback (if there is one) or return with
65692 ** SQLITE_ROW.
65693 **
65694 ** If an attempt is made to open a locked database, then this routine
65695 ** will either invoke the busy callback (if there is one) or it will
65696 ** return SQLITE_BUSY.
65697 **
65698 ** If an error occurs, an error message is written to memory obtained
65699 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
65700 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
65701 **
65702 ** If the callback ever returns non-zero, then the program exits
65703 ** immediately.  There will be no error message but the p->rc field is
65704 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
65705 **
65706 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
65707 ** routine to return SQLITE_ERROR.
65708 **
65709 ** Other fatal errors return SQLITE_ERROR.
65710 **
65711 ** After this routine has finished, sqlite3VdbeFinalize() should be
65712 ** used to clean up the mess that was left behind.
65713 */
65714 SQLITE_PRIVATE int sqlite3VdbeExec(
65715   Vdbe *p                    /* The VDBE */
65716 ){
65717   int pc=0;                  /* The program counter */
65718   Op *aOp = p->aOp;          /* Copy of p->aOp */
65719   Op *pOp;                   /* Current operation */
65720   int rc = SQLITE_OK;        /* Value to return */
65721   sqlite3 *db = p->db;       /* The database */
65722   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
65723   u8 encoding = ENC(db);     /* The database encoding */
65724 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65725   int checkProgress;         /* True if progress callbacks are enabled */
65726   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
65727 #endif
65728   Mem *aMem = p->aMem;       /* Copy of p->aMem */
65729   Mem *pIn1 = 0;             /* 1st input operand */
65730   Mem *pIn2 = 0;             /* 2nd input operand */
65731   Mem *pIn3 = 0;             /* 3rd input operand */
65732   Mem *pOut = 0;             /* Output operand */
65733   int iCompare = 0;          /* Result of last OP_Compare operation */
65734   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
65735   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
65736 #ifdef VDBE_PROFILE
65737   u64 start;                 /* CPU clock count at start of opcode */
65738   int origPc;                /* Program counter at start of opcode */
65739 #endif
65740   /********************************************************************
65741   ** Automatically generated code
65742   **
65743   ** The following union is automatically generated by the
65744   ** vdbe-compress.tcl script.  The purpose of this union is to
65745   ** reduce the amount of stack space required by this function.
65746   ** See comments in the vdbe-compress.tcl script for details.
65747   */
65748   union vdbeExecUnion {
65749     struct OP_Yield_stack_vars {
65750       int pcDest;
65751     } aa;
65752     struct OP_Null_stack_vars {
65753       int cnt;
65754       u16 nullFlag;
65755     } ab;
65756     struct OP_Variable_stack_vars {
65757       Mem *pVar;       /* Value being transferred */
65758     } ac;
65759     struct OP_Move_stack_vars {
65760       char *zMalloc;   /* Holding variable for allocated memory */
65761       int n;           /* Number of registers left to copy */
65762       int p1;          /* Register to copy from */
65763       int p2;          /* Register to copy to */
65764     } ad;
65765     struct OP_Copy_stack_vars {
65766       int n;
65767     } ae;
65768     struct OP_ResultRow_stack_vars {
65769       Mem *pMem;
65770       int i;
65771     } af;
65772     struct OP_Concat_stack_vars {
65773       i64 nByte;
65774     } ag;
65775     struct OP_Remainder_stack_vars {
65776       char bIntint;   /* Started out as two integer operands */
65777       int flags;      /* Combined MEM_* flags from both inputs */
65778       i64 iA;         /* Integer value of left operand */
65779       i64 iB;         /* Integer value of right operand */
65780       double rA;      /* Real value of left operand */
65781       double rB;      /* Real value of right operand */
65782     } ah;
65783     struct OP_Function_stack_vars {
65784       int i;
65785       Mem *pArg;
65786       sqlite3_context ctx;
65787       sqlite3_value **apVal;
65788       int n;
65789     } ai;
65790     struct OP_ShiftRight_stack_vars {
65791       i64 iA;
65792       u64 uA;
65793       i64 iB;
65794       u8 op;
65795     } aj;
65796     struct OP_Ge_stack_vars {
65797       int res;            /* Result of the comparison of pIn1 against pIn3 */
65798       char affinity;      /* Affinity to use for comparison */
65799       u16 flags1;         /* Copy of initial value of pIn1->flags */
65800       u16 flags3;         /* Copy of initial value of pIn3->flags */
65801     } ak;
65802     struct OP_Compare_stack_vars {
65803       int n;
65804       int i;
65805       int p1;
65806       int p2;
65807       const KeyInfo *pKeyInfo;
65808       int idx;
65809       CollSeq *pColl;    /* Collating sequence to use on this term */
65810       int bRev;          /* True for DESCENDING sort order */
65811     } al;
65812     struct OP_Or_stack_vars {
65813       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65814       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65815     } am;
65816     struct OP_IfNot_stack_vars {
65817       int c;
65818     } an;
65819     struct OP_Column_stack_vars {
65820       u32 payloadSize;   /* Number of bytes in the record */
65821       i64 payloadSize64; /* Number of bytes in the record */
65822       int p1;            /* P1 value of the opcode */
65823       int p2;            /* column number to retrieve */
65824       VdbeCursor *pC;    /* The VDBE cursor */
65825       char *zRec;        /* Pointer to complete record-data */
65826       BtCursor *pCrsr;   /* The BTree cursor */
65827       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65828       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65829       int nField;        /* number of fields in the record */
65830       int len;           /* The length of the serialized data for the column */
65831       int i;             /* Loop counter */
65832       char *zData;       /* Part of the record being decoded */
65833       Mem *pDest;        /* Where to write the extracted value */
65834       Mem sMem;          /* For storing the record being decoded */
65835       u8 *zIdx;          /* Index into header */
65836       u8 *zEndHdr;       /* Pointer to first byte after the header */
65837       u32 offset;        /* Offset into the data */
65838       u32 szField;       /* Number of bytes in the content of a field */
65839       int szHdr;         /* Size of the header size field at start of record */
65840       int avail;         /* Number of bytes of available data */
65841       u32 t;             /* A type code from the record header */
65842       Mem *pReg;         /* PseudoTable input register */
65843     } ao;
65844     struct OP_Affinity_stack_vars {
65845       const char *zAffinity;   /* The affinity to be applied */
65846       char cAff;               /* A single character of affinity */
65847     } ap;
65848     struct OP_MakeRecord_stack_vars {
65849       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65850       Mem *pRec;             /* The new record */
65851       u64 nData;             /* Number of bytes of data space */
65852       int nHdr;              /* Number of bytes of header space */
65853       i64 nByte;             /* Data space required for this record */
65854       int nZero;             /* Number of zero bytes at the end of the record */
65855       int nVarint;           /* Number of bytes in a varint */
65856       u32 serial_type;       /* Type field */
65857       Mem *pData0;           /* First field to be combined into the record */
65858       Mem *pLast;            /* Last field of the record */
65859       int nField;            /* Number of fields in the record */
65860       char *zAffinity;       /* The affinity string for the record */
65861       int file_format;       /* File format to use for encoding */
65862       int i;                 /* Space used in zNewRecord[] */
65863       int len;               /* Length of a field */
65864     } aq;
65865     struct OP_Count_stack_vars {
65866       i64 nEntry;
65867       BtCursor *pCrsr;
65868     } ar;
65869     struct OP_Savepoint_stack_vars {
65870       int p1;                         /* Value of P1 operand */
65871       char *zName;                    /* Name of savepoint */
65872       int nName;
65873       Savepoint *pNew;
65874       Savepoint *pSavepoint;
65875       Savepoint *pTmp;
65876       int iSavepoint;
65877       int ii;
65878     } as;
65879     struct OP_AutoCommit_stack_vars {
65880       int desiredAutoCommit;
65881       int iRollback;
65882       int turnOnAC;
65883     } at;
65884     struct OP_Transaction_stack_vars {
65885       Btree *pBt;
65886     } au;
65887     struct OP_ReadCookie_stack_vars {
65888       int iMeta;
65889       int iDb;
65890       int iCookie;
65891     } av;
65892     struct OP_SetCookie_stack_vars {
65893       Db *pDb;
65894     } aw;
65895     struct OP_VerifyCookie_stack_vars {
65896       int iMeta;
65897       int iGen;
65898       Btree *pBt;
65899     } ax;
65900     struct OP_OpenWrite_stack_vars {
65901       int nField;
65902       KeyInfo *pKeyInfo;
65903       int p2;
65904       int iDb;
65905       int wrFlag;
65906       Btree *pX;
65907       VdbeCursor *pCur;
65908       Db *pDb;
65909     } ay;
65910     struct OP_OpenEphemeral_stack_vars {
65911       VdbeCursor *pCx;
65912     } az;
65913     struct OP_SorterOpen_stack_vars {
65914       VdbeCursor *pCx;
65915     } ba;
65916     struct OP_OpenPseudo_stack_vars {
65917       VdbeCursor *pCx;
65918     } bb;
65919     struct OP_SeekGt_stack_vars {
65920       int res;
65921       int oc;
65922       VdbeCursor *pC;
65923       UnpackedRecord r;
65924       int nField;
65925       i64 iKey;      /* The rowid we are to seek to */
65926     } bc;
65927     struct OP_Seek_stack_vars {
65928       VdbeCursor *pC;
65929     } bd;
65930     struct OP_Found_stack_vars {
65931       int alreadyExists;
65932       VdbeCursor *pC;
65933       int res;
65934       char *pFree;
65935       UnpackedRecord *pIdxKey;
65936       UnpackedRecord r;
65937       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65938     } be;
65939     struct OP_IsUnique_stack_vars {
65940       u16 ii;
65941       VdbeCursor *pCx;
65942       BtCursor *pCrsr;
65943       u16 nField;
65944       Mem *aMx;
65945       UnpackedRecord r;                  /* B-Tree index search key */
65946       i64 R;                             /* Rowid stored in register P3 */
65947     } bf;
65948     struct OP_NotExists_stack_vars {
65949       VdbeCursor *pC;
65950       BtCursor *pCrsr;
65951       int res;
65952       u64 iKey;
65953     } bg;
65954     struct OP_NewRowid_stack_vars {
65955       i64 v;                 /* The new rowid */
65956       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65957       int res;               /* Result of an sqlite3BtreeLast() */
65958       int cnt;               /* Counter to limit the number of searches */
65959       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65960       VdbeFrame *pFrame;     /* Root frame of VDBE */
65961     } bh;
65962     struct OP_InsertInt_stack_vars {
65963       Mem *pData;       /* MEM cell holding data for the record to be inserted */
65964       Mem *pKey;        /* MEM cell holding key  for the record */
65965       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
65966       VdbeCursor *pC;   /* Cursor to table into which insert is written */
65967       int nZero;        /* Number of zero-bytes to append */
65968       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
65969       const char *zDb;  /* database name - used by the update hook */
65970       const char *zTbl; /* Table name - used by the opdate hook */
65971       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
65972     } bi;
65973     struct OP_Delete_stack_vars {
65974       i64 iKey;
65975       VdbeCursor *pC;
65976     } bj;
65977     struct OP_SorterCompare_stack_vars {
65978       VdbeCursor *pC;
65979       int res;
65980     } bk;
65981     struct OP_SorterData_stack_vars {
65982       VdbeCursor *pC;
65983     } bl;
65984     struct OP_RowData_stack_vars {
65985       VdbeCursor *pC;
65986       BtCursor *pCrsr;
65987       u32 n;
65988       i64 n64;
65989     } bm;
65990     struct OP_Rowid_stack_vars {
65991       VdbeCursor *pC;
65992       i64 v;
65993       sqlite3_vtab *pVtab;
65994       const sqlite3_module *pModule;
65995     } bn;
65996     struct OP_NullRow_stack_vars {
65997       VdbeCursor *pC;
65998     } bo;
65999     struct OP_Last_stack_vars {
66000       VdbeCursor *pC;
66001       BtCursor *pCrsr;
66002       int res;
66003     } bp;
66004     struct OP_Rewind_stack_vars {
66005       VdbeCursor *pC;
66006       BtCursor *pCrsr;
66007       int res;
66008     } bq;
66009     struct OP_Next_stack_vars {
66010       VdbeCursor *pC;
66011       int res;
66012     } br;
66013     struct OP_IdxInsert_stack_vars {
66014       VdbeCursor *pC;
66015       BtCursor *pCrsr;
66016       int nKey;
66017       const char *zKey;
66018     } bs;
66019     struct OP_IdxDelete_stack_vars {
66020       VdbeCursor *pC;
66021       BtCursor *pCrsr;
66022       int res;
66023       UnpackedRecord r;
66024     } bt;
66025     struct OP_IdxRowid_stack_vars {
66026       BtCursor *pCrsr;
66027       VdbeCursor *pC;
66028       i64 rowid;
66029     } bu;
66030     struct OP_IdxGE_stack_vars {
66031       VdbeCursor *pC;
66032       int res;
66033       UnpackedRecord r;
66034     } bv;
66035     struct OP_Destroy_stack_vars {
66036       int iMoved;
66037       int iCnt;
66038       Vdbe *pVdbe;
66039       int iDb;
66040     } bw;
66041     struct OP_Clear_stack_vars {
66042       int nChange;
66043     } bx;
66044     struct OP_CreateTable_stack_vars {
66045       int pgno;
66046       int flags;
66047       Db *pDb;
66048     } by;
66049     struct OP_ParseSchema_stack_vars {
66050       int iDb;
66051       const char *zMaster;
66052       char *zSql;
66053       InitData initData;
66054     } bz;
66055     struct OP_IntegrityCk_stack_vars {
66056       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
66057       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
66058       int j;          /* Loop counter */
66059       int nErr;       /* Number of errors reported */
66060       char *z;        /* Text of the error report */
66061       Mem *pnErr;     /* Register keeping track of errors remaining */
66062     } ca;
66063     struct OP_RowSetRead_stack_vars {
66064       i64 val;
66065     } cb;
66066     struct OP_RowSetTest_stack_vars {
66067       int iSet;
66068       int exists;
66069     } cc;
66070     struct OP_Program_stack_vars {
66071       int nMem;               /* Number of memory registers for sub-program */
66072       int nByte;              /* Bytes of runtime space required for sub-program */
66073       Mem *pRt;               /* Register to allocate runtime space */
66074       Mem *pMem;              /* Used to iterate through memory cells */
66075       Mem *pEnd;              /* Last memory cell in new array */
66076       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
66077       SubProgram *pProgram;   /* Sub-program to execute */
66078       void *t;                /* Token identifying trigger */
66079     } cd;
66080     struct OP_Param_stack_vars {
66081       VdbeFrame *pFrame;
66082       Mem *pIn;
66083     } ce;
66084     struct OP_MemMax_stack_vars {
66085       Mem *pIn1;
66086       VdbeFrame *pFrame;
66087     } cf;
66088     struct OP_AggStep_stack_vars {
66089       int n;
66090       int i;
66091       Mem *pMem;
66092       Mem *pRec;
66093       sqlite3_context ctx;
66094       sqlite3_value **apVal;
66095     } cg;
66096     struct OP_AggFinal_stack_vars {
66097       Mem *pMem;
66098     } ch;
66099     struct OP_Checkpoint_stack_vars {
66100       int i;                          /* Loop counter */
66101       int aRes[3];                    /* Results */
66102       Mem *pMem;                      /* Write results here */
66103     } ci;
66104     struct OP_JournalMode_stack_vars {
66105       Btree *pBt;                     /* Btree to change journal mode of */
66106       Pager *pPager;                  /* Pager associated with pBt */
66107       int eNew;                       /* New journal mode */
66108       int eOld;                       /* The old journal mode */
66109 #ifndef SQLITE_OMIT_WAL
66110       const char *zFilename;          /* Name of database file for pPager */
66111 #endif
66112     } cj;
66113     struct OP_IncrVacuum_stack_vars {
66114       Btree *pBt;
66115     } ck;
66116     struct OP_VBegin_stack_vars {
66117       VTable *pVTab;
66118     } cl;
66119     struct OP_VOpen_stack_vars {
66120       VdbeCursor *pCur;
66121       sqlite3_vtab_cursor *pVtabCursor;
66122       sqlite3_vtab *pVtab;
66123       sqlite3_module *pModule;
66124     } cm;
66125     struct OP_VFilter_stack_vars {
66126       int nArg;
66127       int iQuery;
66128       const sqlite3_module *pModule;
66129       Mem *pQuery;
66130       Mem *pArgc;
66131       sqlite3_vtab_cursor *pVtabCursor;
66132       sqlite3_vtab *pVtab;
66133       VdbeCursor *pCur;
66134       int res;
66135       int i;
66136       Mem **apArg;
66137     } cn;
66138     struct OP_VColumn_stack_vars {
66139       sqlite3_vtab *pVtab;
66140       const sqlite3_module *pModule;
66141       Mem *pDest;
66142       sqlite3_context sContext;
66143     } co;
66144     struct OP_VNext_stack_vars {
66145       sqlite3_vtab *pVtab;
66146       const sqlite3_module *pModule;
66147       int res;
66148       VdbeCursor *pCur;
66149     } cp;
66150     struct OP_VRename_stack_vars {
66151       sqlite3_vtab *pVtab;
66152       Mem *pName;
66153     } cq;
66154     struct OP_VUpdate_stack_vars {
66155       sqlite3_vtab *pVtab;
66156       sqlite3_module *pModule;
66157       int nArg;
66158       int i;
66159       sqlite_int64 rowid;
66160       Mem **apArg;
66161       Mem *pX;
66162     } cr;
66163     struct OP_Trace_stack_vars {
66164       char *zTrace;
66165       char *z;
66166     } cs;
66167   } u;
66168   /* End automatically generated code
66169   ********************************************************************/
66170
66171   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
66172   sqlite3VdbeEnter(p);
66173   if( p->rc==SQLITE_NOMEM ){
66174     /* This happens if a malloc() inside a call to sqlite3_column_text() or
66175     ** sqlite3_column_text16() failed.  */
66176     goto no_mem;
66177   }
66178   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
66179   p->rc = SQLITE_OK;
66180   assert( p->explain==0 );
66181   p->pResultSet = 0;
66182   db->busyHandler.nBusy = 0;
66183   CHECK_FOR_INTERRUPT;
66184   sqlite3VdbeIOTraceSql(p);
66185 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
66186   checkProgress = db->xProgress!=0;
66187 #endif
66188 #ifdef SQLITE_DEBUG
66189   sqlite3BeginBenignMalloc();
66190   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
66191     int i;
66192     printf("VDBE Program Listing:\n");
66193     sqlite3VdbePrintSql(p);
66194     for(i=0; i<p->nOp; i++){
66195       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
66196     }
66197   }
66198   sqlite3EndBenignMalloc();
66199 #endif
66200   for(pc=p->pc; rc==SQLITE_OK; pc++){
66201     assert( pc>=0 && pc<p->nOp );
66202     if( db->mallocFailed ) goto no_mem;
66203 #ifdef VDBE_PROFILE
66204     origPc = pc;
66205     start = sqlite3Hwtime();
66206 #endif
66207     pOp = &aOp[pc];
66208
66209     /* Only allow tracing if SQLITE_DEBUG is defined.
66210     */
66211 #ifdef SQLITE_DEBUG
66212     if( p->trace ){
66213       if( pc==0 ){
66214         printf("VDBE Execution Trace:\n");
66215         sqlite3VdbePrintSql(p);
66216       }
66217       sqlite3VdbePrintOp(p->trace, pc, pOp);
66218     }
66219 #endif
66220
66221
66222     /* Check to see if we need to simulate an interrupt.  This only happens
66223     ** if we have a special test build.
66224     */
66225 #ifdef SQLITE_TEST
66226     if( sqlite3_interrupt_count>0 ){
66227       sqlite3_interrupt_count--;
66228       if( sqlite3_interrupt_count==0 ){
66229         sqlite3_interrupt(db);
66230       }
66231     }
66232 #endif
66233
66234 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
66235     /* Call the progress callback if it is configured and the required number
66236     ** of VDBE ops have been executed (either since this invocation of
66237     ** sqlite3VdbeExec() or since last time the progress callback was called).
66238     ** If the progress callback returns non-zero, exit the virtual machine with
66239     ** a return code SQLITE_ABORT.
66240     */
66241     if( checkProgress ){
66242       if( db->nProgressOps==nProgressOps ){
66243         int prc;
66244         prc = db->xProgress(db->pProgressArg);
66245         if( prc!=0 ){
66246           rc = SQLITE_INTERRUPT;
66247           goto vdbe_error_halt;
66248         }
66249         nProgressOps = 0;
66250       }
66251       nProgressOps++;
66252     }
66253 #endif
66254
66255     /* On any opcode with the "out2-prerelease" tag, free any
66256     ** external allocations out of mem[p2] and set mem[p2] to be
66257     ** an undefined integer.  Opcodes will either fill in the integer
66258     ** value or convert mem[p2] to a different type.
66259     */
66260     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
66261     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
66262       assert( pOp->p2>0 );
66263       assert( pOp->p2<=p->nMem );
66264       pOut = &aMem[pOp->p2];
66265       memAboutToChange(p, pOut);
66266       VdbeMemRelease(pOut);
66267       pOut->flags = MEM_Int;
66268     }
66269
66270     /* Sanity checking on other operands */
66271 #ifdef SQLITE_DEBUG
66272     if( (pOp->opflags & OPFLG_IN1)!=0 ){
66273       assert( pOp->p1>0 );
66274       assert( pOp->p1<=p->nMem );
66275       assert( memIsValid(&aMem[pOp->p1]) );
66276       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
66277     }
66278     if( (pOp->opflags & OPFLG_IN2)!=0 ){
66279       assert( pOp->p2>0 );
66280       assert( pOp->p2<=p->nMem );
66281       assert( memIsValid(&aMem[pOp->p2]) );
66282       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
66283     }
66284     if( (pOp->opflags & OPFLG_IN3)!=0 ){
66285       assert( pOp->p3>0 );
66286       assert( pOp->p3<=p->nMem );
66287       assert( memIsValid(&aMem[pOp->p3]) );
66288       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
66289     }
66290     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
66291       assert( pOp->p2>0 );
66292       assert( pOp->p2<=p->nMem );
66293       memAboutToChange(p, &aMem[pOp->p2]);
66294     }
66295     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
66296       assert( pOp->p3>0 );
66297       assert( pOp->p3<=p->nMem );
66298       memAboutToChange(p, &aMem[pOp->p3]);
66299     }
66300 #endif
66301
66302     switch( pOp->opcode ){
66303
66304 /*****************************************************************************
66305 ** What follows is a massive switch statement where each case implements a
66306 ** separate instruction in the virtual machine.  If we follow the usual
66307 ** indentation conventions, each case should be indented by 6 spaces.  But
66308 ** that is a lot of wasted space on the left margin.  So the code within
66309 ** the switch statement will break with convention and be flush-left. Another
66310 ** big comment (similar to this one) will mark the point in the code where
66311 ** we transition back to normal indentation.
66312 **
66313 ** The formatting of each case is important.  The makefile for SQLite
66314 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
66315 ** file looking for lines that begin with "case OP_".  The opcodes.h files
66316 ** will be filled with #defines that give unique integer values to each
66317 ** opcode and the opcodes.c file is filled with an array of strings where
66318 ** each string is the symbolic name for the corresponding opcode.  If the
66319 ** case statement is followed by a comment of the form "/# same as ... #/"
66320 ** that comment is used to determine the particular value of the opcode.
66321 **
66322 ** Other keywords in the comment that follows each case are used to
66323 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
66324 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
66325 ** the mkopcodeh.awk script for additional information.
66326 **
66327 ** Documentation about VDBE opcodes is generated by scanning this file
66328 ** for lines of that contain "Opcode:".  That line and all subsequent
66329 ** comment lines are used in the generation of the opcode.html documentation
66330 ** file.
66331 **
66332 ** SUMMARY:
66333 **
66334 **     Formatting is important to scripts that scan this file.
66335 **     Do not deviate from the formatting style currently in use.
66336 **
66337 *****************************************************************************/
66338
66339 /* Opcode:  Goto * P2 * * *
66340 **
66341 ** An unconditional jump to address P2.
66342 ** The next instruction executed will be
66343 ** the one at index P2 from the beginning of
66344 ** the program.
66345 */
66346 case OP_Goto: {             /* jump */
66347   CHECK_FOR_INTERRUPT;
66348   pc = pOp->p2 - 1;
66349   break;
66350 }
66351
66352 /* Opcode:  Gosub P1 P2 * * *
66353 **
66354 ** Write the current address onto register P1
66355 ** and then jump to address P2.
66356 */
66357 case OP_Gosub: {            /* jump */
66358   assert( pOp->p1>0 && pOp->p1<=p->nMem );
66359   pIn1 = &aMem[pOp->p1];
66360   assert( (pIn1->flags & MEM_Dyn)==0 );
66361   memAboutToChange(p, pIn1);
66362   pIn1->flags = MEM_Int;
66363   pIn1->u.i = pc;
66364   REGISTER_TRACE(pOp->p1, pIn1);
66365   pc = pOp->p2 - 1;
66366   break;
66367 }
66368
66369 /* Opcode:  Return P1 * * * *
66370 **
66371 ** Jump to the next instruction after the address in register P1.
66372 */
66373 case OP_Return: {           /* in1 */
66374   pIn1 = &aMem[pOp->p1];
66375   assert( pIn1->flags & MEM_Int );
66376   pc = (int)pIn1->u.i;
66377   break;
66378 }
66379
66380 /* Opcode:  Yield P1 * * * *
66381 **
66382 ** Swap the program counter with the value in register P1.
66383 */
66384 case OP_Yield: {            /* in1 */
66385 #if 0  /* local variables moved into u.aa */
66386   int pcDest;
66387 #endif /* local variables moved into u.aa */
66388   pIn1 = &aMem[pOp->p1];
66389   assert( (pIn1->flags & MEM_Dyn)==0 );
66390   pIn1->flags = MEM_Int;
66391   u.aa.pcDest = (int)pIn1->u.i;
66392   pIn1->u.i = pc;
66393   REGISTER_TRACE(pOp->p1, pIn1);
66394   pc = u.aa.pcDest;
66395   break;
66396 }
66397
66398 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
66399 **
66400 ** Check the value in register P3.  If it is NULL then Halt using
66401 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
66402 ** value in register P3 is not NULL, then this routine is a no-op.
66403 */
66404 case OP_HaltIfNull: {      /* in3 */
66405   pIn3 = &aMem[pOp->p3];
66406   if( (pIn3->flags & MEM_Null)==0 ) break;
66407   /* Fall through into OP_Halt */
66408 }
66409
66410 /* Opcode:  Halt P1 P2 * P4 *
66411 **
66412 ** Exit immediately.  All open cursors, etc are closed
66413 ** automatically.
66414 **
66415 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
66416 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
66417 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
66418 ** whether or not to rollback the current transaction.  Do not rollback
66419 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
66420 ** then back out all changes that have occurred during this execution of the
66421 ** VDBE, but do not rollback the transaction.
66422 **
66423 ** If P4 is not null then it is an error message string.
66424 **
66425 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
66426 ** every program.  So a jump past the last instruction of the program
66427 ** is the same as executing Halt.
66428 */
66429 case OP_Halt: {
66430   if( pOp->p1==SQLITE_OK && p->pFrame ){
66431     /* Halt the sub-program. Return control to the parent frame. */
66432     VdbeFrame *pFrame = p->pFrame;
66433     p->pFrame = pFrame->pParent;
66434     p->nFrame--;
66435     sqlite3VdbeSetChanges(db, p->nChange);
66436     pc = sqlite3VdbeFrameRestore(pFrame);
66437     lastRowid = db->lastRowid;
66438     if( pOp->p2==OE_Ignore ){
66439       /* Instruction pc is the OP_Program that invoked the sub-program
66440       ** currently being halted. If the p2 instruction of this OP_Halt
66441       ** instruction is set to OE_Ignore, then the sub-program is throwing
66442       ** an IGNORE exception. In this case jump to the address specified
66443       ** as the p2 of the calling OP_Program.  */
66444       pc = p->aOp[pc].p2-1;
66445     }
66446     aOp = p->aOp;
66447     aMem = p->aMem;
66448     break;
66449   }
66450
66451   p->rc = pOp->p1;
66452   p->errorAction = (u8)pOp->p2;
66453   p->pc = pc;
66454   if( pOp->p4.z ){
66455     assert( p->rc!=SQLITE_OK );
66456     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
66457     testcase( sqlite3GlobalConfig.xLog!=0 );
66458     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
66459   }else if( p->rc ){
66460     testcase( sqlite3GlobalConfig.xLog!=0 );
66461     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
66462   }
66463   rc = sqlite3VdbeHalt(p);
66464   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
66465   if( rc==SQLITE_BUSY ){
66466     p->rc = rc = SQLITE_BUSY;
66467   }else{
66468     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
66469     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
66470     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
66471   }
66472   goto vdbe_return;
66473 }
66474
66475 /* Opcode: Integer P1 P2 * * *
66476 **
66477 ** The 32-bit integer value P1 is written into register P2.
66478 */
66479 case OP_Integer: {         /* out2-prerelease */
66480   pOut->u.i = pOp->p1;
66481   break;
66482 }
66483
66484 /* Opcode: Int64 * P2 * P4 *
66485 **
66486 ** P4 is a pointer to a 64-bit integer value.
66487 ** Write that value into register P2.
66488 */
66489 case OP_Int64: {           /* out2-prerelease */
66490   assert( pOp->p4.pI64!=0 );
66491   pOut->u.i = *pOp->p4.pI64;
66492   break;
66493 }
66494
66495 #ifndef SQLITE_OMIT_FLOATING_POINT
66496 /* Opcode: Real * P2 * P4 *
66497 **
66498 ** P4 is a pointer to a 64-bit floating point value.
66499 ** Write that value into register P2.
66500 */
66501 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
66502   pOut->flags = MEM_Real;
66503   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
66504   pOut->r = *pOp->p4.pReal;
66505   break;
66506 }
66507 #endif
66508
66509 /* Opcode: String8 * P2 * P4 *
66510 **
66511 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
66512 ** into an OP_String before it is executed for the first time.
66513 */
66514 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
66515   assert( pOp->p4.z!=0 );
66516   pOp->opcode = OP_String;
66517   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
66518
66519 #ifndef SQLITE_OMIT_UTF16
66520   if( encoding!=SQLITE_UTF8 ){
66521     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
66522     if( rc==SQLITE_TOOBIG ) goto too_big;
66523     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
66524     assert( pOut->zMalloc==pOut->z );
66525     assert( pOut->flags & MEM_Dyn );
66526     pOut->zMalloc = 0;
66527     pOut->flags |= MEM_Static;
66528     pOut->flags &= ~MEM_Dyn;
66529     if( pOp->p4type==P4_DYNAMIC ){
66530       sqlite3DbFree(db, pOp->p4.z);
66531     }
66532     pOp->p4type = P4_DYNAMIC;
66533     pOp->p4.z = pOut->z;
66534     pOp->p1 = pOut->n;
66535   }
66536 #endif
66537   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66538     goto too_big;
66539   }
66540   /* Fall through to the next case, OP_String */
66541 }
66542
66543 /* Opcode: String P1 P2 * P4 *
66544 **
66545 ** The string value P4 of length P1 (bytes) is stored in register P2.
66546 */
66547 case OP_String: {          /* out2-prerelease */
66548   assert( pOp->p4.z!=0 );
66549   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
66550   pOut->z = pOp->p4.z;
66551   pOut->n = pOp->p1;
66552   pOut->enc = encoding;
66553   UPDATE_MAX_BLOBSIZE(pOut);
66554   break;
66555 }
66556
66557 /* Opcode: Null P1 P2 P3 * *
66558 **
66559 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
66560 ** NULL into register P3 and every register in between P2 and P3.  If P3
66561 ** is less than P2 (typically P3 is zero) then only register P2 is
66562 ** set to NULL.
66563 **
66564 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
66565 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
66566 ** OP_Ne or OP_Eq.
66567 */
66568 case OP_Null: {           /* out2-prerelease */
66569 #if 0  /* local variables moved into u.ab */
66570   int cnt;
66571   u16 nullFlag;
66572 #endif /* local variables moved into u.ab */
66573   u.ab.cnt = pOp->p3-pOp->p2;
66574   assert( pOp->p3<=p->nMem );
66575   pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
66576   while( u.ab.cnt>0 ){
66577     pOut++;
66578     memAboutToChange(p, pOut);
66579     VdbeMemRelease(pOut);
66580     pOut->flags = u.ab.nullFlag;
66581     u.ab.cnt--;
66582   }
66583   break;
66584 }
66585
66586
66587 /* Opcode: Blob P1 P2 * P4
66588 **
66589 ** P4 points to a blob of data P1 bytes long.  Store this
66590 ** blob in register P2.
66591 */
66592 case OP_Blob: {                /* out2-prerelease */
66593   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
66594   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
66595   pOut->enc = encoding;
66596   UPDATE_MAX_BLOBSIZE(pOut);
66597   break;
66598 }
66599
66600 /* Opcode: Variable P1 P2 * P4 *
66601 **
66602 ** Transfer the values of bound parameter P1 into register P2
66603 **
66604 ** If the parameter is named, then its name appears in P4 and P3==1.
66605 ** The P4 value is used by sqlite3_bind_parameter_name().
66606 */
66607 case OP_Variable: {            /* out2-prerelease */
66608 #if 0  /* local variables moved into u.ac */
66609   Mem *pVar;       /* Value being transferred */
66610 #endif /* local variables moved into u.ac */
66611
66612   assert( pOp->p1>0 && pOp->p1<=p->nVar );
66613   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
66614   u.ac.pVar = &p->aVar[pOp->p1 - 1];
66615   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
66616     goto too_big;
66617   }
66618   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
66619   UPDATE_MAX_BLOBSIZE(pOut);
66620   break;
66621 }
66622
66623 /* Opcode: Move P1 P2 P3 * *
66624 **
66625 ** Move the values in register P1..P1+P3 over into
66626 ** registers P2..P2+P3.  Registers P1..P1+P3 are
66627 ** left holding a NULL.  It is an error for register ranges
66628 ** P1..P1+P3 and P2..P2+P3 to overlap.
66629 */
66630 case OP_Move: {
66631 #if 0  /* local variables moved into u.ad */
66632   char *zMalloc;   /* Holding variable for allocated memory */
66633   int n;           /* Number of registers left to copy */
66634   int p1;          /* Register to copy from */
66635   int p2;          /* Register to copy to */
66636 #endif /* local variables moved into u.ad */
66637
66638   u.ad.n = pOp->p3 + 1;
66639   u.ad.p1 = pOp->p1;
66640   u.ad.p2 = pOp->p2;
66641   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
66642   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
66643
66644   pIn1 = &aMem[u.ad.p1];
66645   pOut = &aMem[u.ad.p2];
66646   while( u.ad.n-- ){
66647     assert( pOut<=&aMem[p->nMem] );
66648     assert( pIn1<=&aMem[p->nMem] );
66649     assert( memIsValid(pIn1) );
66650     memAboutToChange(p, pOut);
66651     u.ad.zMalloc = pOut->zMalloc;
66652     pOut->zMalloc = 0;
66653     sqlite3VdbeMemMove(pOut, pIn1);
66654 #ifdef SQLITE_DEBUG
66655     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
66656       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
66657     }
66658 #endif
66659     pIn1->zMalloc = u.ad.zMalloc;
66660     REGISTER_TRACE(u.ad.p2++, pOut);
66661     pIn1++;
66662     pOut++;
66663   }
66664   break;
66665 }
66666
66667 /* Opcode: Copy P1 P2 P3 * *
66668 **
66669 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
66670 **
66671 ** This instruction makes a deep copy of the value.  A duplicate
66672 ** is made of any string or blob constant.  See also OP_SCopy.
66673 */
66674 case OP_Copy: {
66675 #if 0  /* local variables moved into u.ae */
66676   int n;
66677 #endif /* local variables moved into u.ae */
66678
66679   u.ae.n = pOp->p3;
66680   pIn1 = &aMem[pOp->p1];
66681   pOut = &aMem[pOp->p2];
66682   assert( pOut!=pIn1 );
66683   while( 1 ){
66684     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66685     Deephemeralize(pOut);
66686 #ifdef SQLITE_DEBUG
66687     pOut->pScopyFrom = 0;
66688 #endif
66689     REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
66690     if( (u.ae.n--)==0 ) break;
66691     pOut++;
66692     pIn1++;
66693   }
66694   break;
66695 }
66696
66697 /* Opcode: SCopy P1 P2 * * *
66698 **
66699 ** Make a shallow copy of register P1 into register P2.
66700 **
66701 ** This instruction makes a shallow copy of the value.  If the value
66702 ** is a string or blob, then the copy is only a pointer to the
66703 ** original and hence if the original changes so will the copy.
66704 ** Worse, if the original is deallocated, the copy becomes invalid.
66705 ** Thus the program must guarantee that the original will not change
66706 ** during the lifetime of the copy.  Use OP_Copy to make a complete
66707 ** copy.
66708 */
66709 case OP_SCopy: {            /* in1, out2 */
66710   pIn1 = &aMem[pOp->p1];
66711   pOut = &aMem[pOp->p2];
66712   assert( pOut!=pIn1 );
66713   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66714 #ifdef SQLITE_DEBUG
66715   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
66716 #endif
66717   REGISTER_TRACE(pOp->p2, pOut);
66718   break;
66719 }
66720
66721 /* Opcode: ResultRow P1 P2 * * *
66722 **
66723 ** The registers P1 through P1+P2-1 contain a single row of
66724 ** results. This opcode causes the sqlite3_step() call to terminate
66725 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
66726 ** structure to provide access to the top P1 values as the result
66727 ** row.
66728 */
66729 case OP_ResultRow: {
66730 #if 0  /* local variables moved into u.af */
66731   Mem *pMem;
66732   int i;
66733 #endif /* local variables moved into u.af */
66734   assert( p->nResColumn==pOp->p2 );
66735   assert( pOp->p1>0 );
66736   assert( pOp->p1+pOp->p2<=p->nMem+1 );
66737
66738   /* If this statement has violated immediate foreign key constraints, do
66739   ** not return the number of rows modified. And do not RELEASE the statement
66740   ** transaction. It needs to be rolled back.  */
66741   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
66742     assert( db->flags&SQLITE_CountRows );
66743     assert( p->usesStmtJournal );
66744     break;
66745   }
66746
66747   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
66748   ** DML statements invoke this opcode to return the number of rows
66749   ** modified to the user. This is the only way that a VM that
66750   ** opens a statement transaction may invoke this opcode.
66751   **
66752   ** In case this is such a statement, close any statement transaction
66753   ** opened by this VM before returning control to the user. This is to
66754   ** ensure that statement-transactions are always nested, not overlapping.
66755   ** If the open statement-transaction is not closed here, then the user
66756   ** may step another VM that opens its own statement transaction. This
66757   ** may lead to overlapping statement transactions.
66758   **
66759   ** The statement transaction is never a top-level transaction.  Hence
66760   ** the RELEASE call below can never fail.
66761   */
66762   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
66763   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
66764   if( NEVER(rc!=SQLITE_OK) ){
66765     break;
66766   }
66767
66768   /* Invalidate all ephemeral cursor row caches */
66769   p->cacheCtr = (p->cacheCtr + 2)|1;
66770
66771   /* Make sure the results of the current row are \000 terminated
66772   ** and have an assigned type.  The results are de-ephemeralized as
66773   ** a side effect.
66774   */
66775   u.af.pMem = p->pResultSet = &aMem[pOp->p1];
66776   for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
66777     assert( memIsValid(&u.af.pMem[u.af.i]) );
66778     Deephemeralize(&u.af.pMem[u.af.i]);
66779     assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
66780             || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
66781     sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
66782     sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
66783     REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
66784   }
66785   if( db->mallocFailed ) goto no_mem;
66786
66787   /* Return SQLITE_ROW
66788   */
66789   p->pc = pc + 1;
66790   rc = SQLITE_ROW;
66791   goto vdbe_return;
66792 }
66793
66794 /* Opcode: Concat P1 P2 P3 * *
66795 **
66796 ** Add the text in register P1 onto the end of the text in
66797 ** register P2 and store the result in register P3.
66798 ** If either the P1 or P2 text are NULL then store NULL in P3.
66799 **
66800 **   P3 = P2 || P1
66801 **
66802 ** It is illegal for P1 and P3 to be the same register. Sometimes,
66803 ** if P3 is the same register as P2, the implementation is able
66804 ** to avoid a memcpy().
66805 */
66806 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
66807 #if 0  /* local variables moved into u.ag */
66808   i64 nByte;
66809 #endif /* local variables moved into u.ag */
66810
66811   pIn1 = &aMem[pOp->p1];
66812   pIn2 = &aMem[pOp->p2];
66813   pOut = &aMem[pOp->p3];
66814   assert( pIn1!=pOut );
66815   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66816     sqlite3VdbeMemSetNull(pOut);
66817     break;
66818   }
66819   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66820   Stringify(pIn1, encoding);
66821   Stringify(pIn2, encoding);
66822   u.ag.nByte = pIn1->n + pIn2->n;
66823   if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66824     goto too_big;
66825   }
66826   MemSetTypeFlag(pOut, MEM_Str);
66827   if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
66828     goto no_mem;
66829   }
66830   if( pOut!=pIn2 ){
66831     memcpy(pOut->z, pIn2->z, pIn2->n);
66832   }
66833   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66834   pOut->z[u.ag.nByte] = 0;
66835   pOut->z[u.ag.nByte+1] = 0;
66836   pOut->flags |= MEM_Term;
66837   pOut->n = (int)u.ag.nByte;
66838   pOut->enc = encoding;
66839   UPDATE_MAX_BLOBSIZE(pOut);
66840   break;
66841 }
66842
66843 /* Opcode: Add P1 P2 P3 * *
66844 **
66845 ** Add the value in register P1 to the value in register P2
66846 ** and store the result in register P3.
66847 ** If either input is NULL, the result is NULL.
66848 */
66849 /* Opcode: Multiply P1 P2 P3 * *
66850 **
66851 **
66852 ** Multiply the value in register P1 by the value in register P2
66853 ** and store the result in register P3.
66854 ** If either input is NULL, the result is NULL.
66855 */
66856 /* Opcode: Subtract P1 P2 P3 * *
66857 **
66858 ** Subtract the value in register P1 from the value in register P2
66859 ** and store the result in register P3.
66860 ** If either input is NULL, the result is NULL.
66861 */
66862 /* Opcode: Divide P1 P2 P3 * *
66863 **
66864 ** Divide the value in register P1 by the value in register P2
66865 ** and store the result in register P3 (P3=P2/P1). If the value in
66866 ** register P1 is zero, then the result is NULL. If either input is
66867 ** NULL, the result is NULL.
66868 */
66869 /* Opcode: Remainder P1 P2 P3 * *
66870 **
66871 ** Compute the remainder after integer division of the value in
66872 ** register P1 by the value in register P2 and store the result in P3.
66873 ** If the value in register P2 is zero the result is NULL.
66874 ** If either operand is NULL, the result is NULL.
66875 */
66876 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66877 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66878 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66879 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66880 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66881 #if 0  /* local variables moved into u.ah */
66882   char bIntint;   /* Started out as two integer operands */
66883   int flags;      /* Combined MEM_* flags from both inputs */
66884   i64 iA;         /* Integer value of left operand */
66885   i64 iB;         /* Integer value of right operand */
66886   double rA;      /* Real value of left operand */
66887   double rB;      /* Real value of right operand */
66888 #endif /* local variables moved into u.ah */
66889
66890   pIn1 = &aMem[pOp->p1];
66891   applyNumericAffinity(pIn1);
66892   pIn2 = &aMem[pOp->p2];
66893   applyNumericAffinity(pIn2);
66894   pOut = &aMem[pOp->p3];
66895   u.ah.flags = pIn1->flags | pIn2->flags;
66896   if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66897   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66898     u.ah.iA = pIn1->u.i;
66899     u.ah.iB = pIn2->u.i;
66900     u.ah.bIntint = 1;
66901     switch( pOp->opcode ){
66902       case OP_Add:       if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66903       case OP_Subtract:  if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66904       case OP_Multiply:  if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66905       case OP_Divide: {
66906         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66907         if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
66908         u.ah.iB /= u.ah.iA;
66909         break;
66910       }
66911       default: {
66912         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66913         if( u.ah.iA==-1 ) u.ah.iA = 1;
66914         u.ah.iB %= u.ah.iA;
66915         break;
66916       }
66917     }
66918     pOut->u.i = u.ah.iB;
66919     MemSetTypeFlag(pOut, MEM_Int);
66920   }else{
66921     u.ah.bIntint = 0;
66922 fp_math:
66923     u.ah.rA = sqlite3VdbeRealValue(pIn1);
66924     u.ah.rB = sqlite3VdbeRealValue(pIn2);
66925     switch( pOp->opcode ){
66926       case OP_Add:         u.ah.rB += u.ah.rA;       break;
66927       case OP_Subtract:    u.ah.rB -= u.ah.rA;       break;
66928       case OP_Multiply:    u.ah.rB *= u.ah.rA;       break;
66929       case OP_Divide: {
66930         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
66931         if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
66932         u.ah.rB /= u.ah.rA;
66933         break;
66934       }
66935       default: {
66936         u.ah.iA = (i64)u.ah.rA;
66937         u.ah.iB = (i64)u.ah.rB;
66938         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66939         if( u.ah.iA==-1 ) u.ah.iA = 1;
66940         u.ah.rB = (double)(u.ah.iB % u.ah.iA);
66941         break;
66942       }
66943     }
66944 #ifdef SQLITE_OMIT_FLOATING_POINT
66945     pOut->u.i = u.ah.rB;
66946     MemSetTypeFlag(pOut, MEM_Int);
66947 #else
66948     if( sqlite3IsNaN(u.ah.rB) ){
66949       goto arithmetic_result_is_null;
66950     }
66951     pOut->r = u.ah.rB;
66952     MemSetTypeFlag(pOut, MEM_Real);
66953     if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
66954       sqlite3VdbeIntegerAffinity(pOut);
66955     }
66956 #endif
66957   }
66958   break;
66959
66960 arithmetic_result_is_null:
66961   sqlite3VdbeMemSetNull(pOut);
66962   break;
66963 }
66964
66965 /* Opcode: CollSeq P1 * * P4
66966 **
66967 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
66968 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
66969 ** be returned. This is used by the built-in min(), max() and nullif()
66970 ** functions.
66971 **
66972 ** If P1 is not zero, then it is a register that a subsequent min() or
66973 ** max() aggregate will set to 1 if the current row is not the minimum or
66974 ** maximum.  The P1 register is initialized to 0 by this instruction.
66975 **
66976 ** The interface used by the implementation of the aforementioned functions
66977 ** to retrieve the collation sequence set by this opcode is not available
66978 ** publicly, only to user functions defined in func.c.
66979 */
66980 case OP_CollSeq: {
66981   assert( pOp->p4type==P4_COLLSEQ );
66982   if( pOp->p1 ){
66983     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
66984   }
66985   break;
66986 }
66987
66988 /* Opcode: Function P1 P2 P3 P4 P5
66989 **
66990 ** Invoke a user function (P4 is a pointer to a Function structure that
66991 ** defines the function) with P5 arguments taken from register P2 and
66992 ** successors.  The result of the function is stored in register P3.
66993 ** Register P3 must not be one of the function inputs.
66994 **
66995 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
66996 ** function was determined to be constant at compile time. If the first
66997 ** argument was constant then bit 0 of P1 is set. This is used to determine
66998 ** whether meta data associated with a user function argument using the
66999 ** sqlite3_set_auxdata() API may be safely retained until the next
67000 ** invocation of this opcode.
67001 **
67002 ** See also: AggStep and AggFinal
67003 */
67004 case OP_Function: {
67005 #if 0  /* local variables moved into u.ai */
67006   int i;
67007   Mem *pArg;
67008   sqlite3_context ctx;
67009   sqlite3_value **apVal;
67010   int n;
67011 #endif /* local variables moved into u.ai */
67012
67013   u.ai.n = pOp->p5;
67014   u.ai.apVal = p->apArg;
67015   assert( u.ai.apVal || u.ai.n==0 );
67016   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67017   pOut = &aMem[pOp->p3];
67018   memAboutToChange(p, pOut);
67019
67020   assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
67021   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
67022   u.ai.pArg = &aMem[pOp->p2];
67023   for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
67024     assert( memIsValid(u.ai.pArg) );
67025     u.ai.apVal[u.ai.i] = u.ai.pArg;
67026     Deephemeralize(u.ai.pArg);
67027     sqlite3VdbeMemStoreType(u.ai.pArg);
67028     REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
67029   }
67030
67031   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
67032   if( pOp->p4type==P4_FUNCDEF ){
67033     u.ai.ctx.pFunc = pOp->p4.pFunc;
67034     u.ai.ctx.pVdbeFunc = 0;
67035   }else{
67036     u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
67037     u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
67038   }
67039
67040   u.ai.ctx.s.flags = MEM_Null;
67041   u.ai.ctx.s.db = db;
67042   u.ai.ctx.s.xDel = 0;
67043   u.ai.ctx.s.zMalloc = 0;
67044
67045   /* The output cell may already have a buffer allocated. Move
67046   ** the pointer to u.ai.ctx.s so in case the user-function can use
67047   ** the already allocated buffer instead of allocating a new one.
67048   */
67049   sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
67050   MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
67051
67052   u.ai.ctx.isError = 0;
67053   if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
67054     assert( pOp>aOp );
67055     assert( pOp[-1].p4type==P4_COLLSEQ );
67056     assert( pOp[-1].opcode==OP_CollSeq );
67057     u.ai.ctx.pColl = pOp[-1].p4.pColl;
67058   }
67059   db->lastRowid = lastRowid;
67060   (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
67061   lastRowid = db->lastRowid;
67062
67063   /* If any auxiliary data functions have been called by this user function,
67064   ** immediately call the destructor for any non-static values.
67065   */
67066   if( u.ai.ctx.pVdbeFunc ){
67067     sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
67068     pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
67069     pOp->p4type = P4_VDBEFUNC;
67070   }
67071
67072   if( db->mallocFailed ){
67073     /* Even though a malloc() has failed, the implementation of the
67074     ** user function may have called an sqlite3_result_XXX() function
67075     ** to return a value. The following call releases any resources
67076     ** associated with such a value.
67077     */
67078     sqlite3VdbeMemRelease(&u.ai.ctx.s);
67079     goto no_mem;
67080   }
67081
67082   /* If the function returned an error, throw an exception */
67083   if( u.ai.ctx.isError ){
67084     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
67085     rc = u.ai.ctx.isError;
67086   }
67087
67088   /* Copy the result of the function into register P3 */
67089   sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
67090   sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
67091   if( sqlite3VdbeMemTooBig(pOut) ){
67092     goto too_big;
67093   }
67094
67095 #if 0
67096   /* The app-defined function has done something that as caused this
67097   ** statement to expire.  (Perhaps the function called sqlite3_exec()
67098   ** with a CREATE TABLE statement.)
67099   */
67100   if( p->expired ) rc = SQLITE_ABORT;
67101 #endif
67102
67103   REGISTER_TRACE(pOp->p3, pOut);
67104   UPDATE_MAX_BLOBSIZE(pOut);
67105   break;
67106 }
67107
67108 /* Opcode: BitAnd P1 P2 P3 * *
67109 **
67110 ** Take the bit-wise AND of the values in register P1 and P2 and
67111 ** store the result in register P3.
67112 ** If either input is NULL, the result is NULL.
67113 */
67114 /* Opcode: BitOr P1 P2 P3 * *
67115 **
67116 ** Take the bit-wise OR of the values in register P1 and P2 and
67117 ** store the result in register P3.
67118 ** If either input is NULL, the result is NULL.
67119 */
67120 /* Opcode: ShiftLeft P1 P2 P3 * *
67121 **
67122 ** Shift the integer value in register P2 to the left by the
67123 ** number of bits specified by the integer in register P1.
67124 ** Store the result in register P3.
67125 ** If either input is NULL, the result is NULL.
67126 */
67127 /* Opcode: ShiftRight P1 P2 P3 * *
67128 **
67129 ** Shift the integer value in register P2 to the right by the
67130 ** number of bits specified by the integer in register P1.
67131 ** Store the result in register P3.
67132 ** If either input is NULL, the result is NULL.
67133 */
67134 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
67135 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
67136 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
67137 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
67138 #if 0  /* local variables moved into u.aj */
67139   i64 iA;
67140   u64 uA;
67141   i64 iB;
67142   u8 op;
67143 #endif /* local variables moved into u.aj */
67144
67145   pIn1 = &aMem[pOp->p1];
67146   pIn2 = &aMem[pOp->p2];
67147   pOut = &aMem[pOp->p3];
67148   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
67149     sqlite3VdbeMemSetNull(pOut);
67150     break;
67151   }
67152   u.aj.iA = sqlite3VdbeIntValue(pIn2);
67153   u.aj.iB = sqlite3VdbeIntValue(pIn1);
67154   u.aj.op = pOp->opcode;
67155   if( u.aj.op==OP_BitAnd ){
67156     u.aj.iA &= u.aj.iB;
67157   }else if( u.aj.op==OP_BitOr ){
67158     u.aj.iA |= u.aj.iB;
67159   }else if( u.aj.iB!=0 ){
67160     assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
67161
67162     /* If shifting by a negative amount, shift in the other direction */
67163     if( u.aj.iB<0 ){
67164       assert( OP_ShiftRight==OP_ShiftLeft+1 );
67165       u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
67166       u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
67167     }
67168
67169     if( u.aj.iB>=64 ){
67170       u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
67171     }else{
67172       memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
67173       if( u.aj.op==OP_ShiftLeft ){
67174         u.aj.uA <<= u.aj.iB;
67175       }else{
67176         u.aj.uA >>= u.aj.iB;
67177         /* Sign-extend on a right shift of a negative number */
67178         if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
67179       }
67180       memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
67181     }
67182   }
67183   pOut->u.i = u.aj.iA;
67184   MemSetTypeFlag(pOut, MEM_Int);
67185   break;
67186 }
67187
67188 /* Opcode: AddImm  P1 P2 * * *
67189 **
67190 ** Add the constant P2 to the value in register P1.
67191 ** The result is always an integer.
67192 **
67193 ** To force any register to be an integer, just add 0.
67194 */
67195 case OP_AddImm: {            /* in1 */
67196   pIn1 = &aMem[pOp->p1];
67197   memAboutToChange(p, pIn1);
67198   sqlite3VdbeMemIntegerify(pIn1);
67199   pIn1->u.i += pOp->p2;
67200   break;
67201 }
67202
67203 /* Opcode: MustBeInt P1 P2 * * *
67204 **
67205 ** Force the value in register P1 to be an integer.  If the value
67206 ** in P1 is not an integer and cannot be converted into an integer
67207 ** without data loss, then jump immediately to P2, or if P2==0
67208 ** raise an SQLITE_MISMATCH exception.
67209 */
67210 case OP_MustBeInt: {            /* jump, in1 */
67211   pIn1 = &aMem[pOp->p1];
67212   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
67213   if( (pIn1->flags & MEM_Int)==0 ){
67214     if( pOp->p2==0 ){
67215       rc = SQLITE_MISMATCH;
67216       goto abort_due_to_error;
67217     }else{
67218       pc = pOp->p2 - 1;
67219     }
67220   }else{
67221     MemSetTypeFlag(pIn1, MEM_Int);
67222   }
67223   break;
67224 }
67225
67226 #ifndef SQLITE_OMIT_FLOATING_POINT
67227 /* Opcode: RealAffinity P1 * * * *
67228 **
67229 ** If register P1 holds an integer convert it to a real value.
67230 **
67231 ** This opcode is used when extracting information from a column that
67232 ** has REAL affinity.  Such column values may still be stored as
67233 ** integers, for space efficiency, but after extraction we want them
67234 ** to have only a real value.
67235 */
67236 case OP_RealAffinity: {                  /* in1 */
67237   pIn1 = &aMem[pOp->p1];
67238   if( pIn1->flags & MEM_Int ){
67239     sqlite3VdbeMemRealify(pIn1);
67240   }
67241   break;
67242 }
67243 #endif
67244
67245 #ifndef SQLITE_OMIT_CAST
67246 /* Opcode: ToText P1 * * * *
67247 **
67248 ** Force the value in register P1 to be text.
67249 ** If the value is numeric, convert it to a string using the
67250 ** equivalent of printf().  Blob values are unchanged and
67251 ** are afterwards simply interpreted as text.
67252 **
67253 ** A NULL value is not changed by this routine.  It remains NULL.
67254 */
67255 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
67256   pIn1 = &aMem[pOp->p1];
67257   memAboutToChange(p, pIn1);
67258   if( pIn1->flags & MEM_Null ) break;
67259   assert( MEM_Str==(MEM_Blob>>3) );
67260   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
67261   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67262   rc = ExpandBlob(pIn1);
67263   assert( pIn1->flags & MEM_Str || db->mallocFailed );
67264   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
67265   UPDATE_MAX_BLOBSIZE(pIn1);
67266   break;
67267 }
67268
67269 /* Opcode: ToBlob P1 * * * *
67270 **
67271 ** Force the value in register P1 to be a BLOB.
67272 ** If the value is numeric, convert it to a string first.
67273 ** Strings are simply reinterpreted as blobs with no change
67274 ** to the underlying data.
67275 **
67276 ** A NULL value is not changed by this routine.  It remains NULL.
67277 */
67278 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
67279   pIn1 = &aMem[pOp->p1];
67280   if( pIn1->flags & MEM_Null ) break;
67281   if( (pIn1->flags & MEM_Blob)==0 ){
67282     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67283     assert( pIn1->flags & MEM_Str || db->mallocFailed );
67284     MemSetTypeFlag(pIn1, MEM_Blob);
67285   }else{
67286     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
67287   }
67288   UPDATE_MAX_BLOBSIZE(pIn1);
67289   break;
67290 }
67291
67292 /* Opcode: ToNumeric P1 * * * *
67293 **
67294 ** Force the value in register P1 to be numeric (either an
67295 ** integer or a floating-point number.)
67296 ** If the value is text or blob, try to convert it to an using the
67297 ** equivalent of atoi() or atof() and store 0 if no such conversion
67298 ** is possible.
67299 **
67300 ** A NULL value is not changed by this routine.  It remains NULL.
67301 */
67302 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
67303   pIn1 = &aMem[pOp->p1];
67304   sqlite3VdbeMemNumerify(pIn1);
67305   break;
67306 }
67307 #endif /* SQLITE_OMIT_CAST */
67308
67309 /* Opcode: ToInt P1 * * * *
67310 **
67311 ** Force the value in register P1 to be an integer.  If
67312 ** The value is currently a real number, drop its fractional part.
67313 ** If the value is text or blob, try to convert it to an integer using the
67314 ** equivalent of atoi() and store 0 if no such conversion is possible.
67315 **
67316 ** A NULL value is not changed by this routine.  It remains NULL.
67317 */
67318 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
67319   pIn1 = &aMem[pOp->p1];
67320   if( (pIn1->flags & MEM_Null)==0 ){
67321     sqlite3VdbeMemIntegerify(pIn1);
67322   }
67323   break;
67324 }
67325
67326 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
67327 /* Opcode: ToReal P1 * * * *
67328 **
67329 ** Force the value in register P1 to be a floating point number.
67330 ** If The value is currently an integer, convert it.
67331 ** If the value is text or blob, try to convert it to an integer using the
67332 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
67333 **
67334 ** A NULL value is not changed by this routine.  It remains NULL.
67335 */
67336 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
67337   pIn1 = &aMem[pOp->p1];
67338   memAboutToChange(p, pIn1);
67339   if( (pIn1->flags & MEM_Null)==0 ){
67340     sqlite3VdbeMemRealify(pIn1);
67341   }
67342   break;
67343 }
67344 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
67345
67346 /* Opcode: Lt P1 P2 P3 P4 P5
67347 **
67348 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
67349 ** jump to address P2.
67350 **
67351 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
67352 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
67353 ** bit is clear then fall through if either operand is NULL.
67354 **
67355 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
67356 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
67357 ** to coerce both inputs according to this affinity before the
67358 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
67359 ** affinity is used. Note that the affinity conversions are stored
67360 ** back into the input registers P1 and P3.  So this opcode can cause
67361 ** persistent changes to registers P1 and P3.
67362 **
67363 ** Once any conversions have taken place, and neither value is NULL,
67364 ** the values are compared. If both values are blobs then memcmp() is
67365 ** used to determine the results of the comparison.  If both values
67366 ** are text, then the appropriate collating function specified in
67367 ** P4 is  used to do the comparison.  If P4 is not specified then
67368 ** memcmp() is used to compare text string.  If both values are
67369 ** numeric, then a numeric comparison is used. If the two values
67370 ** are of different types, then numbers are considered less than
67371 ** strings and strings are considered less than blobs.
67372 **
67373 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
67374 ** store a boolean result (either 0, or 1, or NULL) in register P2.
67375 **
67376 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
67377 ** equal to one another, provided that they do not have their MEM_Cleared
67378 ** bit set.
67379 */
67380 /* Opcode: Ne P1 P2 P3 P4 P5
67381 **
67382 ** This works just like the Lt opcode except that the jump is taken if
67383 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
67384 ** additional information.
67385 **
67386 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67387 ** true or false and is never NULL.  If both operands are NULL then the result
67388 ** of comparison is false.  If either operand is NULL then the result is true.
67389 ** If neither operand is NULL the result is the same as it would be if
67390 ** the SQLITE_NULLEQ flag were omitted from P5.
67391 */
67392 /* Opcode: Eq P1 P2 P3 P4 P5
67393 **
67394 ** This works just like the Lt opcode except that the jump is taken if
67395 ** the operands in registers P1 and P3 are equal.
67396 ** See the Lt opcode for additional information.
67397 **
67398 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67399 ** true or false and is never NULL.  If both operands are NULL then the result
67400 ** of comparison is true.  If either operand is NULL then the result is false.
67401 ** If neither operand is NULL the result is the same as it would be if
67402 ** the SQLITE_NULLEQ flag were omitted from P5.
67403 */
67404 /* Opcode: Le P1 P2 P3 P4 P5
67405 **
67406 ** This works just like the Lt opcode except that the jump is taken if
67407 ** the content of register P3 is less than or equal to the content of
67408 ** register P1.  See the Lt opcode for additional information.
67409 */
67410 /* Opcode: Gt P1 P2 P3 P4 P5
67411 **
67412 ** This works just like the Lt opcode except that the jump is taken if
67413 ** the content of register P3 is greater than the content of
67414 ** register P1.  See the Lt opcode for additional information.
67415 */
67416 /* Opcode: Ge P1 P2 P3 P4 P5
67417 **
67418 ** This works just like the Lt opcode except that the jump is taken if
67419 ** the content of register P3 is greater than or equal to the content of
67420 ** register P1.  See the Lt opcode for additional information.
67421 */
67422 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
67423 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
67424 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
67425 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
67426 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
67427 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
67428 #if 0  /* local variables moved into u.ak */
67429   int res;            /* Result of the comparison of pIn1 against pIn3 */
67430   char affinity;      /* Affinity to use for comparison */
67431   u16 flags1;         /* Copy of initial value of pIn1->flags */
67432   u16 flags3;         /* Copy of initial value of pIn3->flags */
67433 #endif /* local variables moved into u.ak */
67434
67435   pIn1 = &aMem[pOp->p1];
67436   pIn3 = &aMem[pOp->p3];
67437   u.ak.flags1 = pIn1->flags;
67438   u.ak.flags3 = pIn3->flags;
67439   if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
67440     /* One or both operands are NULL */
67441     if( pOp->p5 & SQLITE_NULLEQ ){
67442       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
67443       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
67444       ** or not both operands are null.
67445       */
67446       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
67447       assert( (u.ak.flags1 & MEM_Cleared)==0 );
67448       if( (u.ak.flags1&MEM_Null)!=0
67449        && (u.ak.flags3&MEM_Null)!=0
67450        && (u.ak.flags3&MEM_Cleared)==0
67451       ){
67452         u.ak.res = 0;  /* Results are equal */
67453       }else{
67454         u.ak.res = 1;  /* Results are not equal */
67455       }
67456     }else{
67457       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
67458       ** then the result is always NULL.
67459       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
67460       */
67461       if( pOp->p5 & SQLITE_STOREP2 ){
67462         pOut = &aMem[pOp->p2];
67463         MemSetTypeFlag(pOut, MEM_Null);
67464         REGISTER_TRACE(pOp->p2, pOut);
67465       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
67466         pc = pOp->p2-1;
67467       }
67468       break;
67469     }
67470   }else{
67471     /* Neither operand is NULL.  Do a comparison. */
67472     u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
67473     if( u.ak.affinity ){
67474       applyAffinity(pIn1, u.ak.affinity, encoding);
67475       applyAffinity(pIn3, u.ak.affinity, encoding);
67476       if( db->mallocFailed ) goto no_mem;
67477     }
67478
67479     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
67480     ExpandBlob(pIn1);
67481     ExpandBlob(pIn3);
67482     u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
67483   }
67484   switch( pOp->opcode ){
67485     case OP_Eq:    u.ak.res = u.ak.res==0;     break;
67486     case OP_Ne:    u.ak.res = u.ak.res!=0;     break;
67487     case OP_Lt:    u.ak.res = u.ak.res<0;      break;
67488     case OP_Le:    u.ak.res = u.ak.res<=0;     break;
67489     case OP_Gt:    u.ak.res = u.ak.res>0;      break;
67490     default:       u.ak.res = u.ak.res>=0;     break;
67491   }
67492
67493   if( pOp->p5 & SQLITE_STOREP2 ){
67494     pOut = &aMem[pOp->p2];
67495     memAboutToChange(p, pOut);
67496     MemSetTypeFlag(pOut, MEM_Int);
67497     pOut->u.i = u.ak.res;
67498     REGISTER_TRACE(pOp->p2, pOut);
67499   }else if( u.ak.res ){
67500     pc = pOp->p2-1;
67501   }
67502
67503   /* Undo any changes made by applyAffinity() to the input registers. */
67504   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
67505   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
67506   break;
67507 }
67508
67509 /* Opcode: Permutation * * * P4 *
67510 **
67511 ** Set the permutation used by the OP_Compare operator to be the array
67512 ** of integers in P4.
67513 **
67514 ** The permutation is only valid until the next OP_Compare that has
67515 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
67516 ** occur immediately prior to the OP_Compare.
67517 */
67518 case OP_Permutation: {
67519   assert( pOp->p4type==P4_INTARRAY );
67520   assert( pOp->p4.ai );
67521   aPermute = pOp->p4.ai;
67522   break;
67523 }
67524
67525 /* Opcode: Compare P1 P2 P3 P4 P5
67526 **
67527 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
67528 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
67529 ** the comparison for use by the next OP_Jump instruct.
67530 **
67531 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
67532 ** determined by the most recent OP_Permutation operator.  If the
67533 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
67534 ** order.
67535 **
67536 ** P4 is a KeyInfo structure that defines collating sequences and sort
67537 ** orders for the comparison.  The permutation applies to registers
67538 ** only.  The KeyInfo elements are used sequentially.
67539 **
67540 ** The comparison is a sort comparison, so NULLs compare equal,
67541 ** NULLs are less than numbers, numbers are less than strings,
67542 ** and strings are less than blobs.
67543 */
67544 case OP_Compare: {
67545 #if 0  /* local variables moved into u.al */
67546   int n;
67547   int i;
67548   int p1;
67549   int p2;
67550   const KeyInfo *pKeyInfo;
67551   int idx;
67552   CollSeq *pColl;    /* Collating sequence to use on this term */
67553   int bRev;          /* True for DESCENDING sort order */
67554 #endif /* local variables moved into u.al */
67555
67556   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
67557   u.al.n = pOp->p3;
67558   u.al.pKeyInfo = pOp->p4.pKeyInfo;
67559   assert( u.al.n>0 );
67560   assert( u.al.pKeyInfo!=0 );
67561   u.al.p1 = pOp->p1;
67562   u.al.p2 = pOp->p2;
67563 #if SQLITE_DEBUG
67564   if( aPermute ){
67565     int k, mx = 0;
67566     for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
67567     assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
67568     assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
67569   }else{
67570     assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
67571     assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
67572   }
67573 #endif /* SQLITE_DEBUG */
67574   for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
67575     u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
67576     assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
67577     assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
67578     REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
67579     REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
67580     assert( u.al.i<u.al.pKeyInfo->nField );
67581     u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
67582     u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
67583     iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
67584     if( iCompare ){
67585       if( u.al.bRev ) iCompare = -iCompare;
67586       break;
67587     }
67588   }
67589   aPermute = 0;
67590   break;
67591 }
67592
67593 /* Opcode: Jump P1 P2 P3 * *
67594 **
67595 ** Jump to the instruction at address P1, P2, or P3 depending on whether
67596 ** in the most recent OP_Compare instruction the P1 vector was less than
67597 ** equal to, or greater than the P2 vector, respectively.
67598 */
67599 case OP_Jump: {             /* jump */
67600   if( iCompare<0 ){
67601     pc = pOp->p1 - 1;
67602   }else if( iCompare==0 ){
67603     pc = pOp->p2 - 1;
67604   }else{
67605     pc = pOp->p3 - 1;
67606   }
67607   break;
67608 }
67609
67610 /* Opcode: And P1 P2 P3 * *
67611 **
67612 ** Take the logical AND of the values in registers P1 and P2 and
67613 ** write the result into register P3.
67614 **
67615 ** If either P1 or P2 is 0 (false) then the result is 0 even if
67616 ** the other input is NULL.  A NULL and true or two NULLs give
67617 ** a NULL output.
67618 */
67619 /* Opcode: Or P1 P2 P3 * *
67620 **
67621 ** Take the logical OR of the values in register P1 and P2 and
67622 ** store the answer in register P3.
67623 **
67624 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
67625 ** even if the other input is NULL.  A NULL and false or two NULLs
67626 ** give a NULL output.
67627 */
67628 case OP_And:              /* same as TK_AND, in1, in2, out3 */
67629 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
67630 #if 0  /* local variables moved into u.am */
67631   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67632   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67633 #endif /* local variables moved into u.am */
67634
67635   pIn1 = &aMem[pOp->p1];
67636   if( pIn1->flags & MEM_Null ){
67637     u.am.v1 = 2;
67638   }else{
67639     u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
67640   }
67641   pIn2 = &aMem[pOp->p2];
67642   if( pIn2->flags & MEM_Null ){
67643     u.am.v2 = 2;
67644   }else{
67645     u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
67646   }
67647   if( pOp->opcode==OP_And ){
67648     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
67649     u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
67650   }else{
67651     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
67652     u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
67653   }
67654   pOut = &aMem[pOp->p3];
67655   if( u.am.v1==2 ){
67656     MemSetTypeFlag(pOut, MEM_Null);
67657   }else{
67658     pOut->u.i = u.am.v1;
67659     MemSetTypeFlag(pOut, MEM_Int);
67660   }
67661   break;
67662 }
67663
67664 /* Opcode: Not P1 P2 * * *
67665 **
67666 ** Interpret the value in register P1 as a boolean value.  Store the
67667 ** boolean complement in register P2.  If the value in register P1 is
67668 ** NULL, then a NULL is stored in P2.
67669 */
67670 case OP_Not: {                /* same as TK_NOT, in1, out2 */
67671   pIn1 = &aMem[pOp->p1];
67672   pOut = &aMem[pOp->p2];
67673   if( pIn1->flags & MEM_Null ){
67674     sqlite3VdbeMemSetNull(pOut);
67675   }else{
67676     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
67677   }
67678   break;
67679 }
67680
67681 /* Opcode: BitNot P1 P2 * * *
67682 **
67683 ** Interpret the content of register P1 as an integer.  Store the
67684 ** ones-complement of the P1 value into register P2.  If P1 holds
67685 ** a NULL then store a NULL in P2.
67686 */
67687 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
67688   pIn1 = &aMem[pOp->p1];
67689   pOut = &aMem[pOp->p2];
67690   if( pIn1->flags & MEM_Null ){
67691     sqlite3VdbeMemSetNull(pOut);
67692   }else{
67693     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
67694   }
67695   break;
67696 }
67697
67698 /* Opcode: Once P1 P2 * * *
67699 **
67700 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
67701 ** set the flag and fall through to the next instruction.
67702 */
67703 case OP_Once: {             /* jump */
67704   assert( pOp->p1<p->nOnceFlag );
67705   if( p->aOnceFlag[pOp->p1] ){
67706     pc = pOp->p2-1;
67707   }else{
67708     p->aOnceFlag[pOp->p1] = 1;
67709   }
67710   break;
67711 }
67712
67713 /* Opcode: If P1 P2 P3 * *
67714 **
67715 ** Jump to P2 if the value in register P1 is true.  The value
67716 ** is considered true if it is numeric and non-zero.  If the value
67717 ** in P1 is NULL then take the jump if P3 is non-zero.
67718 */
67719 /* Opcode: IfNot P1 P2 P3 * *
67720 **
67721 ** Jump to P2 if the value in register P1 is False.  The value
67722 ** is considered false if it has a numeric value of zero.  If the value
67723 ** in P1 is NULL then take the jump if P3 is zero.
67724 */
67725 case OP_If:                 /* jump, in1 */
67726 case OP_IfNot: {            /* jump, in1 */
67727 #if 0  /* local variables moved into u.an */
67728   int c;
67729 #endif /* local variables moved into u.an */
67730   pIn1 = &aMem[pOp->p1];
67731   if( pIn1->flags & MEM_Null ){
67732     u.an.c = pOp->p3;
67733   }else{
67734 #ifdef SQLITE_OMIT_FLOATING_POINT
67735     u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
67736 #else
67737     u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
67738 #endif
67739     if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
67740   }
67741   if( u.an.c ){
67742     pc = pOp->p2-1;
67743   }
67744   break;
67745 }
67746
67747 /* Opcode: IsNull P1 P2 * * *
67748 **
67749 ** Jump to P2 if the value in register P1 is NULL.
67750 */
67751 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
67752   pIn1 = &aMem[pOp->p1];
67753   if( (pIn1->flags & MEM_Null)!=0 ){
67754     pc = pOp->p2 - 1;
67755   }
67756   break;
67757 }
67758
67759 /* Opcode: NotNull P1 P2 * * *
67760 **
67761 ** Jump to P2 if the value in register P1 is not NULL.
67762 */
67763 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
67764   pIn1 = &aMem[pOp->p1];
67765   if( (pIn1->flags & MEM_Null)==0 ){
67766     pc = pOp->p2 - 1;
67767   }
67768   break;
67769 }
67770
67771 /* Opcode: Column P1 P2 P3 P4 P5
67772 **
67773 ** Interpret the data that cursor P1 points to as a structure built using
67774 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
67775 ** information about the format of the data.)  Extract the P2-th column
67776 ** from this record.  If there are less that (P2+1)
67777 ** values in the record, extract a NULL.
67778 **
67779 ** The value extracted is stored in register P3.
67780 **
67781 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
67782 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
67783 ** the result.
67784 **
67785 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
67786 ** then the cache of the cursor is reset prior to extracting the column.
67787 ** The first OP_Column against a pseudo-table after the value of the content
67788 ** register has changed should have this bit set.
67789 **
67790 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
67791 ** the result is guaranteed to only be used as the argument of a length()
67792 ** or typeof() function, respectively.  The loading of large blobs can be
67793 ** skipped for length() and all content loading can be skipped for typeof().
67794 */
67795 case OP_Column: {
67796 #if 0  /* local variables moved into u.ao */
67797   u32 payloadSize;   /* Number of bytes in the record */
67798   i64 payloadSize64; /* Number of bytes in the record */
67799   int p1;            /* P1 value of the opcode */
67800   int p2;            /* column number to retrieve */
67801   VdbeCursor *pC;    /* The VDBE cursor */
67802   char *zRec;        /* Pointer to complete record-data */
67803   BtCursor *pCrsr;   /* The BTree cursor */
67804   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
67805   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
67806   int nField;        /* number of fields in the record */
67807   int len;           /* The length of the serialized data for the column */
67808   int i;             /* Loop counter */
67809   char *zData;       /* Part of the record being decoded */
67810   Mem *pDest;        /* Where to write the extracted value */
67811   Mem sMem;          /* For storing the record being decoded */
67812   u8 *zIdx;          /* Index into header */
67813   u8 *zEndHdr;       /* Pointer to first byte after the header */
67814   u32 offset;        /* Offset into the data */
67815   u32 szField;       /* Number of bytes in the content of a field */
67816   int szHdr;         /* Size of the header size field at start of record */
67817   int avail;         /* Number of bytes of available data */
67818   u32 t;             /* A type code from the record header */
67819   Mem *pReg;         /* PseudoTable input register */
67820 #endif /* local variables moved into u.ao */
67821
67822
67823   u.ao.p1 = pOp->p1;
67824   u.ao.p2 = pOp->p2;
67825   u.ao.pC = 0;
67826   memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
67827   assert( u.ao.p1<p->nCursor );
67828   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67829   u.ao.pDest = &aMem[pOp->p3];
67830   memAboutToChange(p, u.ao.pDest);
67831   u.ao.zRec = 0;
67832
67833   /* This block sets the variable u.ao.payloadSize to be the total number of
67834   ** bytes in the record.
67835   **
67836   ** u.ao.zRec is set to be the complete text of the record if it is available.
67837   ** The complete record text is always available for pseudo-tables
67838   ** If the record is stored in a cursor, the complete record text
67839   ** might be available in the  u.ao.pC->aRow cache.  Or it might not be.
67840   ** If the data is unavailable,  u.ao.zRec is set to NULL.
67841   **
67842   ** We also compute the number of columns in the record.  For cursors,
67843   ** the number of columns is stored in the VdbeCursor.nField element.
67844   */
67845   u.ao.pC = p->apCsr[u.ao.p1];
67846   assert( u.ao.pC!=0 );
67847 #ifndef SQLITE_OMIT_VIRTUALTABLE
67848   assert( u.ao.pC->pVtabCursor==0 );
67849 #endif
67850   u.ao.pCrsr = u.ao.pC->pCursor;
67851   if( u.ao.pCrsr!=0 ){
67852     /* The record is stored in a B-Tree */
67853     rc = sqlite3VdbeCursorMoveto(u.ao.pC);
67854     if( rc ) goto abort_due_to_error;
67855     if( u.ao.pC->nullRow ){
67856       u.ao.payloadSize = 0;
67857     }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
67858       u.ao.payloadSize = u.ao.pC->payloadSize;
67859       u.ao.zRec = (char*)u.ao.pC->aRow;
67860     }else if( u.ao.pC->isIndex ){
67861       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67862       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
67863       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
67864       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
67865       ** payload size, so it is impossible for u.ao.payloadSize64 to be
67866       ** larger than 32 bits. */
67867       assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
67868       u.ao.payloadSize = (u32)u.ao.payloadSize64;
67869     }else{
67870       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67871       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
67872       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
67873     }
67874   }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
67875     u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
67876     if( u.ao.pC->multiPseudo ){
67877       sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
67878       Deephemeralize(u.ao.pDest);
67879       goto op_column_out;
67880     }
67881     assert( u.ao.pReg->flags & MEM_Blob );
67882     assert( memIsValid(u.ao.pReg) );
67883     u.ao.payloadSize = u.ao.pReg->n;
67884     u.ao.zRec = u.ao.pReg->z;
67885     u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67886     assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
67887   }else{
67888     /* Consider the row to be NULL */
67889     u.ao.payloadSize = 0;
67890   }
67891
67892   /* If u.ao.payloadSize is 0, then just store a NULL.  This can happen because of
67893   ** nullRow or because of a corrupt database. */
67894   if( u.ao.payloadSize==0 ){
67895     MemSetTypeFlag(u.ao.pDest, MEM_Null);
67896     goto op_column_out;
67897   }
67898   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
67899   if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67900     goto too_big;
67901   }
67902
67903   u.ao.nField = u.ao.pC->nField;
67904   assert( u.ao.p2<u.ao.nField );
67905
67906   /* Read and parse the table header.  Store the results of the parse
67907   ** into the record header cache fields of the cursor.
67908   */
67909   u.ao.aType = u.ao.pC->aType;
67910   if( u.ao.pC->cacheStatus==p->cacheCtr ){
67911     u.ao.aOffset = u.ao.pC->aOffset;
67912   }else{
67913     assert(u.ao.aType);
67914     u.ao.avail = 0;
67915     u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
67916     u.ao.pC->payloadSize = u.ao.payloadSize;
67917     u.ao.pC->cacheStatus = p->cacheCtr;
67918
67919     /* Figure out how many bytes are in the header */
67920     if( u.ao.zRec ){
67921       u.ao.zData = u.ao.zRec;
67922     }else{
67923       if( u.ao.pC->isIndex ){
67924         u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
67925       }else{
67926         u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
67927       }
67928       /* If KeyFetch()/DataFetch() managed to get the entire payload,
67929       ** save the payload in the u.ao.pC->aRow cache.  That will save us from
67930       ** having to make additional calls to fetch the content portion of
67931       ** the record.
67932       */
67933       assert( u.ao.avail>=0 );
67934       if( u.ao.payloadSize <= (u32)u.ao.avail ){
67935         u.ao.zRec = u.ao.zData;
67936         u.ao.pC->aRow = (u8*)u.ao.zData;
67937       }else{
67938         u.ao.pC->aRow = 0;
67939       }
67940     }
67941     /* The following assert is true in all cases except when
67942     ** the database file has been corrupted externally.
67943     **    assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
67944     u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
67945
67946     /* Make sure a corrupt database has not given us an oversize header.
67947     ** Do this now to avoid an oversize memory allocation.
67948     **
67949     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
67950     ** types use so much data space that there can only be 4096 and 32 of
67951     ** them, respectively.  So the maximum header length results from a
67952     ** 3-byte type for each of the maximum of 32768 columns plus three
67953     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
67954     */
67955     if( u.ao.offset > 98307 ){
67956       rc = SQLITE_CORRUPT_BKPT;
67957       goto op_column_out;
67958     }
67959
67960     /* Compute in u.ao.len the number of bytes of data we need to read in order
67961     ** to get u.ao.nField type values.  u.ao.offset is an upper bound on this.  But
67962     ** u.ao.nField might be significantly less than the true number of columns
67963     ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
67964     ** We want to minimize u.ao.len in order to limit the size of the memory
67965     ** allocation, especially if a corrupt database file has caused u.ao.offset
67966     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
67967     ** still exceed Robson memory allocation limits on some configurations.
67968     ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
67969     ** will likely be much smaller since u.ao.nField will likely be less than
67970     ** 20 or so.  This insures that Robson memory allocation limits are
67971     ** not exceeded even for corrupt database files.
67972     */
67973     u.ao.len = u.ao.nField*5 + 3;
67974     if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
67975
67976     /* The KeyFetch() or DataFetch() above are fast and will get the entire
67977     ** record header in most cases.  But they will fail to get the complete
67978     ** record header if the record header does not fit on a single page
67979     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
67980     ** acquire the complete header text.
67981     */
67982     if( !u.ao.zRec && u.ao.avail<u.ao.len ){
67983       u.ao.sMem.flags = 0;
67984       u.ao.sMem.db = 0;
67985       rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
67986       if( rc!=SQLITE_OK ){
67987         goto op_column_out;
67988       }
67989       u.ao.zData = u.ao.sMem.z;
67990     }
67991     u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
67992     u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
67993
67994     /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
67995     ** arrays.  u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
67996     ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
67997     ** of the record to the start of the data for the u.ao.i-th column
67998     */
67999     for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
68000       if( u.ao.zIdx<u.ao.zEndHdr ){
68001         u.ao.aOffset[u.ao.i] = u.ao.offset;
68002         if( u.ao.zIdx[0]<0x80 ){
68003           u.ao.t = u.ao.zIdx[0];
68004           u.ao.zIdx++;
68005         }else{
68006           u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
68007         }
68008         u.ao.aType[u.ao.i] = u.ao.t;
68009         u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
68010         u.ao.offset += u.ao.szField;
68011         if( u.ao.offset<u.ao.szField ){  /* True if u.ao.offset overflows */
68012           u.ao.zIdx = &u.ao.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
68013           break;
68014         }
68015       }else{
68016         /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
68017         ** record than SetNumColumns indicated there are columns in the
68018         ** table. Set the u.ao.offset for any extra columns not present in
68019         ** the record to 0. This tells code below to store the default value
68020         ** for the column instead of deserializing a value from the record.
68021         */
68022         u.ao.aOffset[u.ao.i] = 0;
68023       }
68024     }
68025     sqlite3VdbeMemRelease(&u.ao.sMem);
68026     u.ao.sMem.flags = MEM_Null;
68027
68028     /* If we have read more header data than was contained in the header,
68029     ** or if the end of the last field appears to be past the end of the
68030     ** record, or if the end of the last field appears to be before the end
68031     ** of the record (when all fields present), then we must be dealing
68032     ** with a corrupt database.
68033     */
68034     if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
68035          || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
68036       rc = SQLITE_CORRUPT_BKPT;
68037       goto op_column_out;
68038     }
68039   }
68040
68041   /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
68042   ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
68043   ** then there are not enough fields in the record to satisfy the
68044   ** request.  In this case, set the value NULL or to P4 if P4 is
68045   ** a pointer to a Mem object.
68046   */
68047   if( u.ao.aOffset[u.ao.p2] ){
68048     assert( rc==SQLITE_OK );
68049     if( u.ao.zRec ){
68050       /* This is the common case where the whole row fits on a single page */
68051       VdbeMemRelease(u.ao.pDest);
68052       sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
68053     }else{
68054       /* This branch happens only when the row overflows onto multiple pages */
68055       u.ao.t = u.ao.aType[u.ao.p2];
68056       if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
68057        && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
68058       ){
68059         /* Content is irrelevant for the typeof() function and for
68060         ** the length(X) function if X is a blob.  So we might as well use
68061         ** bogus content rather than reading content from disk.  NULL works
68062         ** for text and blob and whatever is in the u.ao.payloadSize64 variable
68063         ** will work for everything else. */
68064         u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
68065       }else{
68066         u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
68067         sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
68068         rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len,  u.ao.pC->isIndex,
68069                                      &u.ao.sMem);
68070         if( rc!=SQLITE_OK ){
68071           goto op_column_out;
68072         }
68073         u.ao.zData = u.ao.sMem.z;
68074       }
68075       sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
68076     }
68077     u.ao.pDest->enc = encoding;
68078   }else{
68079     if( pOp->p4type==P4_MEM ){
68080       sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
68081     }else{
68082       MemSetTypeFlag(u.ao.pDest, MEM_Null);
68083     }
68084   }
68085
68086   /* If we dynamically allocated space to hold the data (in the
68087   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
68088   ** dynamically allocated space over to the u.ao.pDest structure.
68089   ** This prevents a memory copy.
68090   */
68091   if( u.ao.sMem.zMalloc ){
68092     assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
68093     assert( !(u.ao.pDest->flags & MEM_Dyn) );
68094     assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
68095     u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
68096     u.ao.pDest->flags |= MEM_Term;
68097     u.ao.pDest->z = u.ao.sMem.z;
68098     u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
68099   }
68100
68101   rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
68102
68103 op_column_out:
68104   UPDATE_MAX_BLOBSIZE(u.ao.pDest);
68105   REGISTER_TRACE(pOp->p3, u.ao.pDest);
68106   break;
68107 }
68108
68109 /* Opcode: Affinity P1 P2 * P4 *
68110 **
68111 ** Apply affinities to a range of P2 registers starting with P1.
68112 **
68113 ** P4 is a string that is P2 characters long. The nth character of the
68114 ** string indicates the column affinity that should be used for the nth
68115 ** memory cell in the range.
68116 */
68117 case OP_Affinity: {
68118 #if 0  /* local variables moved into u.ap */
68119   const char *zAffinity;   /* The affinity to be applied */
68120   char cAff;               /* A single character of affinity */
68121 #endif /* local variables moved into u.ap */
68122
68123   u.ap.zAffinity = pOp->p4.z;
68124   assert( u.ap.zAffinity!=0 );
68125   assert( u.ap.zAffinity[pOp->p2]==0 );
68126   pIn1 = &aMem[pOp->p1];
68127   while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
68128     assert( pIn1 <= &p->aMem[p->nMem] );
68129     assert( memIsValid(pIn1) );
68130     ExpandBlob(pIn1);
68131     applyAffinity(pIn1, u.ap.cAff, encoding);
68132     pIn1++;
68133   }
68134   break;
68135 }
68136
68137 /* Opcode: MakeRecord P1 P2 P3 P4 *
68138 **
68139 ** Convert P2 registers beginning with P1 into the [record format]
68140 ** use as a data record in a database table or as a key
68141 ** in an index.  The OP_Column opcode can decode the record later.
68142 **
68143 ** P4 may be a string that is P2 characters long.  The nth character of the
68144 ** string indicates the column affinity that should be used for the nth
68145 ** field of the index key.
68146 **
68147 ** The mapping from character to affinity is given by the SQLITE_AFF_
68148 ** macros defined in sqliteInt.h.
68149 **
68150 ** If P4 is NULL then all index fields have the affinity NONE.
68151 */
68152 case OP_MakeRecord: {
68153 #if 0  /* local variables moved into u.aq */
68154   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
68155   Mem *pRec;             /* The new record */
68156   u64 nData;             /* Number of bytes of data space */
68157   int nHdr;              /* Number of bytes of header space */
68158   i64 nByte;             /* Data space required for this record */
68159   int nZero;             /* Number of zero bytes at the end of the record */
68160   int nVarint;           /* Number of bytes in a varint */
68161   u32 serial_type;       /* Type field */
68162   Mem *pData0;           /* First field to be combined into the record */
68163   Mem *pLast;            /* Last field of the record */
68164   int nField;            /* Number of fields in the record */
68165   char *zAffinity;       /* The affinity string for the record */
68166   int file_format;       /* File format to use for encoding */
68167   int i;                 /* Space used in zNewRecord[] */
68168   int len;               /* Length of a field */
68169 #endif /* local variables moved into u.aq */
68170
68171   /* Assuming the record contains N fields, the record format looks
68172   ** like this:
68173   **
68174   ** ------------------------------------------------------------------------
68175   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
68176   ** ------------------------------------------------------------------------
68177   **
68178   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
68179   ** and so froth.
68180   **
68181   ** Each type field is a varint representing the serial type of the
68182   ** corresponding data element (see sqlite3VdbeSerialType()). The
68183   ** hdr-size field is also a varint which is the offset from the beginning
68184   ** of the record to data0.
68185   */
68186   u.aq.nData = 0;         /* Number of bytes of data space */
68187   u.aq.nHdr = 0;          /* Number of bytes of header space */
68188   u.aq.nZero = 0;         /* Number of zero bytes at the end of the record */
68189   u.aq.nField = pOp->p1;
68190   u.aq.zAffinity = pOp->p4.z;
68191   assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
68192   u.aq.pData0 = &aMem[u.aq.nField];
68193   u.aq.nField = pOp->p2;
68194   u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
68195   u.aq.file_format = p->minWriteFileFormat;
68196
68197   /* Identify the output register */
68198   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
68199   pOut = &aMem[pOp->p3];
68200   memAboutToChange(p, pOut);
68201
68202   /* Loop through the elements that will make up the record to figure
68203   ** out how much space is required for the new record.
68204   */
68205   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
68206     assert( memIsValid(u.aq.pRec) );
68207     if( u.aq.zAffinity ){
68208       applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
68209     }
68210     if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
68211       sqlite3VdbeMemExpandBlob(u.aq.pRec);
68212     }
68213     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
68214     u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
68215     u.aq.nData += u.aq.len;
68216     u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
68217     if( u.aq.pRec->flags & MEM_Zero ){
68218       /* Only pure zero-filled BLOBs can be input to this Opcode.
68219       ** We do not allow blobs with a prefix and a zero-filled tail. */
68220       u.aq.nZero += u.aq.pRec->u.nZero;
68221     }else if( u.aq.len ){
68222       u.aq.nZero = 0;
68223     }
68224   }
68225
68226   /* Add the initial header varint and total the size */
68227   u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
68228   if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
68229     u.aq.nHdr++;
68230   }
68231   u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
68232   if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68233     goto too_big;
68234   }
68235
68236   /* Make sure the output register has a buffer large enough to store
68237   ** the new record. The output register (pOp->p3) is not allowed to
68238   ** be one of the input registers (because the following call to
68239   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
68240   */
68241   if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
68242     goto no_mem;
68243   }
68244   u.aq.zNewRecord = (u8 *)pOut->z;
68245
68246   /* Write the record */
68247   u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
68248   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
68249     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
68250     u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type);      /* serial type */
68251   }
68252   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){  /* serial data */
68253     u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
68254   }
68255   assert( u.aq.i==u.aq.nByte );
68256
68257   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68258   pOut->n = (int)u.aq.nByte;
68259   pOut->flags = MEM_Blob | MEM_Dyn;
68260   pOut->xDel = 0;
68261   if( u.aq.nZero ){
68262     pOut->u.nZero = u.aq.nZero;
68263     pOut->flags |= MEM_Zero;
68264   }
68265   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
68266   REGISTER_TRACE(pOp->p3, pOut);
68267   UPDATE_MAX_BLOBSIZE(pOut);
68268   break;
68269 }
68270
68271 /* Opcode: Count P1 P2 * * *
68272 **
68273 ** Store the number of entries (an integer value) in the table or index
68274 ** opened by cursor P1 in register P2
68275 */
68276 #ifndef SQLITE_OMIT_BTREECOUNT
68277 case OP_Count: {         /* out2-prerelease */
68278 #if 0  /* local variables moved into u.ar */
68279   i64 nEntry;
68280   BtCursor *pCrsr;
68281 #endif /* local variables moved into u.ar */
68282
68283   u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
68284   if( ALWAYS(u.ar.pCrsr) ){
68285     rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
68286   }else{
68287     u.ar.nEntry = 0;
68288   }
68289   pOut->u.i = u.ar.nEntry;
68290   break;
68291 }
68292 #endif
68293
68294 /* Opcode: Savepoint P1 * * P4 *
68295 **
68296 ** Open, release or rollback the savepoint named by parameter P4, depending
68297 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
68298 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
68299 */
68300 case OP_Savepoint: {
68301 #if 0  /* local variables moved into u.as */
68302   int p1;                         /* Value of P1 operand */
68303   char *zName;                    /* Name of savepoint */
68304   int nName;
68305   Savepoint *pNew;
68306   Savepoint *pSavepoint;
68307   Savepoint *pTmp;
68308   int iSavepoint;
68309   int ii;
68310 #endif /* local variables moved into u.as */
68311
68312   u.as.p1 = pOp->p1;
68313   u.as.zName = pOp->p4.z;
68314
68315   /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
68316   ** transaction, then there cannot be any savepoints.
68317   */
68318   assert( db->pSavepoint==0 || db->autoCommit==0 );
68319   assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
68320   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
68321   assert( checkSavepointCount(db) );
68322
68323   if( u.as.p1==SAVEPOINT_BEGIN ){
68324     if( db->writeVdbeCnt>0 ){
68325       /* A new savepoint cannot be created if there are active write
68326       ** statements (i.e. open read/write incremental blob handles).
68327       */
68328       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
68329         "SQL statements in progress");
68330       rc = SQLITE_BUSY;
68331     }else{
68332       u.as.nName = sqlite3Strlen30(u.as.zName);
68333
68334 #ifndef SQLITE_OMIT_VIRTUALTABLE
68335       /* This call is Ok even if this savepoint is actually a transaction
68336       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
68337       ** If this is a transaction savepoint being opened, it is guaranteed
68338       ** that the db->aVTrans[] array is empty.  */
68339       assert( db->autoCommit==0 || db->nVTrans==0 );
68340       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
68341                                 db->nStatement+db->nSavepoint);
68342       if( rc!=SQLITE_OK ) goto abort_due_to_error;
68343 #endif
68344
68345       /* Create a new savepoint structure. */
68346       u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
68347       if( u.as.pNew ){
68348         u.as.pNew->zName = (char *)&u.as.pNew[1];
68349         memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
68350
68351         /* If there is no open transaction, then mark this as a special
68352         ** "transaction savepoint". */
68353         if( db->autoCommit ){
68354           db->autoCommit = 0;
68355           db->isTransactionSavepoint = 1;
68356         }else{
68357           db->nSavepoint++;
68358         }
68359
68360         /* Link the new savepoint into the database handle's list. */
68361         u.as.pNew->pNext = db->pSavepoint;
68362         db->pSavepoint = u.as.pNew;
68363         u.as.pNew->nDeferredCons = db->nDeferredCons;
68364       }
68365     }
68366   }else{
68367     u.as.iSavepoint = 0;
68368
68369     /* Find the named savepoint. If there is no such savepoint, then an
68370     ** an error is returned to the user.  */
68371     for(
68372       u.as.pSavepoint = db->pSavepoint;
68373       u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
68374       u.as.pSavepoint = u.as.pSavepoint->pNext
68375     ){
68376       u.as.iSavepoint++;
68377     }
68378     if( !u.as.pSavepoint ){
68379       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
68380       rc = SQLITE_ERROR;
68381     }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
68382       /* It is not possible to release (commit) a savepoint if there are
68383       ** active write statements.
68384       */
68385       sqlite3SetString(&p->zErrMsg, db,
68386         "cannot release savepoint - SQL statements in progress"
68387       );
68388       rc = SQLITE_BUSY;
68389     }else{
68390
68391       /* Determine whether or not this is a transaction savepoint. If so,
68392       ** and this is a RELEASE command, then the current transaction
68393       ** is committed.
68394       */
68395       int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
68396       if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
68397         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68398           goto vdbe_return;
68399         }
68400         db->autoCommit = 1;
68401         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68402           p->pc = pc;
68403           db->autoCommit = 0;
68404           p->rc = rc = SQLITE_BUSY;
68405           goto vdbe_return;
68406         }
68407         db->isTransactionSavepoint = 0;
68408         rc = p->rc;
68409       }else{
68410         u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
68411         if( u.as.p1==SAVEPOINT_ROLLBACK ){
68412           for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68413             sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
68414           }
68415         }
68416         for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68417           rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
68418           if( rc!=SQLITE_OK ){
68419             goto abort_due_to_error;
68420           }
68421         }
68422         if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
68423           sqlite3ExpirePreparedStatements(db);
68424           sqlite3ResetAllSchemasOfConnection(db);
68425           db->flags = (db->flags | SQLITE_InternChanges);
68426         }
68427       }
68428
68429       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
68430       ** savepoints nested inside of the savepoint being operated on. */
68431       while( db->pSavepoint!=u.as.pSavepoint ){
68432         u.as.pTmp = db->pSavepoint;
68433         db->pSavepoint = u.as.pTmp->pNext;
68434         sqlite3DbFree(db, u.as.pTmp);
68435         db->nSavepoint--;
68436       }
68437
68438       /* If it is a RELEASE, then destroy the savepoint being operated on
68439       ** too. If it is a ROLLBACK TO, then set the number of deferred
68440       ** constraint violations present in the database to the value stored
68441       ** when the savepoint was created.  */
68442       if( u.as.p1==SAVEPOINT_RELEASE ){
68443         assert( u.as.pSavepoint==db->pSavepoint );
68444         db->pSavepoint = u.as.pSavepoint->pNext;
68445         sqlite3DbFree(db, u.as.pSavepoint);
68446         if( !isTransaction ){
68447           db->nSavepoint--;
68448         }
68449       }else{
68450         db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
68451       }
68452
68453       if( !isTransaction ){
68454         rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
68455         if( rc!=SQLITE_OK ) goto abort_due_to_error;
68456       }
68457     }
68458   }
68459
68460   break;
68461 }
68462
68463 /* Opcode: AutoCommit P1 P2 * * *
68464 **
68465 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
68466 ** back any currently active btree transactions. If there are any active
68467 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
68468 ** there are active writing VMs or active VMs that use shared cache.
68469 **
68470 ** This instruction causes the VM to halt.
68471 */
68472 case OP_AutoCommit: {
68473 #if 0  /* local variables moved into u.at */
68474   int desiredAutoCommit;
68475   int iRollback;
68476   int turnOnAC;
68477 #endif /* local variables moved into u.at */
68478
68479   u.at.desiredAutoCommit = pOp->p1;
68480   u.at.iRollback = pOp->p2;
68481   u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
68482   assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
68483   assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
68484   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
68485
68486 #if 0
68487   if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
68488     /* If this instruction implements a ROLLBACK and other VMs are
68489     ** still running, and a transaction is active, return an error indicating
68490     ** that the other VMs must complete first.
68491     */
68492     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
68493         "SQL statements in progress");
68494     rc = SQLITE_BUSY;
68495   }else
68496 #endif
68497   if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
68498     /* If this instruction implements a COMMIT and other VMs are writing
68499     ** return an error indicating that the other VMs must complete first.
68500     */
68501     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
68502         "SQL statements in progress");
68503     rc = SQLITE_BUSY;
68504   }else if( u.at.desiredAutoCommit!=db->autoCommit ){
68505     if( u.at.iRollback ){
68506       assert( u.at.desiredAutoCommit==1 );
68507       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
68508       db->autoCommit = 1;
68509     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68510       goto vdbe_return;
68511     }else{
68512       db->autoCommit = (u8)u.at.desiredAutoCommit;
68513       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68514         p->pc = pc;
68515         db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
68516         p->rc = rc = SQLITE_BUSY;
68517         goto vdbe_return;
68518       }
68519     }
68520     assert( db->nStatement==0 );
68521     sqlite3CloseSavepoints(db);
68522     if( p->rc==SQLITE_OK ){
68523       rc = SQLITE_DONE;
68524     }else{
68525       rc = SQLITE_ERROR;
68526     }
68527     goto vdbe_return;
68528   }else{
68529     sqlite3SetString(&p->zErrMsg, db,
68530         (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
68531         (u.at.iRollback)?"cannot rollback - no transaction is active":
68532                    "cannot commit - no transaction is active"));
68533
68534     rc = SQLITE_ERROR;
68535   }
68536   break;
68537 }
68538
68539 /* Opcode: Transaction P1 P2 * * *
68540 **
68541 ** Begin a transaction.  The transaction ends when a Commit or Rollback
68542 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
68543 ** transaction might also be rolled back if an error is encountered.
68544 **
68545 ** P1 is the index of the database file on which the transaction is
68546 ** started.  Index 0 is the main database file and index 1 is the
68547 ** file used for temporary tables.  Indices of 2 or more are used for
68548 ** attached databases.
68549 **
68550 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
68551 ** obtained on the database file when a write-transaction is started.  No
68552 ** other process can start another write transaction while this transaction is
68553 ** underway.  Starting a write transaction also creates a rollback journal. A
68554 ** write transaction must be started before any changes can be made to the
68555 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
68556 ** on the file.
68557 **
68558 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68559 ** true (this flag is set if the Vdbe may modify more than one row and may
68560 ** throw an ABORT exception), a statement transaction may also be opened.
68561 ** More specifically, a statement transaction is opened iff the database
68562 ** connection is currently not in autocommit mode, or if there are other
68563 ** active statements. A statement transaction allows the changes made by this
68564 ** VDBE to be rolled back after an error without having to roll back the
68565 ** entire transaction. If no error is encountered, the statement transaction
68566 ** will automatically commit when the VDBE halts.
68567 **
68568 ** If P2 is zero, then a read-lock is obtained on the database file.
68569 */
68570 case OP_Transaction: {
68571 #if 0  /* local variables moved into u.au */
68572   Btree *pBt;
68573 #endif /* local variables moved into u.au */
68574
68575   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68576   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68577   u.au.pBt = db->aDb[pOp->p1].pBt;
68578
68579   if( u.au.pBt ){
68580     rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
68581     if( rc==SQLITE_BUSY ){
68582       p->pc = pc;
68583       p->rc = rc = SQLITE_BUSY;
68584       goto vdbe_return;
68585     }
68586     if( rc!=SQLITE_OK ){
68587       goto abort_due_to_error;
68588     }
68589
68590     if( pOp->p2 && p->usesStmtJournal
68591      && (db->autoCommit==0 || db->activeVdbeCnt>1)
68592     ){
68593       assert( sqlite3BtreeIsInTrans(u.au.pBt) );
68594       if( p->iStatement==0 ){
68595         assert( db->nStatement>=0 && db->nSavepoint>=0 );
68596         db->nStatement++;
68597         p->iStatement = db->nSavepoint + db->nStatement;
68598       }
68599
68600       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
68601       if( rc==SQLITE_OK ){
68602         rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
68603       }
68604
68605       /* Store the current value of the database handles deferred constraint
68606       ** counter. If the statement transaction needs to be rolled back,
68607       ** the value of this counter needs to be restored too.  */
68608       p->nStmtDefCons = db->nDeferredCons;
68609     }
68610   }
68611   break;
68612 }
68613
68614 /* Opcode: ReadCookie P1 P2 P3 * *
68615 **
68616 ** Read cookie number P3 from database P1 and write it into register P2.
68617 ** P3==1 is the schema version.  P3==2 is the database format.
68618 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
68619 ** the main database file and P1==1 is the database file used to store
68620 ** temporary tables.
68621 **
68622 ** There must be a read-lock on the database (either a transaction
68623 ** must be started or there must be an open cursor) before
68624 ** executing this instruction.
68625 */
68626 case OP_ReadCookie: {               /* out2-prerelease */
68627 #if 0  /* local variables moved into u.av */
68628   int iMeta;
68629   int iDb;
68630   int iCookie;
68631 #endif /* local variables moved into u.av */
68632
68633   u.av.iDb = pOp->p1;
68634   u.av.iCookie = pOp->p3;
68635   assert( pOp->p3<SQLITE_N_BTREE_META );
68636   assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
68637   assert( db->aDb[u.av.iDb].pBt!=0 );
68638   assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
68639
68640   sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
68641   pOut->u.i = u.av.iMeta;
68642   break;
68643 }
68644
68645 /* Opcode: SetCookie P1 P2 P3 * *
68646 **
68647 ** Write the content of register P3 (interpreted as an integer)
68648 ** into cookie number P2 of database P1.  P2==1 is the schema version.
68649 ** P2==2 is the database format. P2==3 is the recommended pager cache
68650 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
68651 ** database file used to store temporary tables.
68652 **
68653 ** A transaction must be started before executing this opcode.
68654 */
68655 case OP_SetCookie: {       /* in3 */
68656 #if 0  /* local variables moved into u.aw */
68657   Db *pDb;
68658 #endif /* local variables moved into u.aw */
68659   assert( pOp->p2<SQLITE_N_BTREE_META );
68660   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68661   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68662   u.aw.pDb = &db->aDb[pOp->p1];
68663   assert( u.aw.pDb->pBt!=0 );
68664   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68665   pIn3 = &aMem[pOp->p3];
68666   sqlite3VdbeMemIntegerify(pIn3);
68667   /* See note about index shifting on OP_ReadCookie */
68668   rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
68669   if( pOp->p2==BTREE_SCHEMA_VERSION ){
68670     /* When the schema cookie changes, record the new cookie internally */
68671     u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
68672     db->flags |= SQLITE_InternChanges;
68673   }else if( pOp->p2==BTREE_FILE_FORMAT ){
68674     /* Record changes in the file format */
68675     u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
68676   }
68677   if( pOp->p1==1 ){
68678     /* Invalidate all prepared statements whenever the TEMP database
68679     ** schema is changed.  Ticket #1644 */
68680     sqlite3ExpirePreparedStatements(db);
68681     p->expired = 0;
68682   }
68683   break;
68684 }
68685
68686 /* Opcode: VerifyCookie P1 P2 P3 * *
68687 **
68688 ** Check the value of global database parameter number 0 (the
68689 ** schema version) and make sure it is equal to P2 and that the
68690 ** generation counter on the local schema parse equals P3.
68691 **
68692 ** P1 is the database number which is 0 for the main database file
68693 ** and 1 for the file holding temporary tables and some higher number
68694 ** for auxiliary databases.
68695 **
68696 ** The cookie changes its value whenever the database schema changes.
68697 ** This operation is used to detect when that the cookie has changed
68698 ** and that the current process needs to reread the schema.
68699 **
68700 ** Either a transaction needs to have been started or an OP_Open needs
68701 ** to be executed (to establish a read lock) before this opcode is
68702 ** invoked.
68703 */
68704 case OP_VerifyCookie: {
68705 #if 0  /* local variables moved into u.ax */
68706   int iMeta;
68707   int iGen;
68708   Btree *pBt;
68709 #endif /* local variables moved into u.ax */
68710
68711   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68712   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68713   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68714   u.ax.pBt = db->aDb[pOp->p1].pBt;
68715   if( u.ax.pBt ){
68716     sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
68717     u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
68718   }else{
68719     u.ax.iGen = u.ax.iMeta = 0;
68720   }
68721   if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
68722     sqlite3DbFree(db, p->zErrMsg);
68723     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
68724     /* If the schema-cookie from the database file matches the cookie
68725     ** stored with the in-memory representation of the schema, do
68726     ** not reload the schema from the database file.
68727     **
68728     ** If virtual-tables are in use, this is not just an optimization.
68729     ** Often, v-tables store their data in other SQLite tables, which
68730     ** are queried from within xNext() and other v-table methods using
68731     ** prepared queries. If such a query is out-of-date, we do not want to
68732     ** discard the database schema, as the user code implementing the
68733     ** v-table would have to be ready for the sqlite3_vtab structure itself
68734     ** to be invalidated whenever sqlite3_step() is called from within
68735     ** a v-table method.
68736     */
68737     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
68738       sqlite3ResetOneSchema(db, pOp->p1);
68739     }
68740
68741     p->expired = 1;
68742     rc = SQLITE_SCHEMA;
68743   }
68744   break;
68745 }
68746
68747 /* Opcode: OpenRead P1 P2 P3 P4 P5
68748 **
68749 ** Open a read-only cursor for the database table whose root page is
68750 ** P2 in a database file.  The database file is determined by P3.
68751 ** P3==0 means the main database, P3==1 means the database used for
68752 ** temporary tables, and P3>1 means used the corresponding attached
68753 ** database.  Give the new cursor an identifier of P1.  The P1
68754 ** values need not be contiguous but all P1 values should be small integers.
68755 ** It is an error for P1 to be negative.
68756 **
68757 ** If P5!=0 then use the content of register P2 as the root page, not
68758 ** the value of P2 itself.
68759 **
68760 ** There will be a read lock on the database whenever there is an
68761 ** open cursor.  If the database was unlocked prior to this instruction
68762 ** then a read lock is acquired as part of this instruction.  A read
68763 ** lock allows other processes to read the database but prohibits
68764 ** any other process from modifying the database.  The read lock is
68765 ** released when all cursors are closed.  If this instruction attempts
68766 ** to get a read lock but fails, the script terminates with an
68767 ** SQLITE_BUSY error code.
68768 **
68769 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68770 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
68771 ** structure, then said structure defines the content and collating
68772 ** sequence of the index being opened. Otherwise, if P4 is an integer
68773 ** value, it is set to the number of columns in the table.
68774 **
68775 ** See also OpenWrite.
68776 */
68777 /* Opcode: OpenWrite P1 P2 P3 P4 P5
68778 **
68779 ** Open a read/write cursor named P1 on the table or index whose root
68780 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
68781 ** root page.
68782 **
68783 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68784 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
68785 ** structure, then said structure defines the content and collating
68786 ** sequence of the index being opened. Otherwise, if P4 is an integer
68787 ** value, it is set to the number of columns in the table, or to the
68788 ** largest index of any column of the table that is actually used.
68789 **
68790 ** This instruction works just like OpenRead except that it opens the cursor
68791 ** in read/write mode.  For a given table, there can be one or more read-only
68792 ** cursors or a single read/write cursor but not both.
68793 **
68794 ** See also OpenRead.
68795 */
68796 case OP_OpenRead:
68797 case OP_OpenWrite: {
68798 #if 0  /* local variables moved into u.ay */
68799   int nField;
68800   KeyInfo *pKeyInfo;
68801   int p2;
68802   int iDb;
68803   int wrFlag;
68804   Btree *pX;
68805   VdbeCursor *pCur;
68806   Db *pDb;
68807 #endif /* local variables moved into u.ay */
68808
68809   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
68810   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
68811
68812   if( p->expired ){
68813     rc = SQLITE_ABORT;
68814     break;
68815   }
68816
68817   u.ay.nField = 0;
68818   u.ay.pKeyInfo = 0;
68819   u.ay.p2 = pOp->p2;
68820   u.ay.iDb = pOp->p3;
68821   assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
68822   assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
68823   u.ay.pDb = &db->aDb[u.ay.iDb];
68824   u.ay.pX = u.ay.pDb->pBt;
68825   assert( u.ay.pX!=0 );
68826   if( pOp->opcode==OP_OpenWrite ){
68827     u.ay.wrFlag = 1;
68828     assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
68829     if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
68830       p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
68831     }
68832   }else{
68833     u.ay.wrFlag = 0;
68834   }
68835   if( pOp->p5 & OPFLAG_P2ISREG ){
68836     assert( u.ay.p2>0 );
68837     assert( u.ay.p2<=p->nMem );
68838     pIn2 = &aMem[u.ay.p2];
68839     assert( memIsValid(pIn2) );
68840     assert( (pIn2->flags & MEM_Int)!=0 );
68841     sqlite3VdbeMemIntegerify(pIn2);
68842     u.ay.p2 = (int)pIn2->u.i;
68843     /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
68844     ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
68845     ** If there were a failure, the prepared statement would have halted
68846     ** before reaching this instruction. */
68847     if( NEVER(u.ay.p2<2) ) {
68848       rc = SQLITE_CORRUPT_BKPT;
68849       goto abort_due_to_error;
68850     }
68851   }
68852   if( pOp->p4type==P4_KEYINFO ){
68853     u.ay.pKeyInfo = pOp->p4.pKeyInfo;
68854     u.ay.pKeyInfo->enc = ENC(p->db);
68855     u.ay.nField = u.ay.pKeyInfo->nField+1;
68856   }else if( pOp->p4type==P4_INT32 ){
68857     u.ay.nField = pOp->p4.i;
68858   }
68859   assert( pOp->p1>=0 );
68860   u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
68861   if( u.ay.pCur==0 ) goto no_mem;
68862   u.ay.pCur->nullRow = 1;
68863   u.ay.pCur->isOrdered = 1;
68864   rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
68865   u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
68866   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
68867   sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
68868
68869   /* Since it performs no memory allocation or IO, the only value that
68870   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
68871   assert( rc==SQLITE_OK );
68872
68873   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68874   ** SQLite used to check if the root-page flags were sane at this point
68875   ** and report database corruption if they were not, but this check has
68876   ** since moved into the btree layer.  */
68877   u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68878   u.ay.pCur->isIndex = !u.ay.pCur->isTable;
68879   break;
68880 }
68881
68882 /* Opcode: OpenEphemeral P1 P2 * P4 P5
68883 **
68884 ** Open a new cursor P1 to a transient table.
68885 ** The cursor is always opened read/write even if
68886 ** the main database is read-only.  The ephemeral
68887 ** table is deleted automatically when the cursor is closed.
68888 **
68889 ** P2 is the number of columns in the ephemeral table.
68890 ** The cursor points to a BTree table if P4==0 and to a BTree index
68891 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68892 ** that defines the format of keys in the index.
68893 **
68894 ** This opcode was once called OpenTemp.  But that created
68895 ** confusion because the term "temp table", might refer either
68896 ** to a TEMP table at the SQL level, or to a table opened by
68897 ** this opcode.  Then this opcode was call OpenVirtual.  But
68898 ** that created confusion with the whole virtual-table idea.
68899 **
68900 ** The P5 parameter can be a mask of the BTREE_* flags defined
68901 ** in btree.h.  These flags control aspects of the operation of
68902 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68903 ** added automatically.
68904 */
68905 /* Opcode: OpenAutoindex P1 P2 * P4 *
68906 **
68907 ** This opcode works the same as OP_OpenEphemeral.  It has a
68908 ** different name to distinguish its use.  Tables created using
68909 ** by this opcode will be used for automatically created transient
68910 ** indices in joins.
68911 */
68912 case OP_OpenAutoindex:
68913 case OP_OpenEphemeral: {
68914 #if 0  /* local variables moved into u.az */
68915   VdbeCursor *pCx;
68916 #endif /* local variables moved into u.az */
68917   static const int vfsFlags =
68918       SQLITE_OPEN_READWRITE |
68919       SQLITE_OPEN_CREATE |
68920       SQLITE_OPEN_EXCLUSIVE |
68921       SQLITE_OPEN_DELETEONCLOSE |
68922       SQLITE_OPEN_TRANSIENT_DB;
68923
68924   assert( pOp->p1>=0 );
68925   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68926   if( u.az.pCx==0 ) goto no_mem;
68927   u.az.pCx->nullRow = 1;
68928   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
68929                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68930   if( rc==SQLITE_OK ){
68931     rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
68932   }
68933   if( rc==SQLITE_OK ){
68934     /* If a transient index is required, create it by calling
68935     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68936     ** opening it. If a transient table is required, just use the
68937     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68938     */
68939     if( pOp->p4.pKeyInfo ){
68940       int pgno;
68941       assert( pOp->p4type==P4_KEYINFO );
68942       rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68943       if( rc==SQLITE_OK ){
68944         assert( pgno==MASTER_ROOT+1 );
68945         rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
68946                                 (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
68947         u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68948         u.az.pCx->pKeyInfo->enc = ENC(p->db);
68949       }
68950       u.az.pCx->isTable = 0;
68951     }else{
68952       rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
68953       u.az.pCx->isTable = 1;
68954     }
68955   }
68956   u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68957   u.az.pCx->isIndex = !u.az.pCx->isTable;
68958   break;
68959 }
68960
68961 /* Opcode: SorterOpen P1 P2 * P4 *
68962 **
68963 ** This opcode works like OP_OpenEphemeral except that it opens
68964 ** a transient index that is specifically designed to sort large
68965 ** tables using an external merge-sort algorithm.
68966 */
68967 case OP_SorterOpen: {
68968 #if 0  /* local variables moved into u.ba */
68969   VdbeCursor *pCx;
68970 #endif /* local variables moved into u.ba */
68971
68972 #ifndef SQLITE_OMIT_MERGE_SORT
68973   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68974   if( u.ba.pCx==0 ) goto no_mem;
68975   u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68976   u.ba.pCx->pKeyInfo->enc = ENC(p->db);
68977   u.ba.pCx->isSorter = 1;
68978   rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
68979 #else
68980   pOp->opcode = OP_OpenEphemeral;
68981   pc--;
68982 #endif
68983   break;
68984 }
68985
68986 /* Opcode: OpenPseudo P1 P2 P3 * P5
68987 **
68988 ** Open a new cursor that points to a fake table that contains a single
68989 ** row of data.  The content of that one row in the content of memory
68990 ** register P2 when P5==0.  In other words, cursor P1 becomes an alias for the
68991 ** MEM_Blob content contained in register P2.  When P5==1, then the
68992 ** row is represented by P3 consecutive registers beginning with P2.
68993 **
68994 ** A pseudo-table created by this opcode is used to hold a single
68995 ** row output from the sorter so that the row can be decomposed into
68996 ** individual columns using the OP_Column opcode.  The OP_Column opcode
68997 ** is the only cursor opcode that works with a pseudo-table.
68998 **
68999 ** P3 is the number of fields in the records that will be stored by
69000 ** the pseudo-table.
69001 */
69002 case OP_OpenPseudo: {
69003 #if 0  /* local variables moved into u.bb */
69004   VdbeCursor *pCx;
69005 #endif /* local variables moved into u.bb */
69006
69007   assert( pOp->p1>=0 );
69008   u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
69009   if( u.bb.pCx==0 ) goto no_mem;
69010   u.bb.pCx->nullRow = 1;
69011   u.bb.pCx->pseudoTableReg = pOp->p2;
69012   u.bb.pCx->isTable = 1;
69013   u.bb.pCx->isIndex = 0;
69014   u.bb.pCx->multiPseudo = pOp->p5;
69015   break;
69016 }
69017
69018 /* Opcode: Close P1 * * * *
69019 **
69020 ** Close a cursor previously opened as P1.  If P1 is not
69021 ** currently open, this instruction is a no-op.
69022 */
69023 case OP_Close: {
69024   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69025   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
69026   p->apCsr[pOp->p1] = 0;
69027   break;
69028 }
69029
69030 /* Opcode: SeekGe P1 P2 P3 P4 *
69031 **
69032 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69033 ** use the value in register P3 as the key.  If cursor P1 refers
69034 ** to an SQL index, then P3 is the first in an array of P4 registers
69035 ** that are used as an unpacked index key.
69036 **
69037 ** Reposition cursor P1 so that  it points to the smallest entry that
69038 ** is greater than or equal to the key value. If there are no records
69039 ** greater than or equal to the key and P2 is not zero, then jump to P2.
69040 **
69041 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
69042 */
69043 /* Opcode: SeekGt P1 P2 P3 P4 *
69044 **
69045 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69046 ** use the value in register P3 as a key. If cursor P1 refers
69047 ** to an SQL index, then P3 is the first in an array of P4 registers
69048 ** that are used as an unpacked index key.
69049 **
69050 ** Reposition cursor P1 so that  it points to the smallest entry that
69051 ** is greater than the key value. If there are no records greater than
69052 ** the key and P2 is not zero, then jump to P2.
69053 **
69054 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
69055 */
69056 /* Opcode: SeekLt P1 P2 P3 P4 *
69057 **
69058 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69059 ** use the value in register P3 as a key. If cursor P1 refers
69060 ** to an SQL index, then P3 is the first in an array of P4 registers
69061 ** that are used as an unpacked index key.
69062 **
69063 ** Reposition cursor P1 so that  it points to the largest entry that
69064 ** is less than the key value. If there are no records less than
69065 ** the key and P2 is not zero, then jump to P2.
69066 **
69067 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
69068 */
69069 /* Opcode: SeekLe P1 P2 P3 P4 *
69070 **
69071 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69072 ** use the value in register P3 as a key. If cursor P1 refers
69073 ** to an SQL index, then P3 is the first in an array of P4 registers
69074 ** that are used as an unpacked index key.
69075 **
69076 ** Reposition cursor P1 so that it points to the largest entry that
69077 ** is less than or equal to the key value. If there are no records
69078 ** less than or equal to the key and P2 is not zero, then jump to P2.
69079 **
69080 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
69081 */
69082 case OP_SeekLt:         /* jump, in3 */
69083 case OP_SeekLe:         /* jump, in3 */
69084 case OP_SeekGe:         /* jump, in3 */
69085 case OP_SeekGt: {       /* jump, in3 */
69086 #if 0  /* local variables moved into u.bc */
69087   int res;
69088   int oc;
69089   VdbeCursor *pC;
69090   UnpackedRecord r;
69091   int nField;
69092   i64 iKey;      /* The rowid we are to seek to */
69093 #endif /* local variables moved into u.bc */
69094
69095   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69096   assert( pOp->p2!=0 );
69097   u.bc.pC = p->apCsr[pOp->p1];
69098   assert( u.bc.pC!=0 );
69099   assert( u.bc.pC->pseudoTableReg==0 );
69100   assert( OP_SeekLe == OP_SeekLt+1 );
69101   assert( OP_SeekGe == OP_SeekLt+2 );
69102   assert( OP_SeekGt == OP_SeekLt+3 );
69103   assert( u.bc.pC->isOrdered );
69104   if( ALWAYS(u.bc.pC->pCursor!=0) ){
69105     u.bc.oc = pOp->opcode;
69106     u.bc.pC->nullRow = 0;
69107     if( u.bc.pC->isTable ){
69108       /* The input value in P3 might be of any type: integer, real, string,
69109       ** blob, or NULL.  But it needs to be an integer before we can do
69110       ** the seek, so covert it. */
69111       pIn3 = &aMem[pOp->p3];
69112       applyNumericAffinity(pIn3);
69113       u.bc.iKey = sqlite3VdbeIntValue(pIn3);
69114       u.bc.pC->rowidIsValid = 0;
69115
69116       /* If the P3 value could not be converted into an integer without
69117       ** loss of information, then special processing is required... */
69118       if( (pIn3->flags & MEM_Int)==0 ){
69119         if( (pIn3->flags & MEM_Real)==0 ){
69120           /* If the P3 value cannot be converted into any kind of a number,
69121           ** then the seek is not possible, so jump to P2 */
69122           pc = pOp->p2 - 1;
69123           break;
69124         }
69125         /* If we reach this point, then the P3 value must be a floating
69126         ** point number. */
69127         assert( (pIn3->flags & MEM_Real)!=0 );
69128
69129         if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
69130           /* The P3 value is too large in magnitude to be expressed as an
69131           ** integer. */
69132           u.bc.res = 1;
69133           if( pIn3->r<0 ){
69134             if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
69135               rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
69136               if( rc!=SQLITE_OK ) goto abort_due_to_error;
69137             }
69138           }else{
69139             if( u.bc.oc<=OP_SeekLe ){  assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
69140               rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
69141               if( rc!=SQLITE_OK ) goto abort_due_to_error;
69142             }
69143           }
69144           if( u.bc.res ){
69145             pc = pOp->p2 - 1;
69146           }
69147           break;
69148         }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
69149           /* Use the ceiling() function to convert real->int */
69150           if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
69151         }else{
69152           /* Use the floor() function to convert real->int */
69153           assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
69154           if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
69155         }
69156       }
69157       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
69158       if( rc!=SQLITE_OK ){
69159         goto abort_due_to_error;
69160       }
69161       if( u.bc.res==0 ){
69162         u.bc.pC->rowidIsValid = 1;
69163         u.bc.pC->lastRowid = u.bc.iKey;
69164       }
69165     }else{
69166       u.bc.nField = pOp->p4.i;
69167       assert( pOp->p4type==P4_INT32 );
69168       assert( u.bc.nField>0 );
69169       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
69170       u.bc.r.nField = (u16)u.bc.nField;
69171
69172       /* The next line of code computes as follows, only faster:
69173       **   if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
69174       **     u.bc.r.flags = UNPACKED_INCRKEY;
69175       **   }else{
69176       **     u.bc.r.flags = 0;
69177       **   }
69178       */
69179       u.bc.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
69180       assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
69181       assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
69182       assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
69183       assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
69184
69185       u.bc.r.aMem = &aMem[pOp->p3];
69186 #ifdef SQLITE_DEBUG
69187       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
69188 #endif
69189       ExpandBlob(u.bc.r.aMem);
69190       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
69191       if( rc!=SQLITE_OK ){
69192         goto abort_due_to_error;
69193       }
69194       u.bc.pC->rowidIsValid = 0;
69195     }
69196     u.bc.pC->deferredMoveto = 0;
69197     u.bc.pC->cacheStatus = CACHE_STALE;
69198 #ifdef SQLITE_TEST
69199     sqlite3_search_count++;
69200 #endif
69201     if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
69202       if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
69203         rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
69204         if( rc!=SQLITE_OK ) goto abort_due_to_error;
69205         u.bc.pC->rowidIsValid = 0;
69206       }else{
69207         u.bc.res = 0;
69208       }
69209     }else{
69210       assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
69211       if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
69212         rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
69213         if( rc!=SQLITE_OK ) goto abort_due_to_error;
69214         u.bc.pC->rowidIsValid = 0;
69215       }else{
69216         /* u.bc.res might be negative because the table is empty.  Check to
69217         ** see if this is the case.
69218         */
69219         u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
69220       }
69221     }
69222     assert( pOp->p2>0 );
69223     if( u.bc.res ){
69224       pc = pOp->p2 - 1;
69225     }
69226   }else{
69227     /* This happens when attempting to open the sqlite3_master table
69228     ** for read access returns SQLITE_EMPTY. In this case always
69229     ** take the jump (since there are no records in the table).
69230     */
69231     pc = pOp->p2 - 1;
69232   }
69233   break;
69234 }
69235
69236 /* Opcode: Seek P1 P2 * * *
69237 **
69238 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
69239 ** for P1 to move so that it points to the rowid given by P2.
69240 **
69241 ** This is actually a deferred seek.  Nothing actually happens until
69242 ** the cursor is used to read a record.  That way, if no reads
69243 ** occur, no unnecessary I/O happens.
69244 */
69245 case OP_Seek: {    /* in2 */
69246 #if 0  /* local variables moved into u.bd */
69247   VdbeCursor *pC;
69248 #endif /* local variables moved into u.bd */
69249
69250   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69251   u.bd.pC = p->apCsr[pOp->p1];
69252   assert( u.bd.pC!=0 );
69253   if( ALWAYS(u.bd.pC->pCursor!=0) ){
69254     assert( u.bd.pC->isTable );
69255     u.bd.pC->nullRow = 0;
69256     pIn2 = &aMem[pOp->p2];
69257     u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
69258     u.bd.pC->rowidIsValid = 0;
69259     u.bd.pC->deferredMoveto = 1;
69260   }
69261   break;
69262 }
69263
69264
69265 /* Opcode: Found P1 P2 P3 P4 *
69266 **
69267 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
69268 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
69269 ** record.
69270 **
69271 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
69272 ** is a prefix of any entry in P1 then a jump is made to P2 and
69273 ** P1 is left pointing at the matching entry.
69274 */
69275 /* Opcode: NotFound P1 P2 P3 P4 *
69276 **
69277 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
69278 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
69279 ** record.
69280 **
69281 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
69282 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
69283 ** does contain an entry whose prefix matches the P3/P4 record then control
69284 ** falls through to the next instruction and P1 is left pointing at the
69285 ** matching entry.
69286 **
69287 ** See also: Found, NotExists, IsUnique
69288 */
69289 case OP_NotFound:       /* jump, in3 */
69290 case OP_Found: {        /* jump, in3 */
69291 #if 0  /* local variables moved into u.be */
69292   int alreadyExists;
69293   VdbeCursor *pC;
69294   int res;
69295   char *pFree;
69296   UnpackedRecord *pIdxKey;
69297   UnpackedRecord r;
69298   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
69299 #endif /* local variables moved into u.be */
69300
69301 #ifdef SQLITE_TEST
69302   sqlite3_found_count++;
69303 #endif
69304
69305   u.be.alreadyExists = 0;
69306   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69307   assert( pOp->p4type==P4_INT32 );
69308   u.be.pC = p->apCsr[pOp->p1];
69309   assert( u.be.pC!=0 );
69310   pIn3 = &aMem[pOp->p3];
69311   if( ALWAYS(u.be.pC->pCursor!=0) ){
69312
69313     assert( u.be.pC->isTable==0 );
69314     if( pOp->p4.i>0 ){
69315       u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
69316       u.be.r.nField = (u16)pOp->p4.i;
69317       u.be.r.aMem = pIn3;
69318 #ifdef SQLITE_DEBUG
69319       { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
69320 #endif
69321       u.be.r.flags = UNPACKED_PREFIX_MATCH;
69322       u.be.pIdxKey = &u.be.r;
69323     }else{
69324       u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
69325           u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
69326       );
69327       if( u.be.pIdxKey==0 ) goto no_mem;
69328       assert( pIn3->flags & MEM_Blob );
69329       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
69330       sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
69331       u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
69332     }
69333     rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
69334     if( pOp->p4.i==0 ){
69335       sqlite3DbFree(db, u.be.pFree);
69336     }
69337     if( rc!=SQLITE_OK ){
69338       break;
69339     }
69340     u.be.alreadyExists = (u.be.res==0);
69341     u.be.pC->deferredMoveto = 0;
69342     u.be.pC->cacheStatus = CACHE_STALE;
69343   }
69344   if( pOp->opcode==OP_Found ){
69345     if( u.be.alreadyExists ) pc = pOp->p2 - 1;
69346   }else{
69347     if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
69348   }
69349   break;
69350 }
69351
69352 /* Opcode: IsUnique P1 P2 P3 P4 *
69353 **
69354 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
69355 ** no data and where the key are records generated by OP_MakeRecord with
69356 ** the list field being the integer ROWID of the entry that the index
69357 ** entry refers to.
69358 **
69359 ** The P3 register contains an integer record number. Call this record
69360 ** number R. Register P4 is the first in a set of N contiguous registers
69361 ** that make up an unpacked index key that can be used with cursor P1.
69362 ** The value of N can be inferred from the cursor. N includes the rowid
69363 ** value appended to the end of the index record. This rowid value may
69364 ** or may not be the same as R.
69365 **
69366 ** If any of the N registers beginning with register P4 contains a NULL
69367 ** value, jump immediately to P2.
69368 **
69369 ** Otherwise, this instruction checks if cursor P1 contains an entry
69370 ** where the first (N-1) fields match but the rowid value at the end
69371 ** of the index entry is not R. If there is no such entry, control jumps
69372 ** to instruction P2. Otherwise, the rowid of the conflicting index
69373 ** entry is copied to register P3 and control falls through to the next
69374 ** instruction.
69375 **
69376 ** See also: NotFound, NotExists, Found
69377 */
69378 case OP_IsUnique: {        /* jump, in3 */
69379 #if 0  /* local variables moved into u.bf */
69380   u16 ii;
69381   VdbeCursor *pCx;
69382   BtCursor *pCrsr;
69383   u16 nField;
69384   Mem *aMx;
69385   UnpackedRecord r;                  /* B-Tree index search key */
69386   i64 R;                             /* Rowid stored in register P3 */
69387 #endif /* local variables moved into u.bf */
69388
69389   pIn3 = &aMem[pOp->p3];
69390   u.bf.aMx = &aMem[pOp->p4.i];
69391   /* Assert that the values of parameters P1 and P4 are in range. */
69392   assert( pOp->p4type==P4_INT32 );
69393   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
69394   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69395
69396   /* Find the index cursor. */
69397   u.bf.pCx = p->apCsr[pOp->p1];
69398   assert( u.bf.pCx->deferredMoveto==0 );
69399   u.bf.pCx->seekResult = 0;
69400   u.bf.pCx->cacheStatus = CACHE_STALE;
69401   u.bf.pCrsr = u.bf.pCx->pCursor;
69402
69403   /* If any of the values are NULL, take the jump. */
69404   u.bf.nField = u.bf.pCx->pKeyInfo->nField;
69405   for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
69406     if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
69407       pc = pOp->p2 - 1;
69408       u.bf.pCrsr = 0;
69409       break;
69410     }
69411   }
69412   assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
69413
69414   if( u.bf.pCrsr!=0 ){
69415     /* Populate the index search key. */
69416     u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
69417     u.bf.r.nField = u.bf.nField + 1;
69418     u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
69419     u.bf.r.aMem = u.bf.aMx;
69420 #ifdef SQLITE_DEBUG
69421     { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
69422 #endif
69423
69424     /* Extract the value of u.bf.R from register P3. */
69425     sqlite3VdbeMemIntegerify(pIn3);
69426     u.bf.R = pIn3->u.i;
69427
69428     /* Search the B-Tree index. If no conflicting record is found, jump
69429     ** to P2. Otherwise, copy the rowid of the conflicting record to
69430     ** register P3 and fall through to the next instruction.  */
69431     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
69432     if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
69433       pc = pOp->p2 - 1;
69434     }else{
69435       pIn3->u.i = u.bf.r.rowid;
69436     }
69437   }
69438   break;
69439 }
69440
69441 /* Opcode: NotExists P1 P2 P3 * *
69442 **
69443 ** Use the content of register P3 as an integer key.  If a record
69444 ** with that key does not exist in table of P1, then jump to P2.
69445 ** If the record does exist, then fall through.  The cursor is left
69446 ** pointing to the record if it exists.
69447 **
69448 ** The difference between this operation and NotFound is that this
69449 ** operation assumes the key is an integer and that P1 is a table whereas
69450 ** NotFound assumes key is a blob constructed from MakeRecord and
69451 ** P1 is an index.
69452 **
69453 ** See also: Found, NotFound, IsUnique
69454 */
69455 case OP_NotExists: {        /* jump, in3 */
69456 #if 0  /* local variables moved into u.bg */
69457   VdbeCursor *pC;
69458   BtCursor *pCrsr;
69459   int res;
69460   u64 iKey;
69461 #endif /* local variables moved into u.bg */
69462
69463   pIn3 = &aMem[pOp->p3];
69464   assert( pIn3->flags & MEM_Int );
69465   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69466   u.bg.pC = p->apCsr[pOp->p1];
69467   assert( u.bg.pC!=0 );
69468   assert( u.bg.pC->isTable );
69469   assert( u.bg.pC->pseudoTableReg==0 );
69470   u.bg.pCrsr = u.bg.pC->pCursor;
69471   if( ALWAYS(u.bg.pCrsr!=0) ){
69472     u.bg.res = 0;
69473     u.bg.iKey = pIn3->u.i;
69474     rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
69475     u.bg.pC->lastRowid = pIn3->u.i;
69476     u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
69477     u.bg.pC->nullRow = 0;
69478     u.bg.pC->cacheStatus = CACHE_STALE;
69479     u.bg.pC->deferredMoveto = 0;
69480     if( u.bg.res!=0 ){
69481       pc = pOp->p2 - 1;
69482       assert( u.bg.pC->rowidIsValid==0 );
69483     }
69484     u.bg.pC->seekResult = u.bg.res;
69485   }else{
69486     /* This happens when an attempt to open a read cursor on the
69487     ** sqlite_master table returns SQLITE_EMPTY.
69488     */
69489     pc = pOp->p2 - 1;
69490     assert( u.bg.pC->rowidIsValid==0 );
69491     u.bg.pC->seekResult = 0;
69492   }
69493   break;
69494 }
69495
69496 /* Opcode: Sequence P1 P2 * * *
69497 **
69498 ** Find the next available sequence number for cursor P1.
69499 ** Write the sequence number into register P2.
69500 ** The sequence number on the cursor is incremented after this
69501 ** instruction.
69502 */
69503 case OP_Sequence: {           /* out2-prerelease */
69504   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69505   assert( p->apCsr[pOp->p1]!=0 );
69506   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
69507   break;
69508 }
69509
69510
69511 /* Opcode: NewRowid P1 P2 P3 * *
69512 **
69513 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
69514 ** The record number is not previously used as a key in the database
69515 ** table that cursor P1 points to.  The new record number is written
69516 ** written to register P2.
69517 **
69518 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
69519 ** the largest previously generated record number. No new record numbers are
69520 ** allowed to be less than this value. When this value reaches its maximum,
69521 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
69522 ** generated record number. This P3 mechanism is used to help implement the
69523 ** AUTOINCREMENT feature.
69524 */
69525 case OP_NewRowid: {           /* out2-prerelease */
69526 #if 0  /* local variables moved into u.bh */
69527   i64 v;                 /* The new rowid */
69528   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
69529   int res;               /* Result of an sqlite3BtreeLast() */
69530   int cnt;               /* Counter to limit the number of searches */
69531   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
69532   VdbeFrame *pFrame;     /* Root frame of VDBE */
69533 #endif /* local variables moved into u.bh */
69534
69535   u.bh.v = 0;
69536   u.bh.res = 0;
69537   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69538   u.bh.pC = p->apCsr[pOp->p1];
69539   assert( u.bh.pC!=0 );
69540   if( NEVER(u.bh.pC->pCursor==0) ){
69541     /* The zero initialization above is all that is needed */
69542   }else{
69543     /* The next rowid or record number (different terms for the same
69544     ** thing) is obtained in a two-step algorithm.
69545     **
69546     ** First we attempt to find the largest existing rowid and add one
69547     ** to that.  But if the largest existing rowid is already the maximum
69548     ** positive integer, we have to fall through to the second
69549     ** probabilistic algorithm
69550     **
69551     ** The second algorithm is to select a rowid at random and see if
69552     ** it already exists in the table.  If it does not exist, we have
69553     ** succeeded.  If the random rowid does exist, we select a new one
69554     ** and try again, up to 100 times.
69555     */
69556     assert( u.bh.pC->isTable );
69557
69558 #ifdef SQLITE_32BIT_ROWID
69559 #   define MAX_ROWID 0x7fffffff
69560 #else
69561     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
69562     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
69563     ** to provide the constant while making all compilers happy.
69564     */
69565 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
69566 #endif
69567
69568     if( !u.bh.pC->useRandomRowid ){
69569       u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
69570       if( u.bh.v==0 ){
69571         rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
69572         if( rc!=SQLITE_OK ){
69573           goto abort_due_to_error;
69574         }
69575         if( u.bh.res ){
69576           u.bh.v = 1;   /* IMP: R-61914-48074 */
69577         }else{
69578           assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
69579           rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
69580           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
69581           if( u.bh.v>=MAX_ROWID ){
69582             u.bh.pC->useRandomRowid = 1;
69583           }else{
69584             u.bh.v++;   /* IMP: R-29538-34987 */
69585           }
69586         }
69587       }
69588
69589 #ifndef SQLITE_OMIT_AUTOINCREMENT
69590       if( pOp->p3 ){
69591         /* Assert that P3 is a valid memory cell. */
69592         assert( pOp->p3>0 );
69593         if( p->pFrame ){
69594           for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
69595           /* Assert that P3 is a valid memory cell. */
69596           assert( pOp->p3<=u.bh.pFrame->nMem );
69597           u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
69598         }else{
69599           /* Assert that P3 is a valid memory cell. */
69600           assert( pOp->p3<=p->nMem );
69601           u.bh.pMem = &aMem[pOp->p3];
69602           memAboutToChange(p, u.bh.pMem);
69603         }
69604         assert( memIsValid(u.bh.pMem) );
69605
69606         REGISTER_TRACE(pOp->p3, u.bh.pMem);
69607         sqlite3VdbeMemIntegerify(u.bh.pMem);
69608         assert( (u.bh.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
69609         if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
69610           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
69611           goto abort_due_to_error;
69612         }
69613         if( u.bh.v<u.bh.pMem->u.i+1 ){
69614           u.bh.v = u.bh.pMem->u.i + 1;
69615         }
69616         u.bh.pMem->u.i = u.bh.v;
69617       }
69618 #endif
69619
69620       sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
69621     }
69622     if( u.bh.pC->useRandomRowid ){
69623       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
69624       ** largest possible integer (9223372036854775807) then the database
69625       ** engine starts picking positive candidate ROWIDs at random until
69626       ** it finds one that is not previously used. */
69627       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
69628                              ** an AUTOINCREMENT table. */
69629       /* on the first attempt, simply do one more than previous */
69630       u.bh.v = lastRowid;
69631       u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69632       u.bh.v++; /* ensure non-zero */
69633       u.bh.cnt = 0;
69634       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
69635                                                  0, &u.bh.res))==SQLITE_OK)
69636             && (u.bh.res==0)
69637             && (++u.bh.cnt<100)){
69638         /* collision - try another random rowid */
69639         sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
69640         if( u.bh.cnt<5 ){
69641           /* try "small" random rowids for the initial attempts */
69642           u.bh.v &= 0xffffff;
69643         }else{
69644           u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69645         }
69646         u.bh.v++; /* ensure non-zero */
69647       }
69648       if( rc==SQLITE_OK && u.bh.res==0 ){
69649         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
69650         goto abort_due_to_error;
69651       }
69652       assert( u.bh.v>0 );  /* EV: R-40812-03570 */
69653     }
69654     u.bh.pC->rowidIsValid = 0;
69655     u.bh.pC->deferredMoveto = 0;
69656     u.bh.pC->cacheStatus = CACHE_STALE;
69657   }
69658   pOut->u.i = u.bh.v;
69659   break;
69660 }
69661
69662 /* Opcode: Insert P1 P2 P3 P4 P5
69663 **
69664 ** Write an entry into the table of cursor P1.  A new entry is
69665 ** created if it doesn't already exist or the data for an existing
69666 ** entry is overwritten.  The data is the value MEM_Blob stored in register
69667 ** number P2. The key is stored in register P3. The key must
69668 ** be a MEM_Int.
69669 **
69670 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
69671 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
69672 ** then rowid is stored for subsequent return by the
69673 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
69674 **
69675 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
69676 ** the last seek operation (OP_NotExists) was a success, then this
69677 ** operation will not attempt to find the appropriate row before doing
69678 ** the insert but will instead overwrite the row that the cursor is
69679 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
69680 ** has already positioned the cursor correctly.  This is an optimization
69681 ** that boosts performance by avoiding redundant seeks.
69682 **
69683 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
69684 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
69685 ** is part of an INSERT operation.  The difference is only important to
69686 ** the update hook.
69687 **
69688 ** Parameter P4 may point to a string containing the table-name, or
69689 ** may be NULL. If it is not NULL, then the update-hook
69690 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
69691 **
69692 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
69693 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
69694 ** and register P2 becomes ephemeral.  If the cursor is changed, the
69695 ** value of register P2 will then change.  Make sure this does not
69696 ** cause any problems.)
69697 **
69698 ** This instruction only works on tables.  The equivalent instruction
69699 ** for indices is OP_IdxInsert.
69700 */
69701 /* Opcode: InsertInt P1 P2 P3 P4 P5
69702 **
69703 ** This works exactly like OP_Insert except that the key is the
69704 ** integer value P3, not the value of the integer stored in register P3.
69705 */
69706 case OP_Insert:
69707 case OP_InsertInt: {
69708 #if 0  /* local variables moved into u.bi */
69709   Mem *pData;       /* MEM cell holding data for the record to be inserted */
69710   Mem *pKey;        /* MEM cell holding key  for the record */
69711   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
69712   VdbeCursor *pC;   /* Cursor to table into which insert is written */
69713   int nZero;        /* Number of zero-bytes to append */
69714   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
69715   const char *zDb;  /* database name - used by the update hook */
69716   const char *zTbl; /* Table name - used by the opdate hook */
69717   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
69718 #endif /* local variables moved into u.bi */
69719
69720   u.bi.pData = &aMem[pOp->p2];
69721   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69722   assert( memIsValid(u.bi.pData) );
69723   u.bi.pC = p->apCsr[pOp->p1];
69724   assert( u.bi.pC!=0 );
69725   assert( u.bi.pC->pCursor!=0 );
69726   assert( u.bi.pC->pseudoTableReg==0 );
69727   assert( u.bi.pC->isTable );
69728   REGISTER_TRACE(pOp->p2, u.bi.pData);
69729
69730   if( pOp->opcode==OP_Insert ){
69731     u.bi.pKey = &aMem[pOp->p3];
69732     assert( u.bi.pKey->flags & MEM_Int );
69733     assert( memIsValid(u.bi.pKey) );
69734     REGISTER_TRACE(pOp->p3, u.bi.pKey);
69735     u.bi.iKey = u.bi.pKey->u.i;
69736   }else{
69737     assert( pOp->opcode==OP_InsertInt );
69738     u.bi.iKey = pOp->p3;
69739   }
69740
69741   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
69742   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
69743   if( u.bi.pData->flags & MEM_Null ){
69744     u.bi.pData->z = 0;
69745     u.bi.pData->n = 0;
69746   }else{
69747     assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
69748   }
69749   u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
69750   if( u.bi.pData->flags & MEM_Zero ){
69751     u.bi.nZero = u.bi.pData->u.nZero;
69752   }else{
69753     u.bi.nZero = 0;
69754   }
69755   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
69756   rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
69757                           u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
69758                           pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
69759   );
69760   u.bi.pC->rowidIsValid = 0;
69761   u.bi.pC->deferredMoveto = 0;
69762   u.bi.pC->cacheStatus = CACHE_STALE;
69763
69764   /* Invoke the update-hook if required. */
69765   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69766     u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
69767     u.bi.zTbl = pOp->p4.z;
69768     u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
69769     assert( u.bi.pC->isTable );
69770     db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
69771     assert( u.bi.pC->iDb>=0 );
69772   }
69773   break;
69774 }
69775
69776 /* Opcode: Delete P1 P2 * P4 *
69777 **
69778 ** Delete the record at which the P1 cursor is currently pointing.
69779 **
69780 ** The cursor will be left pointing at either the next or the previous
69781 ** record in the table. If it is left pointing at the next record, then
69782 ** the next Next instruction will be a no-op.  Hence it is OK to delete
69783 ** a record from within an Next loop.
69784 **
69785 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
69786 ** incremented (otherwise not).
69787 **
69788 ** P1 must not be pseudo-table.  It has to be a real table with
69789 ** multiple rows.
69790 **
69791 ** If P4 is not NULL, then it is the name of the table that P1 is
69792 ** pointing to.  The update hook will be invoked, if it exists.
69793 ** If P4 is not NULL then the P1 cursor must have been positioned
69794 ** using OP_NotFound prior to invoking this opcode.
69795 */
69796 case OP_Delete: {
69797 #if 0  /* local variables moved into u.bj */
69798   i64 iKey;
69799   VdbeCursor *pC;
69800 #endif /* local variables moved into u.bj */
69801
69802   u.bj.iKey = 0;
69803   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69804   u.bj.pC = p->apCsr[pOp->p1];
69805   assert( u.bj.pC!=0 );
69806   assert( u.bj.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
69807
69808   /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
69809   ** row being deleted.
69810   */
69811   if( db->xUpdateCallback && pOp->p4.z ){
69812     assert( u.bj.pC->isTable );
69813     assert( u.bj.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
69814     u.bj.iKey = u.bj.pC->lastRowid;
69815   }
69816
69817   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
69818   ** OP_Column on the same table without any intervening operations that
69819   ** might move or invalidate the cursor.  Hence cursor u.bj.pC is always pointing
69820   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
69821   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
69822   ** to guard against future changes to the code generator.
69823   **/
69824   assert( u.bj.pC->deferredMoveto==0 );
69825   rc = sqlite3VdbeCursorMoveto(u.bj.pC);
69826   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69827
69828   sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
69829   rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
69830   u.bj.pC->cacheStatus = CACHE_STALE;
69831
69832   /* Invoke the update-hook if required. */
69833   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69834     const char *zDb = db->aDb[u.bj.pC->iDb].zName;
69835     const char *zTbl = pOp->p4.z;
69836     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
69837     assert( u.bj.pC->iDb>=0 );
69838   }
69839   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69840   break;
69841 }
69842 /* Opcode: ResetCount * * * * *
69843 **
69844 ** The value of the change counter is copied to the database handle
69845 ** change counter (returned by subsequent calls to sqlite3_changes()).
69846 ** Then the VMs internal change counter resets to 0.
69847 ** This is used by trigger programs.
69848 */
69849 case OP_ResetCount: {
69850   sqlite3VdbeSetChanges(db, p->nChange);
69851   p->nChange = 0;
69852   break;
69853 }
69854
69855 /* Opcode: SorterCompare P1 P2 P3
69856 **
69857 ** P1 is a sorter cursor. This instruction compares the record blob in
69858 ** register P3 with the entry that the sorter cursor currently points to.
69859 ** If, excluding the rowid fields at the end, the two records are a match,
69860 ** fall through to the next instruction. Otherwise, jump to instruction P2.
69861 */
69862 case OP_SorterCompare: {
69863 #if 0  /* local variables moved into u.bk */
69864   VdbeCursor *pC;
69865   int res;
69866 #endif /* local variables moved into u.bk */
69867
69868   u.bk.pC = p->apCsr[pOp->p1];
69869   assert( isSorter(u.bk.pC) );
69870   pIn3 = &aMem[pOp->p3];
69871   rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
69872   if( u.bk.res ){
69873     pc = pOp->p2-1;
69874   }
69875   break;
69876 };
69877
69878 /* Opcode: SorterData P1 P2 * * *
69879 **
69880 ** Write into register P2 the current sorter data for sorter cursor P1.
69881 */
69882 case OP_SorterData: {
69883 #if 0  /* local variables moved into u.bl */
69884   VdbeCursor *pC;
69885 #endif /* local variables moved into u.bl */
69886
69887 #ifndef SQLITE_OMIT_MERGE_SORT
69888   pOut = &aMem[pOp->p2];
69889   u.bl.pC = p->apCsr[pOp->p1];
69890   assert( u.bl.pC->isSorter );
69891   rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
69892 #else
69893   pOp->opcode = OP_RowKey;
69894   pc--;
69895 #endif
69896   break;
69897 }
69898
69899 /* Opcode: RowData P1 P2 * * *
69900 **
69901 ** Write into register P2 the complete row data for cursor P1.
69902 ** There is no interpretation of the data.
69903 ** It is just copied onto the P2 register exactly as
69904 ** it is found in the database file.
69905 **
69906 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69907 ** of a real table, not a pseudo-table.
69908 */
69909 /* Opcode: RowKey P1 P2 * * *
69910 **
69911 ** Write into register P2 the complete row key for cursor P1.
69912 ** There is no interpretation of the data.
69913 ** The key is copied onto the P3 register exactly as
69914 ** it is found in the database file.
69915 **
69916 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69917 ** of a real table, not a pseudo-table.
69918 */
69919 case OP_RowKey:
69920 case OP_RowData: {
69921 #if 0  /* local variables moved into u.bm */
69922   VdbeCursor *pC;
69923   BtCursor *pCrsr;
69924   u32 n;
69925   i64 n64;
69926 #endif /* local variables moved into u.bm */
69927
69928   pOut = &aMem[pOp->p2];
69929   memAboutToChange(p, pOut);
69930
69931   /* Note that RowKey and RowData are really exactly the same instruction */
69932   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69933   u.bm.pC = p->apCsr[pOp->p1];
69934   assert( u.bm.pC->isSorter==0 );
69935   assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
69936   assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
69937   assert( u.bm.pC!=0 );
69938   assert( u.bm.pC->nullRow==0 );
69939   assert( u.bm.pC->pseudoTableReg==0 );
69940   assert( u.bm.pC->pCursor!=0 );
69941   u.bm.pCrsr = u.bm.pC->pCursor;
69942   assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
69943
69944   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69945   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69946   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
69947   ** a no-op and can never fail.  But we leave it in place as a safety.
69948   */
69949   assert( u.bm.pC->deferredMoveto==0 );
69950   rc = sqlite3VdbeCursorMoveto(u.bm.pC);
69951   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69952
69953   if( u.bm.pC->isIndex ){
69954     assert( !u.bm.pC->isTable );
69955     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
69956     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
69957     if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
69958       goto too_big;
69959     }
69960     u.bm.n = (u32)u.bm.n64;
69961   }else{
69962     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
69963     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
69964     if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
69965       goto too_big;
69966     }
69967   }
69968   if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
69969     goto no_mem;
69970   }
69971   pOut->n = u.bm.n;
69972   MemSetTypeFlag(pOut, MEM_Blob);
69973   if( u.bm.pC->isIndex ){
69974     rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69975   }else{
69976     rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69977   }
69978   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
69979   UPDATE_MAX_BLOBSIZE(pOut);
69980   break;
69981 }
69982
69983 /* Opcode: Rowid P1 P2 * * *
69984 **
69985 ** Store in register P2 an integer which is the key of the table entry that
69986 ** P1 is currently point to.
69987 **
69988 ** P1 can be either an ordinary table or a virtual table.  There used to
69989 ** be a separate OP_VRowid opcode for use with virtual tables, but this
69990 ** one opcode now works for both table types.
69991 */
69992 case OP_Rowid: {                 /* out2-prerelease */
69993 #if 0  /* local variables moved into u.bn */
69994   VdbeCursor *pC;
69995   i64 v;
69996   sqlite3_vtab *pVtab;
69997   const sqlite3_module *pModule;
69998 #endif /* local variables moved into u.bn */
69999
70000   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70001   u.bn.pC = p->apCsr[pOp->p1];
70002   assert( u.bn.pC!=0 );
70003   assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
70004   if( u.bn.pC->nullRow ){
70005     pOut->flags = MEM_Null;
70006     break;
70007   }else if( u.bn.pC->deferredMoveto ){
70008     u.bn.v = u.bn.pC->movetoTarget;
70009 #ifndef SQLITE_OMIT_VIRTUALTABLE
70010   }else if( u.bn.pC->pVtabCursor ){
70011     u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
70012     u.bn.pModule = u.bn.pVtab->pModule;
70013     assert( u.bn.pModule->xRowid );
70014     rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
70015     importVtabErrMsg(p, u.bn.pVtab);
70016 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70017   }else{
70018     assert( u.bn.pC->pCursor!=0 );
70019     rc = sqlite3VdbeCursorMoveto(u.bn.pC);
70020     if( rc ) goto abort_due_to_error;
70021     if( u.bn.pC->rowidIsValid ){
70022       u.bn.v = u.bn.pC->lastRowid;
70023     }else{
70024       rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
70025       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
70026     }
70027   }
70028   pOut->u.i = u.bn.v;
70029   break;
70030 }
70031
70032 /* Opcode: NullRow P1 * * * *
70033 **
70034 ** Move the cursor P1 to a null row.  Any OP_Column operations
70035 ** that occur while the cursor is on the null row will always
70036 ** write a NULL.
70037 */
70038 case OP_NullRow: {
70039 #if 0  /* local variables moved into u.bo */
70040   VdbeCursor *pC;
70041 #endif /* local variables moved into u.bo */
70042
70043   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70044   u.bo.pC = p->apCsr[pOp->p1];
70045   assert( u.bo.pC!=0 );
70046   u.bo.pC->nullRow = 1;
70047   u.bo.pC->rowidIsValid = 0;
70048   assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
70049   if( u.bo.pC->pCursor ){
70050     sqlite3BtreeClearCursor(u.bo.pC->pCursor);
70051   }
70052   break;
70053 }
70054
70055 /* Opcode: Last P1 P2 * * *
70056 **
70057 ** The next use of the Rowid or Column or Next instruction for P1
70058 ** will refer to the last entry in the database table or index.
70059 ** If the table or index is empty and P2>0, then jump immediately to P2.
70060 ** If P2 is 0 or if the table or index is not empty, fall through
70061 ** to the following instruction.
70062 */
70063 case OP_Last: {        /* jump */
70064 #if 0  /* local variables moved into u.bp */
70065   VdbeCursor *pC;
70066   BtCursor *pCrsr;
70067   int res;
70068 #endif /* local variables moved into u.bp */
70069
70070   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70071   u.bp.pC = p->apCsr[pOp->p1];
70072   assert( u.bp.pC!=0 );
70073   u.bp.pCrsr = u.bp.pC->pCursor;
70074   u.bp.res = 0;
70075   if( ALWAYS(u.bp.pCrsr!=0) ){
70076     rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
70077   }
70078   u.bp.pC->nullRow = (u8)u.bp.res;
70079   u.bp.pC->deferredMoveto = 0;
70080   u.bp.pC->rowidIsValid = 0;
70081   u.bp.pC->cacheStatus = CACHE_STALE;
70082   if( pOp->p2>0 && u.bp.res ){
70083     pc = pOp->p2 - 1;
70084   }
70085   break;
70086 }
70087
70088
70089 /* Opcode: Sort P1 P2 * * *
70090 **
70091 ** This opcode does exactly the same thing as OP_Rewind except that
70092 ** it increments an undocumented global variable used for testing.
70093 **
70094 ** Sorting is accomplished by writing records into a sorting index,
70095 ** then rewinding that index and playing it back from beginning to
70096 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
70097 ** rewinding so that the global variable will be incremented and
70098 ** regression tests can determine whether or not the optimizer is
70099 ** correctly optimizing out sorts.
70100 */
70101 case OP_SorterSort:    /* jump */
70102 #ifdef SQLITE_OMIT_MERGE_SORT
70103   pOp->opcode = OP_Sort;
70104 #endif
70105 case OP_Sort: {        /* jump */
70106 #ifdef SQLITE_TEST
70107   sqlite3_sort_count++;
70108   sqlite3_search_count--;
70109 #endif
70110   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
70111   /* Fall through into OP_Rewind */
70112 }
70113 /* Opcode: Rewind P1 P2 * * *
70114 **
70115 ** The next use of the Rowid or Column or Next instruction for P1
70116 ** will refer to the first entry in the database table or index.
70117 ** If the table or index is empty and P2>0, then jump immediately to P2.
70118 ** If P2 is 0 or if the table or index is not empty, fall through
70119 ** to the following instruction.
70120 */
70121 case OP_Rewind: {        /* jump */
70122 #if 0  /* local variables moved into u.bq */
70123   VdbeCursor *pC;
70124   BtCursor *pCrsr;
70125   int res;
70126 #endif /* local variables moved into u.bq */
70127
70128   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70129   u.bq.pC = p->apCsr[pOp->p1];
70130   assert( u.bq.pC!=0 );
70131   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
70132   u.bq.res = 1;
70133   if( isSorter(u.bq.pC) ){
70134     rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
70135   }else{
70136     u.bq.pCrsr = u.bq.pC->pCursor;
70137     assert( u.bq.pCrsr );
70138     rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
70139     u.bq.pC->atFirst = u.bq.res==0 ?1:0;
70140     u.bq.pC->deferredMoveto = 0;
70141     u.bq.pC->cacheStatus = CACHE_STALE;
70142     u.bq.pC->rowidIsValid = 0;
70143   }
70144   u.bq.pC->nullRow = (u8)u.bq.res;
70145   assert( pOp->p2>0 && pOp->p2<p->nOp );
70146   if( u.bq.res ){
70147     pc = pOp->p2 - 1;
70148   }
70149   break;
70150 }
70151
70152 /* Opcode: Next P1 P2 * P4 P5
70153 **
70154 ** Advance cursor P1 so that it points to the next key/data pair in its
70155 ** table or index.  If there are no more key/value pairs then fall through
70156 ** to the following instruction.  But if the cursor advance was successful,
70157 ** jump immediately to P2.
70158 **
70159 ** The P1 cursor must be for a real table, not a pseudo-table.
70160 **
70161 ** P4 is always of type P4_ADVANCE. The function pointer points to
70162 ** sqlite3BtreeNext().
70163 **
70164 ** If P5 is positive and the jump is taken, then event counter
70165 ** number P5-1 in the prepared statement is incremented.
70166 **
70167 ** See also: Prev
70168 */
70169 /* Opcode: Prev P1 P2 * * P5
70170 **
70171 ** Back up cursor P1 so that it points to the previous key/data pair in its
70172 ** table or index.  If there is no previous key/value pairs then fall through
70173 ** to the following instruction.  But if the cursor backup was successful,
70174 ** jump immediately to P2.
70175 **
70176 ** The P1 cursor must be for a real table, not a pseudo-table.
70177 **
70178 ** P4 is always of type P4_ADVANCE. The function pointer points to
70179 ** sqlite3BtreePrevious().
70180 **
70181 ** If P5 is positive and the jump is taken, then event counter
70182 ** number P5-1 in the prepared statement is incremented.
70183 */
70184 case OP_SorterNext:    /* jump */
70185 #ifdef SQLITE_OMIT_MERGE_SORT
70186   pOp->opcode = OP_Next;
70187 #endif
70188 case OP_Prev:          /* jump */
70189 case OP_Next: {        /* jump */
70190 #if 0  /* local variables moved into u.br */
70191   VdbeCursor *pC;
70192   int res;
70193 #endif /* local variables moved into u.br */
70194
70195   CHECK_FOR_INTERRUPT;
70196   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70197   assert( pOp->p5<=ArraySize(p->aCounter) );
70198   u.br.pC = p->apCsr[pOp->p1];
70199   if( u.br.pC==0 ){
70200     break;  /* See ticket #2273 */
70201   }
70202   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
70203   if( isSorter(u.br.pC) ){
70204     assert( pOp->opcode==OP_SorterNext );
70205     rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
70206   }else{
70207     u.br.res = 1;
70208     assert( u.br.pC->deferredMoveto==0 );
70209     assert( u.br.pC->pCursor );
70210     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
70211     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
70212     rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
70213   }
70214   u.br.pC->nullRow = (u8)u.br.res;
70215   u.br.pC->cacheStatus = CACHE_STALE;
70216   if( u.br.res==0 ){
70217     pc = pOp->p2 - 1;
70218     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
70219 #ifdef SQLITE_TEST
70220     sqlite3_search_count++;
70221 #endif
70222   }
70223   u.br.pC->rowidIsValid = 0;
70224   break;
70225 }
70226
70227 /* Opcode: IdxInsert P1 P2 P3 * P5
70228 **
70229 ** Register P2 holds an SQL index key made using the
70230 ** MakeRecord instructions.  This opcode writes that key
70231 ** into the index P1.  Data for the entry is nil.
70232 **
70233 ** P3 is a flag that provides a hint to the b-tree layer that this
70234 ** insert is likely to be an append.
70235 **
70236 ** This instruction only works for indices.  The equivalent instruction
70237 ** for tables is OP_Insert.
70238 */
70239 case OP_SorterInsert:       /* in2 */
70240 #ifdef SQLITE_OMIT_MERGE_SORT
70241   pOp->opcode = OP_IdxInsert;
70242 #endif
70243 case OP_IdxInsert: {        /* in2 */
70244 #if 0  /* local variables moved into u.bs */
70245   VdbeCursor *pC;
70246   BtCursor *pCrsr;
70247   int nKey;
70248   const char *zKey;
70249 #endif /* local variables moved into u.bs */
70250
70251   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70252   u.bs.pC = p->apCsr[pOp->p1];
70253   assert( u.bs.pC!=0 );
70254   assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
70255   pIn2 = &aMem[pOp->p2];
70256   assert( pIn2->flags & MEM_Blob );
70257   u.bs.pCrsr = u.bs.pC->pCursor;
70258   if( ALWAYS(u.bs.pCrsr!=0) ){
70259     assert( u.bs.pC->isTable==0 );
70260     rc = ExpandBlob(pIn2);
70261     if( rc==SQLITE_OK ){
70262       if( isSorter(u.bs.pC) ){
70263         rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
70264       }else{
70265         u.bs.nKey = pIn2->n;
70266         u.bs.zKey = pIn2->z;
70267         rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
70268             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
70269             );
70270         assert( u.bs.pC->deferredMoveto==0 );
70271         u.bs.pC->cacheStatus = CACHE_STALE;
70272       }
70273     }
70274   }
70275   break;
70276 }
70277
70278 /* Opcode: IdxDelete P1 P2 P3 * *
70279 **
70280 ** The content of P3 registers starting at register P2 form
70281 ** an unpacked index key. This opcode removes that entry from the
70282 ** index opened by cursor P1.
70283 */
70284 case OP_IdxDelete: {
70285 #if 0  /* local variables moved into u.bt */
70286   VdbeCursor *pC;
70287   BtCursor *pCrsr;
70288   int res;
70289   UnpackedRecord r;
70290 #endif /* local variables moved into u.bt */
70291
70292   assert( pOp->p3>0 );
70293   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
70294   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70295   u.bt.pC = p->apCsr[pOp->p1];
70296   assert( u.bt.pC!=0 );
70297   u.bt.pCrsr = u.bt.pC->pCursor;
70298   if( ALWAYS(u.bt.pCrsr!=0) ){
70299     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
70300     u.bt.r.nField = (u16)pOp->p3;
70301     u.bt.r.flags = 0;
70302     u.bt.r.aMem = &aMem[pOp->p2];
70303 #ifdef SQLITE_DEBUG
70304     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
70305 #endif
70306     rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
70307     if( rc==SQLITE_OK && u.bt.res==0 ){
70308       rc = sqlite3BtreeDelete(u.bt.pCrsr);
70309     }
70310     assert( u.bt.pC->deferredMoveto==0 );
70311     u.bt.pC->cacheStatus = CACHE_STALE;
70312   }
70313   break;
70314 }
70315
70316 /* Opcode: IdxRowid P1 P2 * * *
70317 **
70318 ** Write into register P2 an integer which is the last entry in the record at
70319 ** the end of the index key pointed to by cursor P1.  This integer should be
70320 ** the rowid of the table entry to which this index entry points.
70321 **
70322 ** See also: Rowid, MakeRecord.
70323 */
70324 case OP_IdxRowid: {              /* out2-prerelease */
70325 #if 0  /* local variables moved into u.bu */
70326   BtCursor *pCrsr;
70327   VdbeCursor *pC;
70328   i64 rowid;
70329 #endif /* local variables moved into u.bu */
70330
70331   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70332   u.bu.pC = p->apCsr[pOp->p1];
70333   assert( u.bu.pC!=0 );
70334   u.bu.pCrsr = u.bu.pC->pCursor;
70335   pOut->flags = MEM_Null;
70336   if( ALWAYS(u.bu.pCrsr!=0) ){
70337     rc = sqlite3VdbeCursorMoveto(u.bu.pC);
70338     if( NEVER(rc) ) goto abort_due_to_error;
70339     assert( u.bu.pC->deferredMoveto==0 );
70340     assert( u.bu.pC->isTable==0 );
70341     if( !u.bu.pC->nullRow ){
70342       rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
70343       if( rc!=SQLITE_OK ){
70344         goto abort_due_to_error;
70345       }
70346       pOut->u.i = u.bu.rowid;
70347       pOut->flags = MEM_Int;
70348     }
70349   }
70350   break;
70351 }
70352
70353 /* Opcode: IdxGE P1 P2 P3 P4 P5
70354 **
70355 ** The P4 register values beginning with P3 form an unpacked index
70356 ** key that omits the ROWID.  Compare this key value against the index
70357 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70358 **
70359 ** If the P1 index entry is greater than or equal to the key value
70360 ** then jump to P2.  Otherwise fall through to the next instruction.
70361 **
70362 ** If P5 is non-zero then the key value is increased by an epsilon
70363 ** prior to the comparison.  This make the opcode work like IdxGT except
70364 ** that if the key from register P3 is a prefix of the key in the cursor,
70365 ** the result is false whereas it would be true with IdxGT.
70366 */
70367 /* Opcode: IdxLT P1 P2 P3 P4 P5
70368 **
70369 ** The P4 register values beginning with P3 form an unpacked index
70370 ** key that omits the ROWID.  Compare this key value against the index
70371 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70372 **
70373 ** If the P1 index entry is less than the key value then jump to P2.
70374 ** Otherwise fall through to the next instruction.
70375 **
70376 ** If P5 is non-zero then the key value is increased by an epsilon prior
70377 ** to the comparison.  This makes the opcode work like IdxLE.
70378 */
70379 case OP_IdxLT:          /* jump */
70380 case OP_IdxGE: {        /* jump */
70381 #if 0  /* local variables moved into u.bv */
70382   VdbeCursor *pC;
70383   int res;
70384   UnpackedRecord r;
70385 #endif /* local variables moved into u.bv */
70386
70387   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70388   u.bv.pC = p->apCsr[pOp->p1];
70389   assert( u.bv.pC!=0 );
70390   assert( u.bv.pC->isOrdered );
70391   if( ALWAYS(u.bv.pC->pCursor!=0) ){
70392     assert( u.bv.pC->deferredMoveto==0 );
70393     assert( pOp->p5==0 || pOp->p5==1 );
70394     assert( pOp->p4type==P4_INT32 );
70395     u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
70396     u.bv.r.nField = (u16)pOp->p4.i;
70397     if( pOp->p5 ){
70398       u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
70399     }else{
70400       u.bv.r.flags = UNPACKED_PREFIX_MATCH;
70401     }
70402     u.bv.r.aMem = &aMem[pOp->p3];
70403 #ifdef SQLITE_DEBUG
70404     { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
70405 #endif
70406     rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
70407     if( pOp->opcode==OP_IdxLT ){
70408       u.bv.res = -u.bv.res;
70409     }else{
70410       assert( pOp->opcode==OP_IdxGE );
70411       u.bv.res++;
70412     }
70413     if( u.bv.res>0 ){
70414       pc = pOp->p2 - 1 ;
70415     }
70416   }
70417   break;
70418 }
70419
70420 /* Opcode: Destroy P1 P2 P3 * *
70421 **
70422 ** Delete an entire database table or index whose root page in the database
70423 ** file is given by P1.
70424 **
70425 ** The table being destroyed is in the main database file if P3==0.  If
70426 ** P3==1 then the table to be clear is in the auxiliary database file
70427 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70428 **
70429 ** If AUTOVACUUM is enabled then it is possible that another root page
70430 ** might be moved into the newly deleted root page in order to keep all
70431 ** root pages contiguous at the beginning of the database.  The former
70432 ** value of the root page that moved - its value before the move occurred -
70433 ** is stored in register P2.  If no page
70434 ** movement was required (because the table being dropped was already
70435 ** the last one in the database) then a zero is stored in register P2.
70436 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
70437 **
70438 ** See also: Clear
70439 */
70440 case OP_Destroy: {     /* out2-prerelease */
70441 #if 0  /* local variables moved into u.bw */
70442   int iMoved;
70443   int iCnt;
70444   Vdbe *pVdbe;
70445   int iDb;
70446 #endif /* local variables moved into u.bw */
70447
70448 #ifndef SQLITE_OMIT_VIRTUALTABLE
70449   u.bw.iCnt = 0;
70450   for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
70451     if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
70452       u.bw.iCnt++;
70453     }
70454   }
70455 #else
70456   u.bw.iCnt = db->activeVdbeCnt;
70457 #endif
70458   pOut->flags = MEM_Null;
70459   if( u.bw.iCnt>1 ){
70460     rc = SQLITE_LOCKED;
70461     p->errorAction = OE_Abort;
70462   }else{
70463     u.bw.iDb = pOp->p3;
70464     assert( u.bw.iCnt==1 );
70465     assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
70466     rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
70467     pOut->flags = MEM_Int;
70468     pOut->u.i = u.bw.iMoved;
70469 #ifndef SQLITE_OMIT_AUTOVACUUM
70470     if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
70471       sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
70472       /* All OP_Destroy operations occur on the same btree */
70473       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
70474       resetSchemaOnFault = u.bw.iDb+1;
70475     }
70476 #endif
70477   }
70478   break;
70479 }
70480
70481 /* Opcode: Clear P1 P2 P3
70482 **
70483 ** Delete all contents of the database table or index whose root page
70484 ** in the database file is given by P1.  But, unlike Destroy, do not
70485 ** remove the table or index from the database file.
70486 **
70487 ** The table being clear is in the main database file if P2==0.  If
70488 ** P2==1 then the table to be clear is in the auxiliary database file
70489 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70490 **
70491 ** If the P3 value is non-zero, then the table referred to must be an
70492 ** intkey table (an SQL table, not an index). In this case the row change
70493 ** count is incremented by the number of rows in the table being cleared.
70494 ** If P3 is greater than zero, then the value stored in register P3 is
70495 ** also incremented by the number of rows in the table being cleared.
70496 **
70497 ** See also: Destroy
70498 */
70499 case OP_Clear: {
70500 #if 0  /* local variables moved into u.bx */
70501   int nChange;
70502 #endif /* local variables moved into u.bx */
70503
70504   u.bx.nChange = 0;
70505   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
70506   rc = sqlite3BtreeClearTable(
70507       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
70508   );
70509   if( pOp->p3 ){
70510     p->nChange += u.bx.nChange;
70511     if( pOp->p3>0 ){
70512       assert( memIsValid(&aMem[pOp->p3]) );
70513       memAboutToChange(p, &aMem[pOp->p3]);
70514       aMem[pOp->p3].u.i += u.bx.nChange;
70515     }
70516   }
70517   break;
70518 }
70519
70520 /* Opcode: CreateTable P1 P2 * * *
70521 **
70522 ** Allocate a new table in the main database file if P1==0 or in the
70523 ** auxiliary database file if P1==1 or in an attached database if
70524 ** P1>1.  Write the root page number of the new table into
70525 ** register P2
70526 **
70527 ** The difference between a table and an index is this:  A table must
70528 ** have a 4-byte integer key and can have arbitrary data.  An index
70529 ** has an arbitrary key but no data.
70530 **
70531 ** See also: CreateIndex
70532 */
70533 /* Opcode: CreateIndex P1 P2 * * *
70534 **
70535 ** Allocate a new index in the main database file if P1==0 or in the
70536 ** auxiliary database file if P1==1 or in an attached database if
70537 ** P1>1.  Write the root page number of the new table into
70538 ** register P2.
70539 **
70540 ** See documentation on OP_CreateTable for additional information.
70541 */
70542 case OP_CreateIndex:            /* out2-prerelease */
70543 case OP_CreateTable: {          /* out2-prerelease */
70544 #if 0  /* local variables moved into u.by */
70545   int pgno;
70546   int flags;
70547   Db *pDb;
70548 #endif /* local variables moved into u.by */
70549
70550   u.by.pgno = 0;
70551   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70552   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70553   u.by.pDb = &db->aDb[pOp->p1];
70554   assert( u.by.pDb->pBt!=0 );
70555   if( pOp->opcode==OP_CreateTable ){
70556     /* u.by.flags = BTREE_INTKEY; */
70557     u.by.flags = BTREE_INTKEY;
70558   }else{
70559     u.by.flags = BTREE_BLOBKEY;
70560   }
70561   rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
70562   pOut->u.i = u.by.pgno;
70563   break;
70564 }
70565
70566 /* Opcode: ParseSchema P1 * * P4 *
70567 **
70568 ** Read and parse all entries from the SQLITE_MASTER table of database P1
70569 ** that match the WHERE clause P4.
70570 **
70571 ** This opcode invokes the parser to create a new virtual machine,
70572 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
70573 */
70574 case OP_ParseSchema: {
70575 #if 0  /* local variables moved into u.bz */
70576   int iDb;
70577   const char *zMaster;
70578   char *zSql;
70579   InitData initData;
70580 #endif /* local variables moved into u.bz */
70581
70582   /* Any prepared statement that invokes this opcode will hold mutexes
70583   ** on every btree.  This is a prerequisite for invoking
70584   ** sqlite3InitCallback().
70585   */
70586 #ifdef SQLITE_DEBUG
70587   for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
70588     assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
70589   }
70590 #endif
70591
70592   u.bz.iDb = pOp->p1;
70593   assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
70594   assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
70595   /* Used to be a conditional */ {
70596     u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
70597     u.bz.initData.db = db;
70598     u.bz.initData.iDb = pOp->p1;
70599     u.bz.initData.pzErrMsg = &p->zErrMsg;
70600     u.bz.zSql = sqlite3MPrintf(db,
70601        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
70602        db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
70603     if( u.bz.zSql==0 ){
70604       rc = SQLITE_NOMEM;
70605     }else{
70606       assert( db->init.busy==0 );
70607       db->init.busy = 1;
70608       u.bz.initData.rc = SQLITE_OK;
70609       assert( !db->mallocFailed );
70610       rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
70611       if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
70612       sqlite3DbFree(db, u.bz.zSql);
70613       db->init.busy = 0;
70614     }
70615   }
70616   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
70617   if( rc==SQLITE_NOMEM ){
70618     goto no_mem;
70619   }
70620   break;
70621 }
70622
70623 #if !defined(SQLITE_OMIT_ANALYZE)
70624 /* Opcode: LoadAnalysis P1 * * * *
70625 **
70626 ** Read the sqlite_stat1 table for database P1 and load the content
70627 ** of that table into the internal index hash table.  This will cause
70628 ** the analysis to be used when preparing all subsequent queries.
70629 */
70630 case OP_LoadAnalysis: {
70631   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70632   rc = sqlite3AnalysisLoad(db, pOp->p1);
70633   break;
70634 }
70635 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
70636
70637 /* Opcode: DropTable P1 * * P4 *
70638 **
70639 ** Remove the internal (in-memory) data structures that describe
70640 ** the table named P4 in database P1.  This is called after a table
70641 ** is dropped in order to keep the internal representation of the
70642 ** schema consistent with what is on disk.
70643 */
70644 case OP_DropTable: {
70645   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
70646   break;
70647 }
70648
70649 /* Opcode: DropIndex P1 * * P4 *
70650 **
70651 ** Remove the internal (in-memory) data structures that describe
70652 ** the index named P4 in database P1.  This is called after an index
70653 ** is dropped in order to keep the internal representation of the
70654 ** schema consistent with what is on disk.
70655 */
70656 case OP_DropIndex: {
70657   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
70658   break;
70659 }
70660
70661 /* Opcode: DropTrigger P1 * * P4 *
70662 **
70663 ** Remove the internal (in-memory) data structures that describe
70664 ** the trigger named P4 in database P1.  This is called after a trigger
70665 ** is dropped in order to keep the internal representation of the
70666 ** schema consistent with what is on disk.
70667 */
70668 case OP_DropTrigger: {
70669   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
70670   break;
70671 }
70672
70673
70674 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
70675 /* Opcode: IntegrityCk P1 P2 P3 * P5
70676 **
70677 ** Do an analysis of the currently open database.  Store in
70678 ** register P1 the text of an error message describing any problems.
70679 ** If no problems are found, store a NULL in register P1.
70680 **
70681 ** The register P3 contains the maximum number of allowed errors.
70682 ** At most reg(P3) errors will be reported.
70683 ** In other words, the analysis stops as soon as reg(P1) errors are
70684 ** seen.  Reg(P1) is updated with the number of errors remaining.
70685 **
70686 ** The root page numbers of all tables in the database are integer
70687 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
70688 ** total.
70689 **
70690 ** If P5 is not zero, the check is done on the auxiliary database
70691 ** file, not the main database file.
70692 **
70693 ** This opcode is used to implement the integrity_check pragma.
70694 */
70695 case OP_IntegrityCk: {
70696 #if 0  /* local variables moved into u.ca */
70697   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
70698   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
70699   int j;          /* Loop counter */
70700   int nErr;       /* Number of errors reported */
70701   char *z;        /* Text of the error report */
70702   Mem *pnErr;     /* Register keeping track of errors remaining */
70703 #endif /* local variables moved into u.ca */
70704
70705   u.ca.nRoot = pOp->p2;
70706   assert( u.ca.nRoot>0 );
70707   u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
70708   if( u.ca.aRoot==0 ) goto no_mem;
70709   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70710   u.ca.pnErr = &aMem[pOp->p3];
70711   assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
70712   assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
70713   pIn1 = &aMem[pOp->p1];
70714   for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
70715     u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
70716   }
70717   u.ca.aRoot[u.ca.j] = 0;
70718   assert( pOp->p5<db->nDb );
70719   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
70720   u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
70721                                  (int)u.ca.pnErr->u.i, &u.ca.nErr);
70722   sqlite3DbFree(db, u.ca.aRoot);
70723   u.ca.pnErr->u.i -= u.ca.nErr;
70724   sqlite3VdbeMemSetNull(pIn1);
70725   if( u.ca.nErr==0 ){
70726     assert( u.ca.z==0 );
70727   }else if( u.ca.z==0 ){
70728     goto no_mem;
70729   }else{
70730     sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
70731   }
70732   UPDATE_MAX_BLOBSIZE(pIn1);
70733   sqlite3VdbeChangeEncoding(pIn1, encoding);
70734   break;
70735 }
70736 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
70737
70738 /* Opcode: RowSetAdd P1 P2 * * *
70739 **
70740 ** Insert the integer value held by register P2 into a boolean index
70741 ** held in register P1.
70742 **
70743 ** An assertion fails if P2 is not an integer.
70744 */
70745 case OP_RowSetAdd: {       /* in1, in2 */
70746   pIn1 = &aMem[pOp->p1];
70747   pIn2 = &aMem[pOp->p2];
70748   assert( (pIn2->flags & MEM_Int)!=0 );
70749   if( (pIn1->flags & MEM_RowSet)==0 ){
70750     sqlite3VdbeMemSetRowSet(pIn1);
70751     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70752   }
70753   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
70754   break;
70755 }
70756
70757 /* Opcode: RowSetRead P1 P2 P3 * *
70758 **
70759 ** Extract the smallest value from boolean index P1 and put that value into
70760 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
70761 ** unchanged and jump to instruction P2.
70762 */
70763 case OP_RowSetRead: {       /* jump, in1, out3 */
70764 #if 0  /* local variables moved into u.cb */
70765   i64 val;
70766 #endif /* local variables moved into u.cb */
70767   CHECK_FOR_INTERRUPT;
70768   pIn1 = &aMem[pOp->p1];
70769   if( (pIn1->flags & MEM_RowSet)==0
70770    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
70771   ){
70772     /* The boolean index is empty */
70773     sqlite3VdbeMemSetNull(pIn1);
70774     pc = pOp->p2 - 1;
70775   }else{
70776     /* A value was pulled from the index */
70777     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
70778   }
70779   break;
70780 }
70781
70782 /* Opcode: RowSetTest P1 P2 P3 P4
70783 **
70784 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
70785 ** contains a RowSet object and that RowSet object contains
70786 ** the value held in P3, jump to register P2. Otherwise, insert the
70787 ** integer in P3 into the RowSet and continue on to the
70788 ** next opcode.
70789 **
70790 ** The RowSet object is optimized for the case where successive sets
70791 ** of integers, where each set contains no duplicates. Each set
70792 ** of values is identified by a unique P4 value. The first set
70793 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
70794 ** non-negative.  For non-negative values of P4 only the lower 4
70795 ** bits are significant.
70796 **
70797 ** This allows optimizations: (a) when P4==0 there is no need to test
70798 ** the rowset object for P3, as it is guaranteed not to contain it,
70799 ** (b) when P4==-1 there is no need to insert the value, as it will
70800 ** never be tested for, and (c) when a value that is part of set X is
70801 ** inserted, there is no need to search to see if the same value was
70802 ** previously inserted as part of set X (only if it was previously
70803 ** inserted as part of some other set).
70804 */
70805 case OP_RowSetTest: {                     /* jump, in1, in3 */
70806 #if 0  /* local variables moved into u.cc */
70807   int iSet;
70808   int exists;
70809 #endif /* local variables moved into u.cc */
70810
70811   pIn1 = &aMem[pOp->p1];
70812   pIn3 = &aMem[pOp->p3];
70813   u.cc.iSet = pOp->p4.i;
70814   assert( pIn3->flags&MEM_Int );
70815
70816   /* If there is anything other than a rowset object in memory cell P1,
70817   ** delete it now and initialize P1 with an empty rowset
70818   */
70819   if( (pIn1->flags & MEM_RowSet)==0 ){
70820     sqlite3VdbeMemSetRowSet(pIn1);
70821     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70822   }
70823
70824   assert( pOp->p4type==P4_INT32 );
70825   assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
70826   if( u.cc.iSet ){
70827     u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
70828                                (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
70829                                pIn3->u.i);
70830     if( u.cc.exists ){
70831       pc = pOp->p2 - 1;
70832       break;
70833     }
70834   }
70835   if( u.cc.iSet>=0 ){
70836     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
70837   }
70838   break;
70839 }
70840
70841
70842 #ifndef SQLITE_OMIT_TRIGGER
70843
70844 /* Opcode: Program P1 P2 P3 P4 *
70845 **
70846 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
70847 **
70848 ** P1 contains the address of the memory cell that contains the first memory
70849 ** cell in an array of values used as arguments to the sub-program. P2
70850 ** contains the address to jump to if the sub-program throws an IGNORE
70851 ** exception using the RAISE() function. Register P3 contains the address
70852 ** of a memory cell in this (the parent) VM that is used to allocate the
70853 ** memory required by the sub-vdbe at runtime.
70854 **
70855 ** P4 is a pointer to the VM containing the trigger program.
70856 */
70857 case OP_Program: {        /* jump */
70858 #if 0  /* local variables moved into u.cd */
70859   int nMem;               /* Number of memory registers for sub-program */
70860   int nByte;              /* Bytes of runtime space required for sub-program */
70861   Mem *pRt;               /* Register to allocate runtime space */
70862   Mem *pMem;              /* Used to iterate through memory cells */
70863   Mem *pEnd;              /* Last memory cell in new array */
70864   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
70865   SubProgram *pProgram;   /* Sub-program to execute */
70866   void *t;                /* Token identifying trigger */
70867 #endif /* local variables moved into u.cd */
70868
70869   u.cd.pProgram = pOp->p4.pProgram;
70870   u.cd.pRt = &aMem[pOp->p3];
70871   assert( u.cd.pProgram->nOp>0 );
70872
70873   /* If the p5 flag is clear, then recursive invocation of triggers is
70874   ** disabled for backwards compatibility (p5 is set if this sub-program
70875   ** is really a trigger, not a foreign key action, and the flag set
70876   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70877   **
70878   ** It is recursive invocation of triggers, at the SQL level, that is
70879   ** disabled. In some cases a single trigger may generate more than one
70880   ** SubProgram (if the trigger may be executed with more than one different
70881   ** ON CONFLICT algorithm). SubProgram structures associated with a
70882   ** single trigger all have the same value for the SubProgram.token
70883   ** variable.  */
70884   if( pOp->p5 ){
70885     u.cd.t = u.cd.pProgram->token;
70886     for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
70887     if( u.cd.pFrame ) break;
70888   }
70889
70890   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
70891     rc = SQLITE_ERROR;
70892     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70893     break;
70894   }
70895
70896   /* Register u.cd.pRt is used to store the memory required to save the state
70897   ** of the current program, and the memory required at runtime to execute
70898   ** the trigger program. If this trigger has been fired before, then u.cd.pRt
70899   ** is already allocated. Otherwise, it must be initialized.  */
70900   if( (u.cd.pRt->flags&MEM_Frame)==0 ){
70901     /* SubProgram.nMem is set to the number of memory cells used by the
70902     ** program stored in SubProgram.aOp. As well as these, one memory
70903     ** cell is required for each cursor used by the program. Set local
70904     ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
70905     */
70906     u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
70907     u.cd.nByte = ROUND8(sizeof(VdbeFrame))
70908               + u.cd.nMem * sizeof(Mem)
70909               + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
70910               + u.cd.pProgram->nOnce * sizeof(u8);
70911     u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
70912     if( !u.cd.pFrame ){
70913       goto no_mem;
70914     }
70915     sqlite3VdbeMemRelease(u.cd.pRt);
70916     u.cd.pRt->flags = MEM_Frame;
70917     u.cd.pRt->u.pFrame = u.cd.pFrame;
70918
70919     u.cd.pFrame->v = p;
70920     u.cd.pFrame->nChildMem = u.cd.nMem;
70921     u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
70922     u.cd.pFrame->pc = pc;
70923     u.cd.pFrame->aMem = p->aMem;
70924     u.cd.pFrame->nMem = p->nMem;
70925     u.cd.pFrame->apCsr = p->apCsr;
70926     u.cd.pFrame->nCursor = p->nCursor;
70927     u.cd.pFrame->aOp = p->aOp;
70928     u.cd.pFrame->nOp = p->nOp;
70929     u.cd.pFrame->token = u.cd.pProgram->token;
70930     u.cd.pFrame->aOnceFlag = p->aOnceFlag;
70931     u.cd.pFrame->nOnceFlag = p->nOnceFlag;
70932
70933     u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
70934     for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
70935       u.cd.pMem->flags = MEM_Invalid;
70936       u.cd.pMem->db = db;
70937     }
70938   }else{
70939     u.cd.pFrame = u.cd.pRt->u.pFrame;
70940     assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
70941     assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
70942     assert( pc==u.cd.pFrame->pc );
70943   }
70944
70945   p->nFrame++;
70946   u.cd.pFrame->pParent = p->pFrame;
70947   u.cd.pFrame->lastRowid = lastRowid;
70948   u.cd.pFrame->nChange = p->nChange;
70949   p->nChange = 0;
70950   p->pFrame = u.cd.pFrame;
70951   p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
70952   p->nMem = u.cd.pFrame->nChildMem;
70953   p->nCursor = (u16)u.cd.pFrame->nChildCsr;
70954   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70955   p->aOp = aOp = u.cd.pProgram->aOp;
70956   p->nOp = u.cd.pProgram->nOp;
70957   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
70958   p->nOnceFlag = u.cd.pProgram->nOnce;
70959   pc = -1;
70960   memset(p->aOnceFlag, 0, p->nOnceFlag);
70961
70962   break;
70963 }
70964
70965 /* Opcode: Param P1 P2 * * *
70966 **
70967 ** This opcode is only ever present in sub-programs called via the
70968 ** OP_Program instruction. Copy a value currently stored in a memory
70969 ** cell of the calling (parent) frame to cell P2 in the current frames
70970 ** address space. This is used by trigger programs to access the new.*
70971 ** and old.* values.
70972 **
70973 ** The address of the cell in the parent frame is determined by adding
70974 ** the value of the P1 argument to the value of the P1 argument to the
70975 ** calling OP_Program instruction.
70976 */
70977 case OP_Param: {           /* out2-prerelease */
70978 #if 0  /* local variables moved into u.ce */
70979   VdbeFrame *pFrame;
70980   Mem *pIn;
70981 #endif /* local variables moved into u.ce */
70982   u.ce.pFrame = p->pFrame;
70983   u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
70984   sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
70985   break;
70986 }
70987
70988 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
70989
70990 #ifndef SQLITE_OMIT_FOREIGN_KEY
70991 /* Opcode: FkCounter P1 P2 * * *
70992 **
70993 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70994 ** If P1 is non-zero, the database constraint counter is incremented
70995 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
70996 ** statement counter is incremented (immediate foreign key constraints).
70997 */
70998 case OP_FkCounter: {
70999   if( pOp->p1 ){
71000     db->nDeferredCons += pOp->p2;
71001   }else{
71002     p->nFkConstraint += pOp->p2;
71003   }
71004   break;
71005 }
71006
71007 /* Opcode: FkIfZero P1 P2 * * *
71008 **
71009 ** This opcode tests if a foreign key constraint-counter is currently zero.
71010 ** If so, jump to instruction P2. Otherwise, fall through to the next
71011 ** instruction.
71012 **
71013 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
71014 ** is zero (the one that counts deferred constraint violations). If P1 is
71015 ** zero, the jump is taken if the statement constraint-counter is zero
71016 ** (immediate foreign key constraint violations).
71017 */
71018 case OP_FkIfZero: {         /* jump */
71019   if( pOp->p1 ){
71020     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
71021   }else{
71022     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
71023   }
71024   break;
71025 }
71026 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
71027
71028 #ifndef SQLITE_OMIT_AUTOINCREMENT
71029 /* Opcode: MemMax P1 P2 * * *
71030 **
71031 ** P1 is a register in the root frame of this VM (the root frame is
71032 ** different from the current frame if this instruction is being executed
71033 ** within a sub-program). Set the value of register P1 to the maximum of
71034 ** its current value and the value in register P2.
71035 **
71036 ** This instruction throws an error if the memory cell is not initially
71037 ** an integer.
71038 */
71039 case OP_MemMax: {        /* in2 */
71040 #if 0  /* local variables moved into u.cf */
71041   Mem *pIn1;
71042   VdbeFrame *pFrame;
71043 #endif /* local variables moved into u.cf */
71044   if( p->pFrame ){
71045     for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
71046     u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
71047   }else{
71048     u.cf.pIn1 = &aMem[pOp->p1];
71049   }
71050   assert( memIsValid(u.cf.pIn1) );
71051   sqlite3VdbeMemIntegerify(u.cf.pIn1);
71052   pIn2 = &aMem[pOp->p2];
71053   sqlite3VdbeMemIntegerify(pIn2);
71054   if( u.cf.pIn1->u.i<pIn2->u.i){
71055     u.cf.pIn1->u.i = pIn2->u.i;
71056   }
71057   break;
71058 }
71059 #endif /* SQLITE_OMIT_AUTOINCREMENT */
71060
71061 /* Opcode: IfPos P1 P2 * * *
71062 **
71063 ** If the value of register P1 is 1 or greater, jump to P2.
71064 **
71065 ** It is illegal to use this instruction on a register that does
71066 ** not contain an integer.  An assertion fault will result if you try.
71067 */
71068 case OP_IfPos: {        /* jump, in1 */
71069   pIn1 = &aMem[pOp->p1];
71070   assert( pIn1->flags&MEM_Int );
71071   if( pIn1->u.i>0 ){
71072      pc = pOp->p2 - 1;
71073   }
71074   break;
71075 }
71076
71077 /* Opcode: IfNeg P1 P2 * * *
71078 **
71079 ** If the value of register P1 is less than zero, jump to P2.
71080 **
71081 ** It is illegal to use this instruction on a register that does
71082 ** not contain an integer.  An assertion fault will result if you try.
71083 */
71084 case OP_IfNeg: {        /* jump, in1 */
71085   pIn1 = &aMem[pOp->p1];
71086   assert( pIn1->flags&MEM_Int );
71087   if( pIn1->u.i<0 ){
71088      pc = pOp->p2 - 1;
71089   }
71090   break;
71091 }
71092
71093 /* Opcode: IfZero P1 P2 P3 * *
71094 **
71095 ** The register P1 must contain an integer.  Add literal P3 to the
71096 ** value in register P1.  If the result is exactly 0, jump to P2.
71097 **
71098 ** It is illegal to use this instruction on a register that does
71099 ** not contain an integer.  An assertion fault will result if you try.
71100 */
71101 case OP_IfZero: {        /* jump, in1 */
71102   pIn1 = &aMem[pOp->p1];
71103   assert( pIn1->flags&MEM_Int );
71104   pIn1->u.i += pOp->p3;
71105   if( pIn1->u.i==0 ){
71106      pc = pOp->p2 - 1;
71107   }
71108   break;
71109 }
71110
71111 /* Opcode: AggStep * P2 P3 P4 P5
71112 **
71113 ** Execute the step function for an aggregate.  The
71114 ** function has P5 arguments.   P4 is a pointer to the FuncDef
71115 ** structure that specifies the function.  Use register
71116 ** P3 as the accumulator.
71117 **
71118 ** The P5 arguments are taken from register P2 and its
71119 ** successors.
71120 */
71121 case OP_AggStep: {
71122 #if 0  /* local variables moved into u.cg */
71123   int n;
71124   int i;
71125   Mem *pMem;
71126   Mem *pRec;
71127   sqlite3_context ctx;
71128   sqlite3_value **apVal;
71129 #endif /* local variables moved into u.cg */
71130
71131   u.cg.n = pOp->p5;
71132   assert( u.cg.n>=0 );
71133   u.cg.pRec = &aMem[pOp->p2];
71134   u.cg.apVal = p->apArg;
71135   assert( u.cg.apVal || u.cg.n==0 );
71136   for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
71137     assert( memIsValid(u.cg.pRec) );
71138     u.cg.apVal[u.cg.i] = u.cg.pRec;
71139     memAboutToChange(p, u.cg.pRec);
71140     sqlite3VdbeMemStoreType(u.cg.pRec);
71141   }
71142   u.cg.ctx.pFunc = pOp->p4.pFunc;
71143   assert( pOp->p3>0 && pOp->p3<=p->nMem );
71144   u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
71145   u.cg.pMem->n++;
71146   u.cg.ctx.s.flags = MEM_Null;
71147   u.cg.ctx.s.z = 0;
71148   u.cg.ctx.s.zMalloc = 0;
71149   u.cg.ctx.s.xDel = 0;
71150   u.cg.ctx.s.db = db;
71151   u.cg.ctx.isError = 0;
71152   u.cg.ctx.pColl = 0;
71153   u.cg.ctx.skipFlag = 0;
71154   if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
71155     assert( pOp>p->aOp );
71156     assert( pOp[-1].p4type==P4_COLLSEQ );
71157     assert( pOp[-1].opcode==OP_CollSeq );
71158     u.cg.ctx.pColl = pOp[-1].p4.pColl;
71159   }
71160   (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
71161   if( u.cg.ctx.isError ){
71162     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
71163     rc = u.cg.ctx.isError;
71164   }
71165   if( u.cg.ctx.skipFlag ){
71166     assert( pOp[-1].opcode==OP_CollSeq );
71167     u.cg.i = pOp[-1].p1;
71168     if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
71169   }
71170
71171   sqlite3VdbeMemRelease(&u.cg.ctx.s);
71172
71173   break;
71174 }
71175
71176 /* Opcode: AggFinal P1 P2 * P4 *
71177 **
71178 ** Execute the finalizer function for an aggregate.  P1 is
71179 ** the memory location that is the accumulator for the aggregate.
71180 **
71181 ** P2 is the number of arguments that the step function takes and
71182 ** P4 is a pointer to the FuncDef for this function.  The P2
71183 ** argument is not used by this opcode.  It is only there to disambiguate
71184 ** functions that can take varying numbers of arguments.  The
71185 ** P4 argument is only needed for the degenerate case where
71186 ** the step function was not previously called.
71187 */
71188 case OP_AggFinal: {
71189 #if 0  /* local variables moved into u.ch */
71190   Mem *pMem;
71191 #endif /* local variables moved into u.ch */
71192   assert( pOp->p1>0 && pOp->p1<=p->nMem );
71193   u.ch.pMem = &aMem[pOp->p1];
71194   assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
71195   rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
71196   if( rc ){
71197     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
71198   }
71199   sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
71200   UPDATE_MAX_BLOBSIZE(u.ch.pMem);
71201   if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
71202     goto too_big;
71203   }
71204   break;
71205 }
71206
71207 #ifndef SQLITE_OMIT_WAL
71208 /* Opcode: Checkpoint P1 P2 P3 * *
71209 **
71210 ** Checkpoint database P1. This is a no-op if P1 is not currently in
71211 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
71212 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
71213 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
71214 ** WAL after the checkpoint into mem[P3+1] and the number of pages
71215 ** in the WAL that have been checkpointed after the checkpoint
71216 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
71217 ** mem[P3+2] are initialized to -1.
71218 */
71219 case OP_Checkpoint: {
71220 #if 0  /* local variables moved into u.ci */
71221   int i;                          /* Loop counter */
71222   int aRes[3];                    /* Results */
71223   Mem *pMem;                      /* Write results here */
71224 #endif /* local variables moved into u.ci */
71225
71226   u.ci.aRes[0] = 0;
71227   u.ci.aRes[1] = u.ci.aRes[2] = -1;
71228   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
71229        || pOp->p2==SQLITE_CHECKPOINT_FULL
71230        || pOp->p2==SQLITE_CHECKPOINT_RESTART
71231   );
71232   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
71233   if( rc==SQLITE_BUSY ){
71234     rc = SQLITE_OK;
71235     u.ci.aRes[0] = 1;
71236   }
71237   for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
71238     sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
71239   }
71240   break;
71241 };
71242 #endif
71243
71244 #ifndef SQLITE_OMIT_PRAGMA
71245 /* Opcode: JournalMode P1 P2 P3 * P5
71246 **
71247 ** Change the journal mode of database P1 to P3. P3 must be one of the
71248 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
71249 ** modes (delete, truncate, persist, off and memory), this is a simple
71250 ** operation. No IO is required.
71251 **
71252 ** If changing into or out of WAL mode the procedure is more complicated.
71253 **
71254 ** Write a string containing the final journal-mode to register P2.
71255 */
71256 case OP_JournalMode: {    /* out2-prerelease */
71257 #if 0  /* local variables moved into u.cj */
71258   Btree *pBt;                     /* Btree to change journal mode of */
71259   Pager *pPager;                  /* Pager associated with pBt */
71260   int eNew;                       /* New journal mode */
71261   int eOld;                       /* The old journal mode */
71262 #ifndef SQLITE_OMIT_WAL
71263   const char *zFilename;          /* Name of database file for pPager */
71264 #endif
71265 #endif /* local variables moved into u.cj */
71266
71267   u.cj.eNew = pOp->p3;
71268   assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
71269        || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
71270        || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
71271        || u.cj.eNew==PAGER_JOURNALMODE_OFF
71272        || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
71273        || u.cj.eNew==PAGER_JOURNALMODE_WAL
71274        || u.cj.eNew==PAGER_JOURNALMODE_QUERY
71275   );
71276   assert( pOp->p1>=0 && pOp->p1<db->nDb );
71277
71278   u.cj.pBt = db->aDb[pOp->p1].pBt;
71279   u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
71280   u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
71281   if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
71282   if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
71283
71284 #ifndef SQLITE_OMIT_WAL
71285   u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
71286
71287   /* Do not allow a transition to journal_mode=WAL for a database
71288   ** in temporary storage or if the VFS does not support shared memory
71289   */
71290   if( u.cj.eNew==PAGER_JOURNALMODE_WAL
71291    && (sqlite3Strlen30(u.cj.zFilename)==0           /* Temp file */
71292        || !sqlite3PagerWalSupported(u.cj.pPager))   /* No shared-memory support */
71293   ){
71294     u.cj.eNew = u.cj.eOld;
71295   }
71296
71297   if( (u.cj.eNew!=u.cj.eOld)
71298    && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
71299   ){
71300     if( !db->autoCommit || db->activeVdbeCnt>1 ){
71301       rc = SQLITE_ERROR;
71302       sqlite3SetString(&p->zErrMsg, db,
71303           "cannot change %s wal mode from within a transaction",
71304           (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
71305       );
71306       break;
71307     }else{
71308
71309       if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
71310         /* If leaving WAL mode, close the log file. If successful, the call
71311         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
71312         ** file. An EXCLUSIVE lock may still be held on the database file
71313         ** after a successful return.
71314         */
71315         rc = sqlite3PagerCloseWal(u.cj.pPager);
71316         if( rc==SQLITE_OK ){
71317           sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71318         }
71319       }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
71320         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
71321         ** as an intermediate */
71322         sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
71323       }
71324
71325       /* Open a transaction on the database file. Regardless of the journal
71326       ** mode, this transaction always uses a rollback journal.
71327       */
71328       assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
71329       if( rc==SQLITE_OK ){
71330         rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
71331       }
71332     }
71333   }
71334 #endif /* ifndef SQLITE_OMIT_WAL */
71335
71336   if( rc ){
71337     u.cj.eNew = u.cj.eOld;
71338   }
71339   u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71340
71341   pOut = &aMem[pOp->p2];
71342   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
71343   pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
71344   pOut->n = sqlite3Strlen30(pOut->z);
71345   pOut->enc = SQLITE_UTF8;
71346   sqlite3VdbeChangeEncoding(pOut, encoding);
71347   break;
71348 };
71349 #endif /* SQLITE_OMIT_PRAGMA */
71350
71351 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
71352 /* Opcode: Vacuum * * * * *
71353 **
71354 ** Vacuum the entire database.  This opcode will cause other virtual
71355 ** machines to be created and run.  It may not be called from within
71356 ** a transaction.
71357 */
71358 case OP_Vacuum: {
71359   rc = sqlite3RunVacuum(&p->zErrMsg, db);
71360   break;
71361 }
71362 #endif
71363
71364 #if !defined(SQLITE_OMIT_AUTOVACUUM)
71365 /* Opcode: IncrVacuum P1 P2 * * *
71366 **
71367 ** Perform a single step of the incremental vacuum procedure on
71368 ** the P1 database. If the vacuum has finished, jump to instruction
71369 ** P2. Otherwise, fall through to the next instruction.
71370 */
71371 case OP_IncrVacuum: {        /* jump */
71372 #if 0  /* local variables moved into u.ck */
71373   Btree *pBt;
71374 #endif /* local variables moved into u.ck */
71375
71376   assert( pOp->p1>=0 && pOp->p1<db->nDb );
71377   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
71378   u.ck.pBt = db->aDb[pOp->p1].pBt;
71379   rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
71380   if( rc==SQLITE_DONE ){
71381     pc = pOp->p2 - 1;
71382     rc = SQLITE_OK;
71383   }
71384   break;
71385 }
71386 #endif
71387
71388 /* Opcode: Expire P1 * * * *
71389 **
71390 ** Cause precompiled statements to become expired. An expired statement
71391 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
71392 ** (via sqlite3_step()).
71393 **
71394 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
71395 ** then only the currently executing statement is affected.
71396 */
71397 case OP_Expire: {
71398   if( !pOp->p1 ){
71399     sqlite3ExpirePreparedStatements(db);
71400   }else{
71401     p->expired = 1;
71402   }
71403   break;
71404 }
71405
71406 #ifndef SQLITE_OMIT_SHARED_CACHE
71407 /* Opcode: TableLock P1 P2 P3 P4 *
71408 **
71409 ** Obtain a lock on a particular table. This instruction is only used when
71410 ** the shared-cache feature is enabled.
71411 **
71412 ** P1 is the index of the database in sqlite3.aDb[] of the database
71413 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
71414 ** a write lock if P3==1.
71415 **
71416 ** P2 contains the root-page of the table to lock.
71417 **
71418 ** P4 contains a pointer to the name of the table being locked. This is only
71419 ** used to generate an error message if the lock cannot be obtained.
71420 */
71421 case OP_TableLock: {
71422   u8 isWriteLock = (u8)pOp->p3;
71423   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
71424     int p1 = pOp->p1;
71425     assert( p1>=0 && p1<db->nDb );
71426     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
71427     assert( isWriteLock==0 || isWriteLock==1 );
71428     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
71429     if( (rc&0xFF)==SQLITE_LOCKED ){
71430       const char *z = pOp->p4.z;
71431       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
71432     }
71433   }
71434   break;
71435 }
71436 #endif /* SQLITE_OMIT_SHARED_CACHE */
71437
71438 #ifndef SQLITE_OMIT_VIRTUALTABLE
71439 /* Opcode: VBegin * * * P4 *
71440 **
71441 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
71442 ** xBegin method for that table.
71443 **
71444 ** Also, whether or not P4 is set, check that this is not being called from
71445 ** within a callback to a virtual table xSync() method. If it is, the error
71446 ** code will be set to SQLITE_LOCKED.
71447 */
71448 case OP_VBegin: {
71449 #if 0  /* local variables moved into u.cl */
71450   VTable *pVTab;
71451 #endif /* local variables moved into u.cl */
71452   u.cl.pVTab = pOp->p4.pVtab;
71453   rc = sqlite3VtabBegin(db, u.cl.pVTab);
71454   if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
71455   break;
71456 }
71457 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71458
71459 #ifndef SQLITE_OMIT_VIRTUALTABLE
71460 /* Opcode: VCreate P1 * * P4 *
71461 **
71462 ** P4 is the name of a virtual table in database P1. Call the xCreate method
71463 ** for that table.
71464 */
71465 case OP_VCreate: {
71466   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
71467   break;
71468 }
71469 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71470
71471 #ifndef SQLITE_OMIT_VIRTUALTABLE
71472 /* Opcode: VDestroy P1 * * P4 *
71473 **
71474 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
71475 ** of that table.
71476 */
71477 case OP_VDestroy: {
71478   p->inVtabMethod = 2;
71479   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
71480   p->inVtabMethod = 0;
71481   break;
71482 }
71483 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71484
71485 #ifndef SQLITE_OMIT_VIRTUALTABLE
71486 /* Opcode: VOpen P1 * * P4 *
71487 **
71488 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71489 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
71490 ** table and stores that cursor in P1.
71491 */
71492 case OP_VOpen: {
71493 #if 0  /* local variables moved into u.cm */
71494   VdbeCursor *pCur;
71495   sqlite3_vtab_cursor *pVtabCursor;
71496   sqlite3_vtab *pVtab;
71497   sqlite3_module *pModule;
71498 #endif /* local variables moved into u.cm */
71499
71500   u.cm.pCur = 0;
71501   u.cm.pVtabCursor = 0;
71502   u.cm.pVtab = pOp->p4.pVtab->pVtab;
71503   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
71504   assert(u.cm.pVtab && u.cm.pModule);
71505   rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
71506   importVtabErrMsg(p, u.cm.pVtab);
71507   if( SQLITE_OK==rc ){
71508     /* Initialize sqlite3_vtab_cursor base class */
71509     u.cm.pVtabCursor->pVtab = u.cm.pVtab;
71510
71511     /* Initialise vdbe cursor object */
71512     u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
71513     if( u.cm.pCur ){
71514       u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
71515       u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
71516     }else{
71517       db->mallocFailed = 1;
71518       u.cm.pModule->xClose(u.cm.pVtabCursor);
71519     }
71520   }
71521   break;
71522 }
71523 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71524
71525 #ifndef SQLITE_OMIT_VIRTUALTABLE
71526 /* Opcode: VFilter P1 P2 P3 P4 *
71527 **
71528 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
71529 ** the filtered result set is empty.
71530 **
71531 ** P4 is either NULL or a string that was generated by the xBestIndex
71532 ** method of the module.  The interpretation of the P4 string is left
71533 ** to the module implementation.
71534 **
71535 ** This opcode invokes the xFilter method on the virtual table specified
71536 ** by P1.  The integer query plan parameter to xFilter is stored in register
71537 ** P3. Register P3+1 stores the argc parameter to be passed to the
71538 ** xFilter method. Registers P3+2..P3+1+argc are the argc
71539 ** additional parameters which are passed to
71540 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
71541 **
71542 ** A jump is made to P2 if the result set after filtering would be empty.
71543 */
71544 case OP_VFilter: {   /* jump */
71545 #if 0  /* local variables moved into u.cn */
71546   int nArg;
71547   int iQuery;
71548   const sqlite3_module *pModule;
71549   Mem *pQuery;
71550   Mem *pArgc;
71551   sqlite3_vtab_cursor *pVtabCursor;
71552   sqlite3_vtab *pVtab;
71553   VdbeCursor *pCur;
71554   int res;
71555   int i;
71556   Mem **apArg;
71557 #endif /* local variables moved into u.cn */
71558
71559   u.cn.pQuery = &aMem[pOp->p3];
71560   u.cn.pArgc = &u.cn.pQuery[1];
71561   u.cn.pCur = p->apCsr[pOp->p1];
71562   assert( memIsValid(u.cn.pQuery) );
71563   REGISTER_TRACE(pOp->p3, u.cn.pQuery);
71564   assert( u.cn.pCur->pVtabCursor );
71565   u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
71566   u.cn.pVtab = u.cn.pVtabCursor->pVtab;
71567   u.cn.pModule = u.cn.pVtab->pModule;
71568
71569   /* Grab the index number and argc parameters */
71570   assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
71571   u.cn.nArg = (int)u.cn.pArgc->u.i;
71572   u.cn.iQuery = (int)u.cn.pQuery->u.i;
71573
71574   /* Invoke the xFilter method */
71575   {
71576     u.cn.res = 0;
71577     u.cn.apArg = p->apArg;
71578     for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
71579       u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
71580       sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
71581     }
71582
71583     p->inVtabMethod = 1;
71584     rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
71585     p->inVtabMethod = 0;
71586     importVtabErrMsg(p, u.cn.pVtab);
71587     if( rc==SQLITE_OK ){
71588       u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
71589     }
71590
71591     if( u.cn.res ){
71592       pc = pOp->p2 - 1;
71593     }
71594   }
71595   u.cn.pCur->nullRow = 0;
71596
71597   break;
71598 }
71599 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71600
71601 #ifndef SQLITE_OMIT_VIRTUALTABLE
71602 /* Opcode: VColumn P1 P2 P3 * *
71603 **
71604 ** Store the value of the P2-th column of
71605 ** the row of the virtual-table that the
71606 ** P1 cursor is pointing to into register P3.
71607 */
71608 case OP_VColumn: {
71609 #if 0  /* local variables moved into u.co */
71610   sqlite3_vtab *pVtab;
71611   const sqlite3_module *pModule;
71612   Mem *pDest;
71613   sqlite3_context sContext;
71614 #endif /* local variables moved into u.co */
71615
71616   VdbeCursor *pCur = p->apCsr[pOp->p1];
71617   assert( pCur->pVtabCursor );
71618   assert( pOp->p3>0 && pOp->p3<=p->nMem );
71619   u.co.pDest = &aMem[pOp->p3];
71620   memAboutToChange(p, u.co.pDest);
71621   if( pCur->nullRow ){
71622     sqlite3VdbeMemSetNull(u.co.pDest);
71623     break;
71624   }
71625   u.co.pVtab = pCur->pVtabCursor->pVtab;
71626   u.co.pModule = u.co.pVtab->pModule;
71627   assert( u.co.pModule->xColumn );
71628   memset(&u.co.sContext, 0, sizeof(u.co.sContext));
71629
71630   /* The output cell may already have a buffer allocated. Move
71631   ** the current contents to u.co.sContext.s so in case the user-function
71632   ** can use the already allocated buffer instead of allocating a
71633   ** new one.
71634   */
71635   sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
71636   MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
71637
71638   rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
71639   importVtabErrMsg(p, u.co.pVtab);
71640   if( u.co.sContext.isError ){
71641     rc = u.co.sContext.isError;
71642   }
71643
71644   /* Copy the result of the function to the P3 register. We
71645   ** do this regardless of whether or not an error occurred to ensure any
71646   ** dynamic allocation in u.co.sContext.s (a Mem struct) is  released.
71647   */
71648   sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
71649   sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
71650   REGISTER_TRACE(pOp->p3, u.co.pDest);
71651   UPDATE_MAX_BLOBSIZE(u.co.pDest);
71652
71653   if( sqlite3VdbeMemTooBig(u.co.pDest) ){
71654     goto too_big;
71655   }
71656   break;
71657 }
71658 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71659
71660 #ifndef SQLITE_OMIT_VIRTUALTABLE
71661 /* Opcode: VNext P1 P2 * * *
71662 **
71663 ** Advance virtual table P1 to the next row in its result set and
71664 ** jump to instruction P2.  Or, if the virtual table has reached
71665 ** the end of its result set, then fall through to the next instruction.
71666 */
71667 case OP_VNext: {   /* jump */
71668 #if 0  /* local variables moved into u.cp */
71669   sqlite3_vtab *pVtab;
71670   const sqlite3_module *pModule;
71671   int res;
71672   VdbeCursor *pCur;
71673 #endif /* local variables moved into u.cp */
71674
71675   u.cp.res = 0;
71676   u.cp.pCur = p->apCsr[pOp->p1];
71677   assert( u.cp.pCur->pVtabCursor );
71678   if( u.cp.pCur->nullRow ){
71679     break;
71680   }
71681   u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
71682   u.cp.pModule = u.cp.pVtab->pModule;
71683   assert( u.cp.pModule->xNext );
71684
71685   /* Invoke the xNext() method of the module. There is no way for the
71686   ** underlying implementation to return an error if one occurs during
71687   ** xNext(). Instead, if an error occurs, true is returned (indicating that
71688   ** data is available) and the error code returned when xColumn or
71689   ** some other method is next invoked on the save virtual table cursor.
71690   */
71691   p->inVtabMethod = 1;
71692   rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
71693   p->inVtabMethod = 0;
71694   importVtabErrMsg(p, u.cp.pVtab);
71695   if( rc==SQLITE_OK ){
71696     u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
71697   }
71698
71699   if( !u.cp.res ){
71700     /* If there is data, jump to P2 */
71701     pc = pOp->p2 - 1;
71702   }
71703   break;
71704 }
71705 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71706
71707 #ifndef SQLITE_OMIT_VIRTUALTABLE
71708 /* Opcode: VRename P1 * * P4 *
71709 **
71710 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71711 ** This opcode invokes the corresponding xRename method. The value
71712 ** in register P1 is passed as the zName argument to the xRename method.
71713 */
71714 case OP_VRename: {
71715 #if 0  /* local variables moved into u.cq */
71716   sqlite3_vtab *pVtab;
71717   Mem *pName;
71718 #endif /* local variables moved into u.cq */
71719
71720   u.cq.pVtab = pOp->p4.pVtab->pVtab;
71721   u.cq.pName = &aMem[pOp->p1];
71722   assert( u.cq.pVtab->pModule->xRename );
71723   assert( memIsValid(u.cq.pName) );
71724   REGISTER_TRACE(pOp->p1, u.cq.pName);
71725   assert( u.cq.pName->flags & MEM_Str );
71726   testcase( u.cq.pName->enc==SQLITE_UTF8 );
71727   testcase( u.cq.pName->enc==SQLITE_UTF16BE );
71728   testcase( u.cq.pName->enc==SQLITE_UTF16LE );
71729   rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
71730   if( rc==SQLITE_OK ){
71731     rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
71732     importVtabErrMsg(p, u.cq.pVtab);
71733     p->expired = 0;
71734   }
71735   break;
71736 }
71737 #endif
71738
71739 #ifndef SQLITE_OMIT_VIRTUALTABLE
71740 /* Opcode: VUpdate P1 P2 P3 P4 *
71741 **
71742 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71743 ** This opcode invokes the corresponding xUpdate method. P2 values
71744 ** are contiguous memory cells starting at P3 to pass to the xUpdate
71745 ** invocation. The value in register (P3+P2-1) corresponds to the
71746 ** p2th element of the argv array passed to xUpdate.
71747 **
71748 ** The xUpdate method will do a DELETE or an INSERT or both.
71749 ** The argv[0] element (which corresponds to memory cell P3)
71750 ** is the rowid of a row to delete.  If argv[0] is NULL then no
71751 ** deletion occurs.  The argv[1] element is the rowid of the new
71752 ** row.  This can be NULL to have the virtual table select the new
71753 ** rowid for itself.  The subsequent elements in the array are
71754 ** the values of columns in the new row.
71755 **
71756 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
71757 ** a row to delete.
71758 **
71759 ** P1 is a boolean flag. If it is set to true and the xUpdate call
71760 ** is successful, then the value returned by sqlite3_last_insert_rowid()
71761 ** is set to the value of the rowid for the row just inserted.
71762 */
71763 case OP_VUpdate: {
71764 #if 0  /* local variables moved into u.cr */
71765   sqlite3_vtab *pVtab;
71766   sqlite3_module *pModule;
71767   int nArg;
71768   int i;
71769   sqlite_int64 rowid;
71770   Mem **apArg;
71771   Mem *pX;
71772 #endif /* local variables moved into u.cr */
71773
71774   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
71775        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
71776   );
71777   u.cr.pVtab = pOp->p4.pVtab->pVtab;
71778   u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
71779   u.cr.nArg = pOp->p2;
71780   assert( pOp->p4type==P4_VTAB );
71781   if( ALWAYS(u.cr.pModule->xUpdate) ){
71782     u8 vtabOnConflict = db->vtabOnConflict;
71783     u.cr.apArg = p->apArg;
71784     u.cr.pX = &aMem[pOp->p3];
71785     for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
71786       assert( memIsValid(u.cr.pX) );
71787       memAboutToChange(p, u.cr.pX);
71788       sqlite3VdbeMemStoreType(u.cr.pX);
71789       u.cr.apArg[u.cr.i] = u.cr.pX;
71790       u.cr.pX++;
71791     }
71792     db->vtabOnConflict = pOp->p5;
71793     rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
71794     db->vtabOnConflict = vtabOnConflict;
71795     importVtabErrMsg(p, u.cr.pVtab);
71796     if( rc==SQLITE_OK && pOp->p1 ){
71797       assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
71798       db->lastRowid = lastRowid = u.cr.rowid;
71799     }
71800     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
71801       if( pOp->p5==OE_Ignore ){
71802         rc = SQLITE_OK;
71803       }else{
71804         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
71805       }
71806     }else{
71807       p->nChange++;
71808     }
71809   }
71810   break;
71811 }
71812 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71813
71814 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71815 /* Opcode: Pagecount P1 P2 * * *
71816 **
71817 ** Write the current number of pages in database P1 to memory cell P2.
71818 */
71819 case OP_Pagecount: {            /* out2-prerelease */
71820   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
71821   break;
71822 }
71823 #endif
71824
71825
71826 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71827 /* Opcode: MaxPgcnt P1 P2 P3 * *
71828 **
71829 ** Try to set the maximum page count for database P1 to the value in P3.
71830 ** Do not let the maximum page count fall below the current page count and
71831 ** do not change the maximum page count value if P3==0.
71832 **
71833 ** Store the maximum page count after the change in register P2.
71834 */
71835 case OP_MaxPgcnt: {            /* out2-prerelease */
71836   unsigned int newMax;
71837   Btree *pBt;
71838
71839   pBt = db->aDb[pOp->p1].pBt;
71840   newMax = 0;
71841   if( pOp->p3 ){
71842     newMax = sqlite3BtreeLastPage(pBt);
71843     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
71844   }
71845   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
71846   break;
71847 }
71848 #endif
71849
71850
71851 #ifndef SQLITE_OMIT_TRACE
71852 /* Opcode: Trace * * * P4 *
71853 **
71854 ** If tracing is enabled (by the sqlite3_trace()) interface, then
71855 ** the UTF-8 string contained in P4 is emitted on the trace callback.
71856 */
71857 case OP_Trace: {
71858 #if 0  /* local variables moved into u.cs */
71859   char *zTrace;
71860   char *z;
71861 #endif /* local variables moved into u.cs */
71862
71863   if( db->xTrace
71864    && !p->doingRerun
71865    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71866   ){
71867     u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
71868     db->xTrace(db->pTraceArg, u.cs.z);
71869     sqlite3DbFree(db, u.cs.z);
71870   }
71871 #ifdef SQLITE_DEBUG
71872   if( (db->flags & SQLITE_SqlTrace)!=0
71873    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71874   ){
71875     sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
71876   }
71877 #endif /* SQLITE_DEBUG */
71878   break;
71879 }
71880 #endif
71881
71882
71883 /* Opcode: Noop * * * * *
71884 **
71885 ** Do nothing.  This instruction is often useful as a jump
71886 ** destination.
71887 */
71888 /*
71889 ** The magic Explain opcode are only inserted when explain==2 (which
71890 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71891 ** This opcode records information from the optimizer.  It is the
71892 ** the same as a no-op.  This opcodesnever appears in a real VM program.
71893 */
71894 default: {          /* This is really OP_Noop and OP_Explain */
71895   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71896   break;
71897 }
71898
71899 /*****************************************************************************
71900 ** The cases of the switch statement above this line should all be indented
71901 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71902 ** readability.  From this point on down, the normal indentation rules are
71903 ** restored.
71904 *****************************************************************************/
71905     }
71906
71907 #ifdef VDBE_PROFILE
71908     {
71909       u64 elapsed = sqlite3Hwtime() - start;
71910       pOp->cycles += elapsed;
71911       pOp->cnt++;
71912 #if 0
71913         fprintf(stdout, "%10llu ", elapsed);
71914         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71915 #endif
71916     }
71917 #endif
71918
71919     /* The following code adds nothing to the actual functionality
71920     ** of the program.  It is only here for testing and debugging.
71921     ** On the other hand, it does burn CPU cycles every time through
71922     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
71923     */
71924 #ifndef NDEBUG
71925     assert( pc>=-1 && pc<p->nOp );
71926
71927 #ifdef SQLITE_DEBUG
71928     if( p->trace ){
71929       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71930       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71931         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71932       }
71933       if( pOp->opflags & OPFLG_OUT3 ){
71934         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71935       }
71936     }
71937 #endif  /* SQLITE_DEBUG */
71938 #endif  /* NDEBUG */
71939   }  /* The end of the for(;;) loop the loops through opcodes */
71940
71941   /* If we reach this point, it means that execution is finished with
71942   ** an error of some kind.
71943   */
71944 vdbe_error_halt:
71945   assert( rc );
71946   p->rc = rc;
71947   testcase( sqlite3GlobalConfig.xLog!=0 );
71948   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
71949                    pc, p->zSql, p->zErrMsg);
71950   sqlite3VdbeHalt(p);
71951   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
71952   rc = SQLITE_ERROR;
71953   if( resetSchemaOnFault>0 ){
71954     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
71955   }
71956
71957   /* This is the only way out of this procedure.  We have to
71958   ** release the mutexes on btrees that were acquired at the
71959   ** top. */
71960 vdbe_return:
71961   db->lastRowid = lastRowid;
71962   sqlite3VdbeLeave(p);
71963   return rc;
71964
71965   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
71966   ** is encountered.
71967   */
71968 too_big:
71969   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
71970   rc = SQLITE_TOOBIG;
71971   goto vdbe_error_halt;
71972
71973   /* Jump to here if a malloc() fails.
71974   */
71975 no_mem:
71976   db->mallocFailed = 1;
71977   sqlite3SetString(&p->zErrMsg, db, "out of memory");
71978   rc = SQLITE_NOMEM;
71979   goto vdbe_error_halt;
71980
71981   /* Jump to here for any other kind of fatal error.  The "rc" variable
71982   ** should hold the error number.
71983   */
71984 abort_due_to_error:
71985   assert( p->zErrMsg==0 );
71986   if( db->mallocFailed ) rc = SQLITE_NOMEM;
71987   if( rc!=SQLITE_IOERR_NOMEM ){
71988     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71989   }
71990   goto vdbe_error_halt;
71991
71992   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
71993   ** flag.
71994   */
71995 abort_due_to_interrupt:
71996   assert( db->u1.isInterrupted );
71997   rc = SQLITE_INTERRUPT;
71998   p->rc = rc;
71999   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
72000   goto vdbe_error_halt;
72001 }
72002
72003 /************** End of vdbe.c ************************************************/
72004 /************** Begin file vdbeblob.c ****************************************/
72005 /*
72006 ** 2007 May 1
72007 **
72008 ** The author disclaims copyright to this source code.  In place of
72009 ** a legal notice, here is a blessing:
72010 **
72011 **    May you do good and not evil.
72012 **    May you find forgiveness for yourself and forgive others.
72013 **    May you share freely, never taking more than you give.
72014 **
72015 *************************************************************************
72016 **
72017 ** This file contains code used to implement incremental BLOB I/O.
72018 */
72019
72020
72021 #ifndef SQLITE_OMIT_INCRBLOB
72022
72023 /*
72024 ** Valid sqlite3_blob* handles point to Incrblob structures.
72025 */
72026 typedef struct Incrblob Incrblob;
72027 struct Incrblob {
72028   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
72029   int nByte;              /* Size of open blob, in bytes */
72030   int iOffset;            /* Byte offset of blob in cursor data */
72031   int iCol;               /* Table column this handle is open on */
72032   BtCursor *pCsr;         /* Cursor pointing at blob row */
72033   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
72034   sqlite3 *db;            /* The associated database */
72035 };
72036
72037
72038 /*
72039 ** This function is used by both blob_open() and blob_reopen(). It seeks
72040 ** the b-tree cursor associated with blob handle p to point to row iRow.
72041 ** If successful, SQLITE_OK is returned and subsequent calls to
72042 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
72043 **
72044 ** If an error occurs, or if the specified row does not exist or does not
72045 ** contain a value of type TEXT or BLOB in the column nominated when the
72046 ** blob handle was opened, then an error code is returned and *pzErr may
72047 ** be set to point to a buffer containing an error message. It is the
72048 ** responsibility of the caller to free the error message buffer using
72049 ** sqlite3DbFree().
72050 **
72051 ** If an error does occur, then the b-tree cursor is closed. All subsequent
72052 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
72053 ** immediately return SQLITE_ABORT.
72054 */
72055 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
72056   int rc;                         /* Error code */
72057   char *zErr = 0;                 /* Error message */
72058   Vdbe *v = (Vdbe *)p->pStmt;
72059
72060   /* Set the value of the SQL statements only variable to integer iRow.
72061   ** This is done directly instead of using sqlite3_bind_int64() to avoid
72062   ** triggering asserts related to mutexes.
72063   */
72064   assert( v->aVar[0].flags&MEM_Int );
72065   v->aVar[0].u.i = iRow;
72066
72067   rc = sqlite3_step(p->pStmt);
72068   if( rc==SQLITE_ROW ){
72069     u32 type = v->apCsr[0]->aType[p->iCol];
72070     if( type<12 ){
72071       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
72072           type==0?"null": type==7?"real": "integer"
72073       );
72074       rc = SQLITE_ERROR;
72075       sqlite3_finalize(p->pStmt);
72076       p->pStmt = 0;
72077     }else{
72078       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
72079       p->nByte = sqlite3VdbeSerialTypeLen(type);
72080       p->pCsr =  v->apCsr[0]->pCursor;
72081       sqlite3BtreeEnterCursor(p->pCsr);
72082       sqlite3BtreeCacheOverflow(p->pCsr);
72083       sqlite3BtreeLeaveCursor(p->pCsr);
72084     }
72085   }
72086
72087   if( rc==SQLITE_ROW ){
72088     rc = SQLITE_OK;
72089   }else if( p->pStmt ){
72090     rc = sqlite3_finalize(p->pStmt);
72091     p->pStmt = 0;
72092     if( rc==SQLITE_OK ){
72093       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
72094       rc = SQLITE_ERROR;
72095     }else{
72096       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
72097     }
72098   }
72099
72100   assert( rc!=SQLITE_OK || zErr==0 );
72101   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
72102
72103   *pzErr = zErr;
72104   return rc;
72105 }
72106
72107 /*
72108 ** Open a blob handle.
72109 */
72110 SQLITE_API int sqlite3_blob_open(
72111   sqlite3* db,            /* The database connection */
72112   const char *zDb,        /* The attached database containing the blob */
72113   const char *zTable,     /* The table containing the blob */
72114   const char *zColumn,    /* The column containing the blob */
72115   sqlite_int64 iRow,      /* The row containing the glob */
72116   int flags,              /* True -> read/write access, false -> read-only */
72117   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
72118 ){
72119   int nAttempt = 0;
72120   int iCol;               /* Index of zColumn in row-record */
72121
72122   /* This VDBE program seeks a btree cursor to the identified
72123   ** db/table/row entry. The reason for using a vdbe program instead
72124   ** of writing code to use the b-tree layer directly is that the
72125   ** vdbe program will take advantage of the various transaction,
72126   ** locking and error handling infrastructure built into the vdbe.
72127   **
72128   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
72129   ** Code external to the Vdbe then "borrows" the b-tree cursor and
72130   ** uses it to implement the blob_read(), blob_write() and
72131   ** blob_bytes() functions.
72132   **
72133   ** The sqlite3_blob_close() function finalizes the vdbe program,
72134   ** which closes the b-tree cursor and (possibly) commits the
72135   ** transaction.
72136   */
72137   static const VdbeOpList openBlob[] = {
72138     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
72139     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
72140     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
72141
72142     /* One of the following two instructions is replaced by an OP_Noop. */
72143     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
72144     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
72145
72146     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
72147     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
72148     {OP_Column, 0, 0, 1},          /* 7  */
72149     {OP_ResultRow, 1, 0, 0},       /* 8  */
72150     {OP_Goto, 0, 5, 0},            /* 9  */
72151     {OP_Close, 0, 0, 0},           /* 10 */
72152     {OP_Halt, 0, 0, 0},            /* 11 */
72153   };
72154
72155   int rc = SQLITE_OK;
72156   char *zErr = 0;
72157   Table *pTab;
72158   Parse *pParse = 0;
72159   Incrblob *pBlob = 0;
72160
72161   flags = !!flags;                /* flags = (flags ? 1 : 0); */
72162   *ppBlob = 0;
72163
72164   sqlite3_mutex_enter(db->mutex);
72165
72166   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
72167   if( !pBlob ) goto blob_open_out;
72168   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
72169   if( !pParse ) goto blob_open_out;
72170
72171   do {
72172     memset(pParse, 0, sizeof(Parse));
72173     pParse->db = db;
72174     sqlite3DbFree(db, zErr);
72175     zErr = 0;
72176
72177     sqlite3BtreeEnterAll(db);
72178     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
72179     if( pTab && IsVirtual(pTab) ){
72180       pTab = 0;
72181       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
72182     }
72183 #ifndef SQLITE_OMIT_VIEW
72184     if( pTab && pTab->pSelect ){
72185       pTab = 0;
72186       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
72187     }
72188 #endif
72189     if( !pTab ){
72190       if( pParse->zErrMsg ){
72191         sqlite3DbFree(db, zErr);
72192         zErr = pParse->zErrMsg;
72193         pParse->zErrMsg = 0;
72194       }
72195       rc = SQLITE_ERROR;
72196       sqlite3BtreeLeaveAll(db);
72197       goto blob_open_out;
72198     }
72199
72200     /* Now search pTab for the exact column. */
72201     for(iCol=0; iCol<pTab->nCol; iCol++) {
72202       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
72203         break;
72204       }
72205     }
72206     if( iCol==pTab->nCol ){
72207       sqlite3DbFree(db, zErr);
72208       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
72209       rc = SQLITE_ERROR;
72210       sqlite3BtreeLeaveAll(db);
72211       goto blob_open_out;
72212     }
72213
72214     /* If the value is being opened for writing, check that the
72215     ** column is not indexed, and that it is not part of a foreign key.
72216     ** It is against the rules to open a column to which either of these
72217     ** descriptions applies for writing.  */
72218     if( flags ){
72219       const char *zFault = 0;
72220       Index *pIdx;
72221 #ifndef SQLITE_OMIT_FOREIGN_KEY
72222       if( db->flags&SQLITE_ForeignKeys ){
72223         /* Check that the column is not part of an FK child key definition. It
72224         ** is not necessary to check if it is part of a parent key, as parent
72225         ** key columns must be indexed. The check below will pick up this
72226         ** case.  */
72227         FKey *pFKey;
72228         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
72229           int j;
72230           for(j=0; j<pFKey->nCol; j++){
72231             if( pFKey->aCol[j].iFrom==iCol ){
72232               zFault = "foreign key";
72233             }
72234           }
72235         }
72236       }
72237 #endif
72238       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72239         int j;
72240         for(j=0; j<pIdx->nColumn; j++){
72241           if( pIdx->aiColumn[j]==iCol ){
72242             zFault = "indexed";
72243           }
72244         }
72245       }
72246       if( zFault ){
72247         sqlite3DbFree(db, zErr);
72248         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
72249         rc = SQLITE_ERROR;
72250         sqlite3BtreeLeaveAll(db);
72251         goto blob_open_out;
72252       }
72253     }
72254
72255     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
72256     assert( pBlob->pStmt || db->mallocFailed );
72257     if( pBlob->pStmt ){
72258       Vdbe *v = (Vdbe *)pBlob->pStmt;
72259       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72260
72261       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
72262
72263
72264       /* Configure the OP_Transaction */
72265       sqlite3VdbeChangeP1(v, 0, iDb);
72266       sqlite3VdbeChangeP2(v, 0, flags);
72267
72268       /* Configure the OP_VerifyCookie */
72269       sqlite3VdbeChangeP1(v, 1, iDb);
72270       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
72271       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
72272
72273       /* Make sure a mutex is held on the table to be accessed */
72274       sqlite3VdbeUsesBtree(v, iDb);
72275
72276       /* Configure the OP_TableLock instruction */
72277 #ifdef SQLITE_OMIT_SHARED_CACHE
72278       sqlite3VdbeChangeToNoop(v, 2);
72279 #else
72280       sqlite3VdbeChangeP1(v, 2, iDb);
72281       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
72282       sqlite3VdbeChangeP3(v, 2, flags);
72283       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
72284 #endif
72285
72286       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
72287       ** parameter of the other to pTab->tnum.  */
72288       sqlite3VdbeChangeToNoop(v, 4 - flags);
72289       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
72290       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
72291
72292       /* Configure the number of columns. Configure the cursor to
72293       ** think that the table has one more column than it really
72294       ** does. An OP_Column to retrieve this imaginary column will
72295       ** always return an SQL NULL. This is useful because it means
72296       ** we can invoke OP_Column to fill in the vdbe cursors type
72297       ** and offset cache without causing any IO.
72298       */
72299       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
72300       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
72301       if( !db->mallocFailed ){
72302         pParse->nVar = 1;
72303         pParse->nMem = 1;
72304         pParse->nTab = 1;
72305         sqlite3VdbeMakeReady(v, pParse);
72306       }
72307     }
72308
72309     pBlob->flags = flags;
72310     pBlob->iCol = iCol;
72311     pBlob->db = db;
72312     sqlite3BtreeLeaveAll(db);
72313     if( db->mallocFailed ){
72314       goto blob_open_out;
72315     }
72316     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
72317     rc = blobSeekToRow(pBlob, iRow, &zErr);
72318   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
72319
72320 blob_open_out:
72321   if( rc==SQLITE_OK && db->mallocFailed==0 ){
72322     *ppBlob = (sqlite3_blob *)pBlob;
72323   }else{
72324     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
72325     sqlite3DbFree(db, pBlob);
72326   }
72327   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72328   sqlite3DbFree(db, zErr);
72329   sqlite3StackFree(db, pParse);
72330   rc = sqlite3ApiExit(db, rc);
72331   sqlite3_mutex_leave(db->mutex);
72332   return rc;
72333 }
72334
72335 /*
72336 ** Close a blob handle that was previously created using
72337 ** sqlite3_blob_open().
72338 */
72339 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
72340   Incrblob *p = (Incrblob *)pBlob;
72341   int rc;
72342   sqlite3 *db;
72343
72344   if( p ){
72345     db = p->db;
72346     sqlite3_mutex_enter(db->mutex);
72347     rc = sqlite3_finalize(p->pStmt);
72348     sqlite3DbFree(db, p);
72349     sqlite3_mutex_leave(db->mutex);
72350   }else{
72351     rc = SQLITE_OK;
72352   }
72353   return rc;
72354 }
72355
72356 /*
72357 ** Perform a read or write operation on a blob
72358 */
72359 static int blobReadWrite(
72360   sqlite3_blob *pBlob,
72361   void *z,
72362   int n,
72363   int iOffset,
72364   int (*xCall)(BtCursor*, u32, u32, void*)
72365 ){
72366   int rc;
72367   Incrblob *p = (Incrblob *)pBlob;
72368   Vdbe *v;
72369   sqlite3 *db;
72370
72371   if( p==0 ) return SQLITE_MISUSE_BKPT;
72372   db = p->db;
72373   sqlite3_mutex_enter(db->mutex);
72374   v = (Vdbe*)p->pStmt;
72375
72376   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
72377     /* Request is out of range. Return a transient error. */
72378     rc = SQLITE_ERROR;
72379     sqlite3Error(db, SQLITE_ERROR, 0);
72380   }else if( v==0 ){
72381     /* If there is no statement handle, then the blob-handle has
72382     ** already been invalidated. Return SQLITE_ABORT in this case.
72383     */
72384     rc = SQLITE_ABORT;
72385   }else{
72386     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
72387     ** returned, clean-up the statement handle.
72388     */
72389     assert( db == v->db );
72390     sqlite3BtreeEnterCursor(p->pCsr);
72391     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
72392     sqlite3BtreeLeaveCursor(p->pCsr);
72393     if( rc==SQLITE_ABORT ){
72394       sqlite3VdbeFinalize(v);
72395       p->pStmt = 0;
72396     }else{
72397       db->errCode = rc;
72398       v->rc = rc;
72399     }
72400   }
72401   rc = sqlite3ApiExit(db, rc);
72402   sqlite3_mutex_leave(db->mutex);
72403   return rc;
72404 }
72405
72406 /*
72407 ** Read data from a blob handle.
72408 */
72409 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
72410   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
72411 }
72412
72413 /*
72414 ** Write data to a blob handle.
72415 */
72416 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
72417   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
72418 }
72419
72420 /*
72421 ** Query a blob handle for the size of the data.
72422 **
72423 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
72424 ** so no mutex is required for access.
72425 */
72426 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
72427   Incrblob *p = (Incrblob *)pBlob;
72428   return (p && p->pStmt) ? p->nByte : 0;
72429 }
72430
72431 /*
72432 ** Move an existing blob handle to point to a different row of the same
72433 ** database table.
72434 **
72435 ** If an error occurs, or if the specified row does not exist or does not
72436 ** contain a blob or text value, then an error code is returned and the
72437 ** database handle error code and message set. If this happens, then all
72438 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
72439 ** immediately return SQLITE_ABORT.
72440 */
72441 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
72442   int rc;
72443   Incrblob *p = (Incrblob *)pBlob;
72444   sqlite3 *db;
72445
72446   if( p==0 ) return SQLITE_MISUSE_BKPT;
72447   db = p->db;
72448   sqlite3_mutex_enter(db->mutex);
72449
72450   if( p->pStmt==0 ){
72451     /* If there is no statement handle, then the blob-handle has
72452     ** already been invalidated. Return SQLITE_ABORT in this case.
72453     */
72454     rc = SQLITE_ABORT;
72455   }else{
72456     char *zErr;
72457     rc = blobSeekToRow(p, iRow, &zErr);
72458     if( rc!=SQLITE_OK ){
72459       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72460       sqlite3DbFree(db, zErr);
72461     }
72462     assert( rc!=SQLITE_SCHEMA );
72463   }
72464
72465   rc = sqlite3ApiExit(db, rc);
72466   assert( rc==SQLITE_OK || p->pStmt==0 );
72467   sqlite3_mutex_leave(db->mutex);
72468   return rc;
72469 }
72470
72471 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
72472
72473 /************** End of vdbeblob.c ********************************************/
72474 /************** Begin file vdbesort.c ****************************************/
72475 /*
72476 ** 2011 July 9
72477 **
72478 ** The author disclaims copyright to this source code.  In place of
72479 ** a legal notice, here is a blessing:
72480 **
72481 **    May you do good and not evil.
72482 **    May you find forgiveness for yourself and forgive others.
72483 **    May you share freely, never taking more than you give.
72484 **
72485 *************************************************************************
72486 ** This file contains code for the VdbeSorter object, used in concert with
72487 ** a VdbeCursor to sort large numbers of keys (as may be required, for
72488 ** example, by CREATE INDEX statements on tables too large to fit in main
72489 ** memory).
72490 */
72491
72492
72493 #ifndef SQLITE_OMIT_MERGE_SORT
72494
72495 typedef struct VdbeSorterIter VdbeSorterIter;
72496 typedef struct SorterRecord SorterRecord;
72497 typedef struct FileWriter FileWriter;
72498
72499 /*
72500 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
72501 **
72502 ** As keys are added to the sorter, they are written to disk in a series
72503 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
72504 ** the same as the cache-size allowed for temporary databases. In order
72505 ** to allow the caller to extract keys from the sorter in sorted order,
72506 ** all PMAs currently stored on disk must be merged together. This comment
72507 ** describes the data structure used to do so. The structure supports
72508 ** merging any number of arrays in a single pass with no redundant comparison
72509 ** operations.
72510 **
72511 ** The aIter[] array contains an iterator for each of the PMAs being merged.
72512 ** An aIter[] iterator either points to a valid key or else is at EOF. For
72513 ** the purposes of the paragraphs below, we assume that the array is actually
72514 ** N elements in size, where N is the smallest power of 2 greater to or equal
72515 ** to the number of iterators being merged. The extra aIter[] elements are
72516 ** treated as if they are empty (always at EOF).
72517 **
72518 ** The aTree[] array is also N elements in size. The value of N is stored in
72519 ** the VdbeSorter.nTree variable.
72520 **
72521 ** The final (N/2) elements of aTree[] contain the results of comparing
72522 ** pairs of iterator keys together. Element i contains the result of
72523 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
72524 ** aTree element is set to the index of it.
72525 **
72526 ** For the purposes of this comparison, EOF is considered greater than any
72527 ** other key value. If the keys are equal (only possible with two EOF
72528 ** values), it doesn't matter which index is stored.
72529 **
72530 ** The (N/4) elements of aTree[] that preceed the final (N/2) described
72531 ** above contains the index of the smallest of each block of 4 iterators.
72532 ** And so on. So that aTree[1] contains the index of the iterator that
72533 ** currently points to the smallest key value. aTree[0] is unused.
72534 **
72535 ** Example:
72536 **
72537 **     aIter[0] -> Banana
72538 **     aIter[1] -> Feijoa
72539 **     aIter[2] -> Elderberry
72540 **     aIter[3] -> Currant
72541 **     aIter[4] -> Grapefruit
72542 **     aIter[5] -> Apple
72543 **     aIter[6] -> Durian
72544 **     aIter[7] -> EOF
72545 **
72546 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
72547 **
72548 ** The current element is "Apple" (the value of the key indicated by
72549 ** iterator 5). When the Next() operation is invoked, iterator 5 will
72550 ** be advanced to the next key in its segment. Say the next key is
72551 ** "Eggplant":
72552 **
72553 **     aIter[5] -> Eggplant
72554 **
72555 ** The contents of aTree[] are updated first by comparing the new iterator
72556 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
72557 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
72558 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
72559 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
72560 ** so the value written into element 1 of the array is 0. As follows:
72561 **
72562 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
72563 **
72564 ** In other words, each time we advance to the next sorter element, log2(N)
72565 ** key comparison operations are required, where N is the number of segments
72566 ** being merged (rounded up to the next power of 2).
72567 */
72568 struct VdbeSorter {
72569   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
72570   i64 iReadOff;                   /* Current read offset within file pTemp1 */
72571   int nInMemory;                  /* Current size of pRecord list as PMA */
72572   int nTree;                      /* Used size of aTree/aIter (power of 2) */
72573   int nPMA;                       /* Number of PMAs stored in pTemp1 */
72574   int mnPmaSize;                  /* Minimum PMA size, in bytes */
72575   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
72576   VdbeSorterIter *aIter;          /* Array of iterators to merge */
72577   int *aTree;                     /* Current state of incremental merge */
72578   sqlite3_file *pTemp1;           /* PMA file 1 */
72579   SorterRecord *pRecord;          /* Head of in-memory record list */
72580   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
72581 };
72582
72583 /*
72584 ** The following type is an iterator for a PMA. It caches the current key in
72585 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
72586 */
72587 struct VdbeSorterIter {
72588   i64 iReadOff;                   /* Current read offset */
72589   i64 iEof;                       /* 1 byte past EOF for this iterator */
72590   int nAlloc;                     /* Bytes of space at aAlloc */
72591   int nKey;                       /* Number of bytes in key */
72592   sqlite3_file *pFile;            /* File iterator is reading from */
72593   u8 *aAlloc;                     /* Allocated space */
72594   u8 *aKey;                       /* Pointer to current key */
72595   u8 *aBuffer;                    /* Current read buffer */
72596   int nBuffer;                    /* Size of read buffer in bytes */
72597 };
72598
72599 /*
72600 ** An instance of this structure is used to organize the stream of records
72601 ** being written to files by the merge-sort code into aligned, page-sized
72602 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
72603 ** faster on many operating systems.
72604 */
72605 struct FileWriter {
72606   int eFWErr;                     /* Non-zero if in an error state */
72607   u8 *aBuffer;                    /* Pointer to write buffer */
72608   int nBuffer;                    /* Size of write buffer in bytes */
72609   int iBufStart;                  /* First byte of buffer to write */
72610   int iBufEnd;                    /* Last byte of buffer to write */
72611   i64 iWriteOff;                  /* Offset of start of buffer in file */
72612   sqlite3_file *pFile;            /* File to write to */
72613 };
72614
72615 /*
72616 ** A structure to store a single record. All in-memory records are connected
72617 ** together into a linked list headed at VdbeSorter.pRecord using the
72618 ** SorterRecord.pNext pointer.
72619 */
72620 struct SorterRecord {
72621   void *pVal;
72622   int nVal;
72623   SorterRecord *pNext;
72624 };
72625
72626 /* Minimum allowable value for the VdbeSorter.nWorking variable */
72627 #define SORTER_MIN_WORKING 10
72628
72629 /* Maximum number of segments to merge in a single pass. */
72630 #define SORTER_MAX_MERGE_COUNT 16
72631
72632 /*
72633 ** Free all memory belonging to the VdbeSorterIter object passed as the second
72634 ** argument. All structure fields are set to zero before returning.
72635 */
72636 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
72637   sqlite3DbFree(db, pIter->aAlloc);
72638   sqlite3DbFree(db, pIter->aBuffer);
72639   memset(pIter, 0, sizeof(VdbeSorterIter));
72640 }
72641
72642 /*
72643 ** Read nByte bytes of data from the stream of data iterated by object p.
72644 ** If successful, set *ppOut to point to a buffer containing the data
72645 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
72646 ** error code.
72647 **
72648 ** The buffer indicated by *ppOut may only be considered valid until the
72649 ** next call to this function.
72650 */
72651 static int vdbeSorterIterRead(
72652   sqlite3 *db,                    /* Database handle (for malloc) */
72653   VdbeSorterIter *p,              /* Iterator */
72654   int nByte,                      /* Bytes of data to read */
72655   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
72656 ){
72657   int iBuf;                       /* Offset within buffer to read from */
72658   int nAvail;                     /* Bytes of data available in buffer */
72659   assert( p->aBuffer );
72660
72661   /* If there is no more data to be read from the buffer, read the next
72662   ** p->nBuffer bytes of data from the file into it. Or, if there are less
72663   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
72664   iBuf = p->iReadOff % p->nBuffer;
72665   if( iBuf==0 ){
72666     int nRead;                    /* Bytes to read from disk */
72667     int rc;                       /* sqlite3OsRead() return code */
72668
72669     /* Determine how many bytes of data to read. */
72670     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
72671       nRead = p->nBuffer;
72672     }else{
72673       nRead = (int)(p->iEof - p->iReadOff);
72674     }
72675     assert( nRead>0 );
72676
72677     /* Read data from the file. Return early if an error occurs. */
72678     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
72679     assert( rc!=SQLITE_IOERR_SHORT_READ );
72680     if( rc!=SQLITE_OK ) return rc;
72681   }
72682   nAvail = p->nBuffer - iBuf;
72683
72684   if( nByte<=nAvail ){
72685     /* The requested data is available in the in-memory buffer. In this
72686     ** case there is no need to make a copy of the data, just return a
72687     ** pointer into the buffer to the caller.  */
72688     *ppOut = &p->aBuffer[iBuf];
72689     p->iReadOff += nByte;
72690   }else{
72691     /* The requested data is not all available in the in-memory buffer.
72692     ** In this case, allocate space at p->aAlloc[] to copy the requested
72693     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
72694     int nRem;                     /* Bytes remaining to copy */
72695
72696     /* Extend the p->aAlloc[] allocation if required. */
72697     if( p->nAlloc<nByte ){
72698       int nNew = p->nAlloc*2;
72699       while( nByte>nNew ) nNew = nNew*2;
72700       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
72701       if( !p->aAlloc ) return SQLITE_NOMEM;
72702       p->nAlloc = nNew;
72703     }
72704
72705     /* Copy as much data as is available in the buffer into the start of
72706     ** p->aAlloc[].  */
72707     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
72708     p->iReadOff += nAvail;
72709     nRem = nByte - nAvail;
72710
72711     /* The following loop copies up to p->nBuffer bytes per iteration into
72712     ** the p->aAlloc[] buffer.  */
72713     while( nRem>0 ){
72714       int rc;                     /* vdbeSorterIterRead() return code */
72715       int nCopy;                  /* Number of bytes to copy */
72716       u8 *aNext;                  /* Pointer to buffer to copy data from */
72717
72718       nCopy = nRem;
72719       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
72720       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
72721       if( rc!=SQLITE_OK ) return rc;
72722       assert( aNext!=p->aAlloc );
72723       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
72724       nRem -= nCopy;
72725     }
72726
72727     *ppOut = p->aAlloc;
72728   }
72729
72730   return SQLITE_OK;
72731 }
72732
72733 /*
72734 ** Read a varint from the stream of data accessed by p. Set *pnOut to
72735 ** the value read.
72736 */
72737 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
72738   int iBuf;
72739
72740   iBuf = p->iReadOff % p->nBuffer;
72741   if( iBuf && (p->nBuffer-iBuf)>=9 ){
72742     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
72743   }else{
72744     u8 aVarint[16], *a;
72745     int i = 0, rc;
72746     do{
72747       rc = vdbeSorterIterRead(db, p, 1, &a);
72748       if( rc ) return rc;
72749       aVarint[(i++)&0xf] = a[0];
72750     }while( (a[0]&0x80)!=0 );
72751     sqlite3GetVarint(aVarint, pnOut);
72752   }
72753
72754   return SQLITE_OK;
72755 }
72756
72757
72758 /*
72759 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
72760 ** no error occurs, or an SQLite error code if one does.
72761 */
72762 static int vdbeSorterIterNext(
72763   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
72764   VdbeSorterIter *pIter           /* Iterator to advance */
72765 ){
72766   int rc;                         /* Return Code */
72767   u64 nRec = 0;                   /* Size of record in bytes */
72768
72769   if( pIter->iReadOff>=pIter->iEof ){
72770     /* This is an EOF condition */
72771     vdbeSorterIterZero(db, pIter);
72772     return SQLITE_OK;
72773   }
72774
72775   rc = vdbeSorterIterVarint(db, pIter, &nRec);
72776   if( rc==SQLITE_OK ){
72777     pIter->nKey = (int)nRec;
72778     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
72779   }
72780
72781   return rc;
72782 }
72783
72784 /*
72785 ** Initialize iterator pIter to scan through the PMA stored in file pFile
72786 ** starting at offset iStart and ending at offset iEof-1. This function
72787 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
72788 ** PMA is empty).
72789 */
72790 static int vdbeSorterIterInit(
72791   sqlite3 *db,                    /* Database handle */
72792   const VdbeSorter *pSorter,      /* Sorter object */
72793   i64 iStart,                     /* Start offset in pFile */
72794   VdbeSorterIter *pIter,          /* Iterator to populate */
72795   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
72796 ){
72797   int rc = SQLITE_OK;
72798   int nBuf;
72799
72800   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72801
72802   assert( pSorter->iWriteOff>iStart );
72803   assert( pIter->aAlloc==0 );
72804   assert( pIter->aBuffer==0 );
72805   pIter->pFile = pSorter->pTemp1;
72806   pIter->iReadOff = iStart;
72807   pIter->nAlloc = 128;
72808   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
72809   pIter->nBuffer = nBuf;
72810   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
72811
72812   if( !pIter->aBuffer ){
72813     rc = SQLITE_NOMEM;
72814   }else{
72815     int iBuf;
72816
72817     iBuf = iStart % nBuf;
72818     if( iBuf ){
72819       int nRead = nBuf - iBuf;
72820       if( (iStart + nRead) > pSorter->iWriteOff ){
72821         nRead = (int)(pSorter->iWriteOff - iStart);
72822       }
72823       rc = sqlite3OsRead(
72824           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
72825       );
72826       assert( rc!=SQLITE_IOERR_SHORT_READ );
72827     }
72828
72829     if( rc==SQLITE_OK ){
72830       u64 nByte;                       /* Size of PMA in bytes */
72831       pIter->iEof = pSorter->iWriteOff;
72832       rc = vdbeSorterIterVarint(db, pIter, &nByte);
72833       pIter->iEof = pIter->iReadOff + nByte;
72834       *pnByte += nByte;
72835     }
72836   }
72837
72838   if( rc==SQLITE_OK ){
72839     rc = vdbeSorterIterNext(db, pIter);
72840   }
72841   return rc;
72842 }
72843
72844
72845 /*
72846 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
72847 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
72848 ** used by the comparison. If an error occurs, return an SQLite error code.
72849 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
72850 ** value, depending on whether key1 is smaller, equal to or larger than key2.
72851 **
72852 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
72853 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
72854 ** is true and key1 contains even a single NULL value, it is considered to
72855 ** be less than key2. Even if key2 also contains NULL values.
72856 **
72857 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
72858 ** has been allocated and contains an unpacked record that is used as key2.
72859 */
72860 static void vdbeSorterCompare(
72861   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
72862   int bOmitRowid,                 /* Ignore rowid field at end of keys */
72863   const void *pKey1, int nKey1,   /* Left side of comparison */
72864   const void *pKey2, int nKey2,   /* Right side of comparison */
72865   int *pRes                       /* OUT: Result of comparison */
72866 ){
72867   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
72868   VdbeSorter *pSorter = pCsr->pSorter;
72869   UnpackedRecord *r2 = pSorter->pUnpacked;
72870   int i;
72871
72872   if( pKey2 ){
72873     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
72874   }
72875
72876   if( bOmitRowid ){
72877     r2->nField = pKeyInfo->nField;
72878     assert( r2->nField>0 );
72879     for(i=0; i<r2->nField; i++){
72880       if( r2->aMem[i].flags & MEM_Null ){
72881         *pRes = -1;
72882         return;
72883       }
72884     }
72885     r2->flags |= UNPACKED_PREFIX_MATCH;
72886   }
72887
72888   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
72889 }
72890
72891 /*
72892 ** This function is called to compare two iterator keys when merging
72893 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
72894 ** value to recalculate.
72895 */
72896 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
72897   VdbeSorter *pSorter = pCsr->pSorter;
72898   int i1;
72899   int i2;
72900   int iRes;
72901   VdbeSorterIter *p1;
72902   VdbeSorterIter *p2;
72903
72904   assert( iOut<pSorter->nTree && iOut>0 );
72905
72906   if( iOut>=(pSorter->nTree/2) ){
72907     i1 = (iOut - pSorter->nTree/2) * 2;
72908     i2 = i1 + 1;
72909   }else{
72910     i1 = pSorter->aTree[iOut*2];
72911     i2 = pSorter->aTree[iOut*2+1];
72912   }
72913
72914   p1 = &pSorter->aIter[i1];
72915   p2 = &pSorter->aIter[i2];
72916
72917   if( p1->pFile==0 ){
72918     iRes = i2;
72919   }else if( p2->pFile==0 ){
72920     iRes = i1;
72921   }else{
72922     int res;
72923     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
72924     vdbeSorterCompare(
72925         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
72926     );
72927     if( res<=0 ){
72928       iRes = i1;
72929     }else{
72930       iRes = i2;
72931     }
72932   }
72933
72934   pSorter->aTree[iOut] = iRes;
72935   return SQLITE_OK;
72936 }
72937
72938 /*
72939 ** Initialize the temporary index cursor just opened as a sorter cursor.
72940 */
72941 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
72942   int pgsz;                       /* Page size of main database */
72943   int mxCache;                    /* Cache size */
72944   VdbeSorter *pSorter;            /* The new sorter */
72945   char *d;                        /* Dummy */
72946
72947   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
72948   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
72949   if( pSorter==0 ){
72950     return SQLITE_NOMEM;
72951   }
72952
72953   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72954   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
72955   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72956
72957   if( !sqlite3TempInMemory(db) ){
72958     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72959     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72960     mxCache = db->aDb[0].pSchema->cache_size;
72961     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72962     pSorter->mxPmaSize = mxCache * pgsz;
72963   }
72964
72965   return SQLITE_OK;
72966 }
72967
72968 /*
72969 ** Free the list of sorted records starting at pRecord.
72970 */
72971 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
72972   SorterRecord *p;
72973   SorterRecord *pNext;
72974   for(p=pRecord; p; p=pNext){
72975     pNext = p->pNext;
72976     sqlite3DbFree(db, p);
72977   }
72978 }
72979
72980 /*
72981 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
72982 */
72983 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
72984   VdbeSorter *pSorter = pCsr->pSorter;
72985   if( pSorter ){
72986     if( pSorter->aIter ){
72987       int i;
72988       for(i=0; i<pSorter->nTree; i++){
72989         vdbeSorterIterZero(db, &pSorter->aIter[i]);
72990       }
72991       sqlite3DbFree(db, pSorter->aIter);
72992     }
72993     if( pSorter->pTemp1 ){
72994       sqlite3OsCloseFree(pSorter->pTemp1);
72995     }
72996     vdbeSorterRecordFree(db, pSorter->pRecord);
72997     sqlite3DbFree(db, pSorter->pUnpacked);
72998     sqlite3DbFree(db, pSorter);
72999     pCsr->pSorter = 0;
73000   }
73001 }
73002
73003 /*
73004 ** Allocate space for a file-handle and open a temporary file. If successful,
73005 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
73006 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
73007 */
73008 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
73009   int dummy;
73010   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
73011       SQLITE_OPEN_TEMP_JOURNAL |
73012       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
73013       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
73014   );
73015 }
73016
73017 /*
73018 ** Merge the two sorted lists p1 and p2 into a single list.
73019 ** Set *ppOut to the head of the new list.
73020 */
73021 static void vdbeSorterMerge(
73022   const VdbeCursor *pCsr,         /* For pKeyInfo */
73023   SorterRecord *p1,               /* First list to merge */
73024   SorterRecord *p2,               /* Second list to merge */
73025   SorterRecord **ppOut            /* OUT: Head of merged list */
73026 ){
73027   SorterRecord *pFinal = 0;
73028   SorterRecord **pp = &pFinal;
73029   void *pVal2 = p2 ? p2->pVal : 0;
73030
73031   while( p1 && p2 ){
73032     int res;
73033     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
73034     if( res<=0 ){
73035       *pp = p1;
73036       pp = &p1->pNext;
73037       p1 = p1->pNext;
73038       pVal2 = 0;
73039     }else{
73040       *pp = p2;
73041        pp = &p2->pNext;
73042       p2 = p2->pNext;
73043       if( p2==0 ) break;
73044       pVal2 = p2->pVal;
73045     }
73046   }
73047   *pp = p1 ? p1 : p2;
73048   *ppOut = pFinal;
73049 }
73050
73051 /*
73052 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
73053 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
73054 ** occurs.
73055 */
73056 static int vdbeSorterSort(const VdbeCursor *pCsr){
73057   int i;
73058   SorterRecord **aSlot;
73059   SorterRecord *p;
73060   VdbeSorter *pSorter = pCsr->pSorter;
73061
73062   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
73063   if( !aSlot ){
73064     return SQLITE_NOMEM;
73065   }
73066
73067   p = pSorter->pRecord;
73068   while( p ){
73069     SorterRecord *pNext = p->pNext;
73070     p->pNext = 0;
73071     for(i=0; aSlot[i]; i++){
73072       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
73073       aSlot[i] = 0;
73074     }
73075     aSlot[i] = p;
73076     p = pNext;
73077   }
73078
73079   p = 0;
73080   for(i=0; i<64; i++){
73081     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
73082   }
73083   pSorter->pRecord = p;
73084
73085   sqlite3_free(aSlot);
73086   return SQLITE_OK;
73087 }
73088
73089 /*
73090 ** Initialize a file-writer object.
73091 */
73092 static void fileWriterInit(
73093   sqlite3 *db,                    /* Database (for malloc) */
73094   sqlite3_file *pFile,            /* File to write to */
73095   FileWriter *p,                  /* Object to populate */
73096   i64 iStart                      /* Offset of pFile to begin writing at */
73097 ){
73098   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
73099
73100   memset(p, 0, sizeof(FileWriter));
73101   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
73102   if( !p->aBuffer ){
73103     p->eFWErr = SQLITE_NOMEM;
73104   }else{
73105     p->iBufEnd = p->iBufStart = (iStart % nBuf);
73106     p->iWriteOff = iStart - p->iBufStart;
73107     p->nBuffer = nBuf;
73108     p->pFile = pFile;
73109   }
73110 }
73111
73112 /*
73113 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
73114 ** if successful, or an SQLite error code if an error occurs.
73115 */
73116 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
73117   int nRem = nData;
73118   while( nRem>0 && p->eFWErr==0 ){
73119     int nCopy = nRem;
73120     if( nCopy>(p->nBuffer - p->iBufEnd) ){
73121       nCopy = p->nBuffer - p->iBufEnd;
73122     }
73123
73124     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
73125     p->iBufEnd += nCopy;
73126     if( p->iBufEnd==p->nBuffer ){
73127       p->eFWErr = sqlite3OsWrite(p->pFile,
73128           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
73129           p->iWriteOff + p->iBufStart
73130       );
73131       p->iBufStart = p->iBufEnd = 0;
73132       p->iWriteOff += p->nBuffer;
73133     }
73134     assert( p->iBufEnd<p->nBuffer );
73135
73136     nRem -= nCopy;
73137   }
73138 }
73139
73140 /*
73141 ** Flush any buffered data to disk and clean up the file-writer object.
73142 ** The results of using the file-writer after this call are undefined.
73143 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
73144 ** required. Otherwise, return an SQLite error code.
73145 **
73146 ** Before returning, set *piEof to the offset immediately following the
73147 ** last byte written to the file.
73148 */
73149 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
73150   int rc;
73151   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
73152     p->eFWErr = sqlite3OsWrite(p->pFile,
73153         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
73154         p->iWriteOff + p->iBufStart
73155     );
73156   }
73157   *piEof = (p->iWriteOff + p->iBufEnd);
73158   sqlite3DbFree(db, p->aBuffer);
73159   rc = p->eFWErr;
73160   memset(p, 0, sizeof(FileWriter));
73161   return rc;
73162 }
73163
73164 /*
73165 ** Write value iVal encoded as a varint to the file-write object. Return
73166 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
73167 */
73168 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
73169   int nByte;
73170   u8 aByte[10];
73171   nByte = sqlite3PutVarint(aByte, iVal);
73172   fileWriterWrite(p, aByte, nByte);
73173 }
73174
73175 /*
73176 ** Write the current contents of the in-memory linked-list to a PMA. Return
73177 ** SQLITE_OK if successful, or an SQLite error code otherwise.
73178 **
73179 ** The format of a PMA is:
73180 **
73181 **     * A varint. This varint contains the total number of bytes of content
73182 **       in the PMA (not including the varint itself).
73183 **
73184 **     * One or more records packed end-to-end in order of ascending keys.
73185 **       Each record consists of a varint followed by a blob of data (the
73186 **       key). The varint is the number of bytes in the blob of data.
73187 */
73188 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
73189   int rc = SQLITE_OK;             /* Return code */
73190   VdbeSorter *pSorter = pCsr->pSorter;
73191   FileWriter writer;
73192
73193   memset(&writer, 0, sizeof(FileWriter));
73194
73195   if( pSorter->nInMemory==0 ){
73196     assert( pSorter->pRecord==0 );
73197     return rc;
73198   }
73199
73200   rc = vdbeSorterSort(pCsr);
73201
73202   /* If the first temporary PMA file has not been opened, open it now. */
73203   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
73204     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
73205     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
73206     assert( pSorter->iWriteOff==0 );
73207     assert( pSorter->nPMA==0 );
73208   }
73209
73210   if( rc==SQLITE_OK ){
73211     SorterRecord *p;
73212     SorterRecord *pNext = 0;
73213
73214     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
73215     pSorter->nPMA++;
73216     fileWriterWriteVarint(&writer, pSorter->nInMemory);
73217     for(p=pSorter->pRecord; p; p=pNext){
73218       pNext = p->pNext;
73219       fileWriterWriteVarint(&writer, p->nVal);
73220       fileWriterWrite(&writer, p->pVal, p->nVal);
73221       sqlite3DbFree(db, p);
73222     }
73223     pSorter->pRecord = p;
73224     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
73225   }
73226
73227   return rc;
73228 }
73229
73230 /*
73231 ** Add a record to the sorter.
73232 */
73233 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
73234   sqlite3 *db,                    /* Database handle */
73235   const VdbeCursor *pCsr,               /* Sorter cursor */
73236   Mem *pVal                       /* Memory cell containing record */
73237 ){
73238   VdbeSorter *pSorter = pCsr->pSorter;
73239   int rc = SQLITE_OK;             /* Return Code */
73240   SorterRecord *pNew;             /* New list element */
73241
73242   assert( pSorter );
73243   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
73244
73245   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
73246   if( pNew==0 ){
73247     rc = SQLITE_NOMEM;
73248   }else{
73249     pNew->pVal = (void *)&pNew[1];
73250     memcpy(pNew->pVal, pVal->z, pVal->n);
73251     pNew->nVal = pVal->n;
73252     pNew->pNext = pSorter->pRecord;
73253     pSorter->pRecord = pNew;
73254   }
73255
73256   /* See if the contents of the sorter should now be written out. They
73257   ** are written out when either of the following are true:
73258   **
73259   **   * The total memory allocated for the in-memory list is greater
73260   **     than (page-size * cache-size), or
73261   **
73262   **   * The total memory allocated for the in-memory list is greater
73263   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
73264   */
73265   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
73266         (pSorter->nInMemory>pSorter->mxPmaSize)
73267      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
73268   )){
73269 #ifdef SQLITE_DEBUG
73270     i64 nExpect = pSorter->iWriteOff
73271                 + sqlite3VarintLen(pSorter->nInMemory)
73272                 + pSorter->nInMemory;
73273 #endif
73274     rc = vdbeSorterListToPMA(db, pCsr);
73275     pSorter->nInMemory = 0;
73276     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
73277   }
73278
73279   return rc;
73280 }
73281
73282 /*
73283 ** Helper function for sqlite3VdbeSorterRewind().
73284 */
73285 static int vdbeSorterInitMerge(
73286   sqlite3 *db,                    /* Database handle */
73287   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
73288   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
73289 ){
73290   VdbeSorter *pSorter = pCsr->pSorter;
73291   int rc = SQLITE_OK;             /* Return code */
73292   int i;                          /* Used to iterator through aIter[] */
73293   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
73294
73295   /* Initialize the iterators. */
73296   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
73297     VdbeSorterIter *pIter = &pSorter->aIter[i];
73298     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
73299     pSorter->iReadOff = pIter->iEof;
73300     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
73301     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
73302   }
73303
73304   /* Initialize the aTree[] array. */
73305   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
73306     rc = vdbeSorterDoCompare(pCsr, i);
73307   }
73308
73309   *pnByte = nByte;
73310   return rc;
73311 }
73312
73313 /*
73314 ** Once the sorter has been populated, this function is called to prepare
73315 ** for iterating through its contents in sorted order.
73316 */
73317 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73318   VdbeSorter *pSorter = pCsr->pSorter;
73319   int rc;                         /* Return code */
73320   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
73321   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
73322   int nIter;                      /* Number of iterators used */
73323   int nByte;                      /* Bytes of space required for aIter/aTree */
73324   int N = 2;                      /* Power of 2 >= nIter */
73325
73326   assert( pSorter );
73327
73328   /* If no data has been written to disk, then do not do so now. Instead,
73329   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
73330   ** from the in-memory list.  */
73331   if( pSorter->nPMA==0 ){
73332     *pbEof = !pSorter->pRecord;
73333     assert( pSorter->aTree==0 );
73334     return vdbeSorterSort(pCsr);
73335   }
73336
73337   /* Write the current in-memory list to a PMA. */
73338   rc = vdbeSorterListToPMA(db, pCsr);
73339   if( rc!=SQLITE_OK ) return rc;
73340
73341   /* Allocate space for aIter[] and aTree[]. */
73342   nIter = pSorter->nPMA;
73343   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
73344   assert( nIter>0 );
73345   while( N<nIter ) N += N;
73346   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
73347   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
73348   if( !pSorter->aIter ) return SQLITE_NOMEM;
73349   pSorter->aTree = (int *)&pSorter->aIter[N];
73350   pSorter->nTree = N;
73351
73352   do {
73353     int iNew;                     /* Index of new, merged, PMA */
73354
73355     for(iNew=0;
73356         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
73357         iNew++
73358     ){
73359       int rc2;                    /* Return code from fileWriterFinish() */
73360       FileWriter writer;          /* Object used to write to disk */
73361       i64 nWrite;                 /* Number of bytes in new PMA */
73362
73363       memset(&writer, 0, sizeof(FileWriter));
73364
73365       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
73366       ** initialize an iterator for each of them and break out of the loop.
73367       ** These iterators will be incrementally merged as the VDBE layer calls
73368       ** sqlite3VdbeSorterNext().
73369       **
73370       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
73371       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
73372       ** are merged into a single PMA that is written to file pTemp2.
73373       */
73374       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
73375       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
73376       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73377         break;
73378       }
73379
73380       /* Open the second temp file, if it is not already open. */
73381       if( pTemp2==0 ){
73382         assert( iWrite2==0 );
73383         rc = vdbeSorterOpenTempFile(db, &pTemp2);
73384       }
73385
73386       if( rc==SQLITE_OK ){
73387         int bEof = 0;
73388         fileWriterInit(db, pTemp2, &writer, iWrite2);
73389         fileWriterWriteVarint(&writer, nWrite);
73390         while( rc==SQLITE_OK && bEof==0 ){
73391           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73392           assert( pIter->pFile );
73393
73394           fileWriterWriteVarint(&writer, pIter->nKey);
73395           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
73396           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
73397         }
73398         rc2 = fileWriterFinish(db, &writer, &iWrite2);
73399         if( rc==SQLITE_OK ) rc = rc2;
73400       }
73401     }
73402
73403     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73404       break;
73405     }else{
73406       sqlite3_file *pTmp = pSorter->pTemp1;
73407       pSorter->nPMA = iNew;
73408       pSorter->pTemp1 = pTemp2;
73409       pTemp2 = pTmp;
73410       pSorter->iWriteOff = iWrite2;
73411       pSorter->iReadOff = 0;
73412       iWrite2 = 0;
73413     }
73414   }while( rc==SQLITE_OK );
73415
73416   if( pTemp2 ){
73417     sqlite3OsCloseFree(pTemp2);
73418   }
73419   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73420   return rc;
73421 }
73422
73423 /*
73424 ** Advance to the next element in the sorter.
73425 */
73426 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73427   VdbeSorter *pSorter = pCsr->pSorter;
73428   int rc;                         /* Return code */
73429
73430   if( pSorter->aTree ){
73431     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
73432     int i;                        /* Index of aTree[] to recalculate */
73433
73434     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
73435     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
73436       rc = vdbeSorterDoCompare(pCsr, i);
73437     }
73438
73439     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73440   }else{
73441     SorterRecord *pFree = pSorter->pRecord;
73442     pSorter->pRecord = pFree->pNext;
73443     pFree->pNext = 0;
73444     vdbeSorterRecordFree(db, pFree);
73445     *pbEof = !pSorter->pRecord;
73446     rc = SQLITE_OK;
73447   }
73448   return rc;
73449 }
73450
73451 /*
73452 ** Return a pointer to a buffer owned by the sorter that contains the
73453 ** current key.
73454 */
73455 static void *vdbeSorterRowkey(
73456   const VdbeSorter *pSorter,      /* Sorter object */
73457   int *pnKey                      /* OUT: Size of current key in bytes */
73458 ){
73459   void *pKey;
73460   if( pSorter->aTree ){
73461     VdbeSorterIter *pIter;
73462     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73463     *pnKey = pIter->nKey;
73464     pKey = pIter->aKey;
73465   }else{
73466     *pnKey = pSorter->pRecord->nVal;
73467     pKey = pSorter->pRecord->pVal;
73468   }
73469   return pKey;
73470 }
73471
73472 /*
73473 ** Copy the current sorter key into the memory cell pOut.
73474 */
73475 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
73476   VdbeSorter *pSorter = pCsr->pSorter;
73477   void *pKey; int nKey;           /* Sorter key to copy into pOut */
73478
73479   pKey = vdbeSorterRowkey(pSorter, &nKey);
73480   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
73481     return SQLITE_NOMEM;
73482   }
73483   pOut->n = nKey;
73484   MemSetTypeFlag(pOut, MEM_Blob);
73485   memcpy(pOut->z, pKey, nKey);
73486
73487   return SQLITE_OK;
73488 }
73489
73490 /*
73491 ** Compare the key in memory cell pVal with the key that the sorter cursor
73492 ** passed as the first argument currently points to. For the purposes of
73493 ** the comparison, ignore the rowid field at the end of each record.
73494 **
73495 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
73496 ** Otherwise, set *pRes to a negative, zero or positive value if the
73497 ** key in pVal is smaller than, equal to or larger than the current sorter
73498 ** key.
73499 */
73500 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
73501   const VdbeCursor *pCsr,         /* Sorter cursor */
73502   Mem *pVal,                      /* Value to compare to current sorter key */
73503   int *pRes                       /* OUT: Result of comparison */
73504 ){
73505   VdbeSorter *pSorter = pCsr->pSorter;
73506   void *pKey; int nKey;           /* Sorter key to compare pVal with */
73507
73508   pKey = vdbeSorterRowkey(pSorter, &nKey);
73509   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
73510   return SQLITE_OK;
73511 }
73512
73513 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
73514
73515 /************** End of vdbesort.c ********************************************/
73516 /************** Begin file journal.c *****************************************/
73517 /*
73518 ** 2007 August 22
73519 **
73520 ** The author disclaims copyright to this source code.  In place of
73521 ** a legal notice, here is a blessing:
73522 **
73523 **    May you do good and not evil.
73524 **    May you find forgiveness for yourself and forgive others.
73525 **    May you share freely, never taking more than you give.
73526 **
73527 *************************************************************************
73528 **
73529 ** This file implements a special kind of sqlite3_file object used
73530 ** by SQLite to create journal files if the atomic-write optimization
73531 ** is enabled.
73532 **
73533 ** The distinctive characteristic of this sqlite3_file is that the
73534 ** actual on disk file is created lazily. When the file is created,
73535 ** the caller specifies a buffer size for an in-memory buffer to
73536 ** be used to service read() and write() requests. The actual file
73537 ** on disk is not created or populated until either:
73538 **
73539 **   1) The in-memory representation grows too large for the allocated
73540 **      buffer, or
73541 **   2) The sqlite3JournalCreate() function is called.
73542 */
73543 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
73544
73545
73546 /*
73547 ** A JournalFile object is a subclass of sqlite3_file used by
73548 ** as an open file handle for journal files.
73549 */
73550 struct JournalFile {
73551   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
73552   int nBuf;                       /* Size of zBuf[] in bytes */
73553   char *zBuf;                     /* Space to buffer journal writes */
73554   int iSize;                      /* Amount of zBuf[] currently used */
73555   int flags;                      /* xOpen flags */
73556   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
73557   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
73558   const char *zJournal;           /* Name of the journal file */
73559 };
73560 typedef struct JournalFile JournalFile;
73561
73562 /*
73563 ** If it does not already exists, create and populate the on-disk file
73564 ** for JournalFile p.
73565 */
73566 static int createFile(JournalFile *p){
73567   int rc = SQLITE_OK;
73568   if( !p->pReal ){
73569     sqlite3_file *pReal = (sqlite3_file *)&p[1];
73570     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
73571     if( rc==SQLITE_OK ){
73572       p->pReal = pReal;
73573       if( p->iSize>0 ){
73574         assert(p->iSize<=p->nBuf);
73575         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
73576       }
73577     }
73578   }
73579   return rc;
73580 }
73581
73582 /*
73583 ** Close the file.
73584 */
73585 static int jrnlClose(sqlite3_file *pJfd){
73586   JournalFile *p = (JournalFile *)pJfd;
73587   if( p->pReal ){
73588     sqlite3OsClose(p->pReal);
73589   }
73590   sqlite3_free(p->zBuf);
73591   return SQLITE_OK;
73592 }
73593
73594 /*
73595 ** Read data from the file.
73596 */
73597 static int jrnlRead(
73598   sqlite3_file *pJfd,    /* The journal file from which to read */
73599   void *zBuf,            /* Put the results here */
73600   int iAmt,              /* Number of bytes to read */
73601   sqlite_int64 iOfst     /* Begin reading at this offset */
73602 ){
73603   int rc = SQLITE_OK;
73604   JournalFile *p = (JournalFile *)pJfd;
73605   if( p->pReal ){
73606     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
73607   }else if( (iAmt+iOfst)>p->iSize ){
73608     rc = SQLITE_IOERR_SHORT_READ;
73609   }else{
73610     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
73611   }
73612   return rc;
73613 }
73614
73615 /*
73616 ** Write data to the file.
73617 */
73618 static int jrnlWrite(
73619   sqlite3_file *pJfd,    /* The journal file into which to write */
73620   const void *zBuf,      /* Take data to be written from here */
73621   int iAmt,              /* Number of bytes to write */
73622   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73623 ){
73624   int rc = SQLITE_OK;
73625   JournalFile *p = (JournalFile *)pJfd;
73626   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
73627     rc = createFile(p);
73628   }
73629   if( rc==SQLITE_OK ){
73630     if( p->pReal ){
73631       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
73632     }else{
73633       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
73634       if( p->iSize<(iOfst+iAmt) ){
73635         p->iSize = (iOfst+iAmt);
73636       }
73637     }
73638   }
73639   return rc;
73640 }
73641
73642 /*
73643 ** Truncate the file.
73644 */
73645 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73646   int rc = SQLITE_OK;
73647   JournalFile *p = (JournalFile *)pJfd;
73648   if( p->pReal ){
73649     rc = sqlite3OsTruncate(p->pReal, size);
73650   }else if( size<p->iSize ){
73651     p->iSize = size;
73652   }
73653   return rc;
73654 }
73655
73656 /*
73657 ** Sync the file.
73658 */
73659 static int jrnlSync(sqlite3_file *pJfd, int flags){
73660   int rc;
73661   JournalFile *p = (JournalFile *)pJfd;
73662   if( p->pReal ){
73663     rc = sqlite3OsSync(p->pReal, flags);
73664   }else{
73665     rc = SQLITE_OK;
73666   }
73667   return rc;
73668 }
73669
73670 /*
73671 ** Query the size of the file in bytes.
73672 */
73673 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73674   int rc = SQLITE_OK;
73675   JournalFile *p = (JournalFile *)pJfd;
73676   if( p->pReal ){
73677     rc = sqlite3OsFileSize(p->pReal, pSize);
73678   }else{
73679     *pSize = (sqlite_int64) p->iSize;
73680   }
73681   return rc;
73682 }
73683
73684 /*
73685 ** Table of methods for JournalFile sqlite3_file object.
73686 */
73687 static struct sqlite3_io_methods JournalFileMethods = {
73688   1,             /* iVersion */
73689   jrnlClose,     /* xClose */
73690   jrnlRead,      /* xRead */
73691   jrnlWrite,     /* xWrite */
73692   jrnlTruncate,  /* xTruncate */
73693   jrnlSync,      /* xSync */
73694   jrnlFileSize,  /* xFileSize */
73695   0,             /* xLock */
73696   0,             /* xUnlock */
73697   0,             /* xCheckReservedLock */
73698   0,             /* xFileControl */
73699   0,             /* xSectorSize */
73700   0,             /* xDeviceCharacteristics */
73701   0,             /* xShmMap */
73702   0,             /* xShmLock */
73703   0,             /* xShmBarrier */
73704   0              /* xShmUnmap */
73705 };
73706
73707 /*
73708 ** Open a journal file.
73709 */
73710 SQLITE_PRIVATE int sqlite3JournalOpen(
73711   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
73712   const char *zName,         /* Name of the journal file */
73713   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
73714   int flags,                 /* Opening flags */
73715   int nBuf                   /* Bytes buffered before opening the file */
73716 ){
73717   JournalFile *p = (JournalFile *)pJfd;
73718   memset(p, 0, sqlite3JournalSize(pVfs));
73719   if( nBuf>0 ){
73720     p->zBuf = sqlite3MallocZero(nBuf);
73721     if( !p->zBuf ){
73722       return SQLITE_NOMEM;
73723     }
73724   }else{
73725     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
73726   }
73727   p->pMethod = &JournalFileMethods;
73728   p->nBuf = nBuf;
73729   p->flags = flags;
73730   p->zJournal = zName;
73731   p->pVfs = pVfs;
73732   return SQLITE_OK;
73733 }
73734
73735 /*
73736 ** If the argument p points to a JournalFile structure, and the underlying
73737 ** file has not yet been created, create it now.
73738 */
73739 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
73740   if( p->pMethods!=&JournalFileMethods ){
73741     return SQLITE_OK;
73742   }
73743   return createFile((JournalFile *)p);
73744 }
73745
73746 /*
73747 ** The file-handle passed as the only argument is guaranteed to be an open
73748 ** file. It may or may not be of class JournalFile. If the file is a
73749 ** JournalFile, and the underlying file on disk has not yet been opened,
73750 ** return 0. Otherwise, return 1.
73751 */
73752 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
73753   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
73754 }
73755
73756 /*
73757 ** Return the number of bytes required to store a JournalFile that uses vfs
73758 ** pVfs to create the underlying on-disk files.
73759 */
73760 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
73761   return (pVfs->szOsFile+sizeof(JournalFile));
73762 }
73763 #endif
73764
73765 /************** End of journal.c *********************************************/
73766 /************** Begin file memjournal.c **************************************/
73767 /*
73768 ** 2008 October 7
73769 **
73770 ** The author disclaims copyright to this source code.  In place of
73771 ** a legal notice, here is a blessing:
73772 **
73773 **    May you do good and not evil.
73774 **    May you find forgiveness for yourself and forgive others.
73775 **    May you share freely, never taking more than you give.
73776 **
73777 *************************************************************************
73778 **
73779 ** This file contains code use to implement an in-memory rollback journal.
73780 ** The in-memory rollback journal is used to journal transactions for
73781 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
73782 */
73783
73784 /* Forward references to internal structures */
73785 typedef struct MemJournal MemJournal;
73786 typedef struct FilePoint FilePoint;
73787 typedef struct FileChunk FileChunk;
73788
73789 /* Space to hold the rollback journal is allocated in increments of
73790 ** this many bytes.
73791 **
73792 ** The size chosen is a little less than a power of two.  That way,
73793 ** the FileChunk object will have a size that almost exactly fills
73794 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
73795 ** memory allocators.
73796 */
73797 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73798
73799 /* Macro to find the minimum of two numeric values.
73800 */
73801 #ifndef MIN
73802 # define MIN(x,y) ((x)<(y)?(x):(y))
73803 #endif
73804
73805 /*
73806 ** The rollback journal is composed of a linked list of these structures.
73807 */
73808 struct FileChunk {
73809   FileChunk *pNext;               /* Next chunk in the journal */
73810   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
73811 };
73812
73813 /*
73814 ** An instance of this object serves as a cursor into the rollback journal.
73815 ** The cursor can be either for reading or writing.
73816 */
73817 struct FilePoint {
73818   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
73819   FileChunk *pChunk;              /* Specific chunk into which cursor points */
73820 };
73821
73822 /*
73823 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
73824 ** is an instance of this class.
73825 */
73826 struct MemJournal {
73827   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
73828   FileChunk *pFirst;              /* Head of in-memory chunk-list */
73829   FilePoint endpoint;             /* Pointer to the end of the file */
73830   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
73831 };
73832
73833 /*
73834 ** Read data from the in-memory journal file.  This is the implementation
73835 ** of the sqlite3_vfs.xRead method.
73836 */
73837 static int memjrnlRead(
73838   sqlite3_file *pJfd,    /* The journal file from which to read */
73839   void *zBuf,            /* Put the results here */
73840   int iAmt,              /* Number of bytes to read */
73841   sqlite_int64 iOfst     /* Begin reading at this offset */
73842 ){
73843   MemJournal *p = (MemJournal *)pJfd;
73844   u8 *zOut = zBuf;
73845   int nRead = iAmt;
73846   int iChunkOffset;
73847   FileChunk *pChunk;
73848
73849   /* SQLite never tries to read past the end of a rollback journal file */
73850   assert( iOfst+iAmt<=p->endpoint.iOffset );
73851
73852   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
73853     sqlite3_int64 iOff = 0;
73854     for(pChunk=p->pFirst;
73855         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
73856         pChunk=pChunk->pNext
73857     ){
73858       iOff += JOURNAL_CHUNKSIZE;
73859     }
73860   }else{
73861     pChunk = p->readpoint.pChunk;
73862   }
73863
73864   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
73865   do {
73866     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
73867     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
73868     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
73869     zOut += nCopy;
73870     nRead -= iSpace;
73871     iChunkOffset = 0;
73872   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
73873   p->readpoint.iOffset = iOfst+iAmt;
73874   p->readpoint.pChunk = pChunk;
73875
73876   return SQLITE_OK;
73877 }
73878
73879 /*
73880 ** Write data to the file.
73881 */
73882 static int memjrnlWrite(
73883   sqlite3_file *pJfd,    /* The journal file into which to write */
73884   const void *zBuf,      /* Take data to be written from here */
73885   int iAmt,              /* Number of bytes to write */
73886   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73887 ){
73888   MemJournal *p = (MemJournal *)pJfd;
73889   int nWrite = iAmt;
73890   u8 *zWrite = (u8 *)zBuf;
73891
73892   /* An in-memory journal file should only ever be appended to. Random
73893   ** access writes are not required by sqlite.
73894   */
73895   assert( iOfst==p->endpoint.iOffset );
73896   UNUSED_PARAMETER(iOfst);
73897
73898   while( nWrite>0 ){
73899     FileChunk *pChunk = p->endpoint.pChunk;
73900     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
73901     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
73902
73903     if( iChunkOffset==0 ){
73904       /* New chunk is required to extend the file. */
73905       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
73906       if( !pNew ){
73907         return SQLITE_IOERR_NOMEM;
73908       }
73909       pNew->pNext = 0;
73910       if( pChunk ){
73911         assert( p->pFirst );
73912         pChunk->pNext = pNew;
73913       }else{
73914         assert( !p->pFirst );
73915         p->pFirst = pNew;
73916       }
73917       p->endpoint.pChunk = pNew;
73918     }
73919
73920     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
73921     zWrite += iSpace;
73922     nWrite -= iSpace;
73923     p->endpoint.iOffset += iSpace;
73924   }
73925
73926   return SQLITE_OK;
73927 }
73928
73929 /*
73930 ** Truncate the file.
73931 */
73932 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73933   MemJournal *p = (MemJournal *)pJfd;
73934   FileChunk *pChunk;
73935   assert(size==0);
73936   UNUSED_PARAMETER(size);
73937   pChunk = p->pFirst;
73938   while( pChunk ){
73939     FileChunk *pTmp = pChunk;
73940     pChunk = pChunk->pNext;
73941     sqlite3_free(pTmp);
73942   }
73943   sqlite3MemJournalOpen(pJfd);
73944   return SQLITE_OK;
73945 }
73946
73947 /*
73948 ** Close the file.
73949 */
73950 static int memjrnlClose(sqlite3_file *pJfd){
73951   memjrnlTruncate(pJfd, 0);
73952   return SQLITE_OK;
73953 }
73954
73955
73956 /*
73957 ** Sync the file.
73958 **
73959 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
73960 ** is never called in a working implementation.  This implementation
73961 ** exists purely as a contingency, in case some malfunction in some other
73962 ** part of SQLite causes Sync to be called by mistake.
73963 */
73964 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
73965   UNUSED_PARAMETER2(NotUsed, NotUsed2);
73966   return SQLITE_OK;
73967 }
73968
73969 /*
73970 ** Query the size of the file in bytes.
73971 */
73972 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73973   MemJournal *p = (MemJournal *)pJfd;
73974   *pSize = (sqlite_int64) p->endpoint.iOffset;
73975   return SQLITE_OK;
73976 }
73977
73978 /*
73979 ** Table of methods for MemJournal sqlite3_file object.
73980 */
73981 static const struct sqlite3_io_methods MemJournalMethods = {
73982   1,                /* iVersion */
73983   memjrnlClose,     /* xClose */
73984   memjrnlRead,      /* xRead */
73985   memjrnlWrite,     /* xWrite */
73986   memjrnlTruncate,  /* xTruncate */
73987   memjrnlSync,      /* xSync */
73988   memjrnlFileSize,  /* xFileSize */
73989   0,                /* xLock */
73990   0,                /* xUnlock */
73991   0,                /* xCheckReservedLock */
73992   0,                /* xFileControl */
73993   0,                /* xSectorSize */
73994   0,                /* xDeviceCharacteristics */
73995   0,                /* xShmMap */
73996   0,                /* xShmLock */
73997   0,                /* xShmBarrier */
73998   0                 /* xShmUnlock */
73999 };
74000
74001 /*
74002 ** Open a journal file.
74003 */
74004 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
74005   MemJournal *p = (MemJournal *)pJfd;
74006   assert( EIGHT_BYTE_ALIGNMENT(p) );
74007   memset(p, 0, sqlite3MemJournalSize());
74008   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
74009 }
74010
74011 /*
74012 ** Return true if the file-handle passed as an argument is
74013 ** an in-memory journal
74014 */
74015 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
74016   return pJfd->pMethods==&MemJournalMethods;
74017 }
74018
74019 /*
74020 ** Return the number of bytes required to store a MemJournal file descriptor.
74021 */
74022 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
74023   return sizeof(MemJournal);
74024 }
74025
74026 /************** End of memjournal.c ******************************************/
74027 /************** Begin file walker.c ******************************************/
74028 /*
74029 ** 2008 August 16
74030 **
74031 ** The author disclaims copyright to this source code.  In place of
74032 ** a legal notice, here is a blessing:
74033 **
74034 **    May you do good and not evil.
74035 **    May you find forgiveness for yourself and forgive others.
74036 **    May you share freely, never taking more than you give.
74037 **
74038 *************************************************************************
74039 ** This file contains routines used for walking the parser tree for
74040 ** an SQL statement.
74041 */
74042 /* #include <stdlib.h> */
74043 /* #include <string.h> */
74044
74045
74046 /*
74047 ** Walk an expression tree.  Invoke the callback once for each node
74048 ** of the expression, while decending.  (In other words, the callback
74049 ** is invoked before visiting children.)
74050 **
74051 ** The return value from the callback should be one of the WRC_*
74052 ** constants to specify how to proceed with the walk.
74053 **
74054 **    WRC_Continue      Continue descending down the tree.
74055 **
74056 **    WRC_Prune         Do not descend into child nodes.  But allow
74057 **                      the walk to continue with sibling nodes.
74058 **
74059 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
74060 **                      return the top-level walk call.
74061 **
74062 ** The return value from this routine is WRC_Abort to abandon the tree walk
74063 ** and WRC_Continue to continue.
74064 */
74065 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
74066   int rc;
74067   if( pExpr==0 ) return WRC_Continue;
74068   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
74069   testcase( ExprHasProperty(pExpr, EP_Reduced) );
74070   rc = pWalker->xExprCallback(pWalker, pExpr);
74071   if( rc==WRC_Continue
74072               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
74073     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
74074     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
74075     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74076       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
74077     }else{
74078       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
74079     }
74080   }
74081   return rc & WRC_Abort;
74082 }
74083
74084 /*
74085 ** Call sqlite3WalkExpr() for every expression in list p or until
74086 ** an abort request is seen.
74087 */
74088 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
74089   int i;
74090   struct ExprList_item *pItem;
74091   if( p ){
74092     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
74093       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
74094     }
74095   }
74096   return WRC_Continue;
74097 }
74098
74099 /*
74100 ** Walk all expressions associated with SELECT statement p.  Do
74101 ** not invoke the SELECT callback on p, but do (of course) invoke
74102 ** any expr callbacks and SELECT callbacks that come from subqueries.
74103 ** Return WRC_Abort or WRC_Continue.
74104 */
74105 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
74106   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
74107   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
74108   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
74109   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
74110   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
74111   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
74112   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
74113   return WRC_Continue;
74114 }
74115
74116 /*
74117 ** Walk the parse trees associated with all subqueries in the
74118 ** FROM clause of SELECT statement p.  Do not invoke the select
74119 ** callback on p, but do invoke it on each FROM clause subquery
74120 ** and on any subqueries further down in the tree.  Return
74121 ** WRC_Abort or WRC_Continue;
74122 */
74123 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
74124   SrcList *pSrc;
74125   int i;
74126   struct SrcList_item *pItem;
74127
74128   pSrc = p->pSrc;
74129   if( ALWAYS(pSrc) ){
74130     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
74131       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
74132         return WRC_Abort;
74133       }
74134     }
74135   }
74136   return WRC_Continue;
74137 }
74138
74139 /*
74140 ** Call sqlite3WalkExpr() for every expression in Select statement p.
74141 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
74142 ** on the compound select chain, p->pPrior.
74143 **
74144 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
74145 ** there is an abort request.
74146 **
74147 ** If the Walker does not have an xSelectCallback() then this routine
74148 ** is a no-op returning WRC_Continue.
74149 */
74150 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
74151   int rc;
74152   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
74153   rc = WRC_Continue;
74154   pWalker->walkerDepth++;
74155   while( p ){
74156     rc = pWalker->xSelectCallback(pWalker, p);
74157     if( rc ) break;
74158     if( sqlite3WalkSelectExpr(pWalker, p)
74159      || sqlite3WalkSelectFrom(pWalker, p)
74160     ){
74161       pWalker->walkerDepth--;
74162       return WRC_Abort;
74163     }
74164     p = p->pPrior;
74165   }
74166   pWalker->walkerDepth--;
74167   return rc & WRC_Abort;
74168 }
74169
74170 /************** End of walker.c **********************************************/
74171 /************** Begin file resolve.c *****************************************/
74172 /*
74173 ** 2008 August 18
74174 **
74175 ** The author disclaims copyright to this source code.  In place of
74176 ** a legal notice, here is a blessing:
74177 **
74178 **    May you do good and not evil.
74179 **    May you find forgiveness for yourself and forgive others.
74180 **    May you share freely, never taking more than you give.
74181 **
74182 *************************************************************************
74183 **
74184 ** This file contains routines used for walking the parser tree and
74185 ** resolve all identifiers by associating them with a particular
74186 ** table and column.
74187 */
74188 /* #include <stdlib.h> */
74189 /* #include <string.h> */
74190
74191 /*
74192 ** Walk the expression tree pExpr and increase the aggregate function
74193 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
74194 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
74195 ** outer query into an inner subquery.
74196 **
74197 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
74198 ** is a helper function - a callback for the tree walker.
74199 */
74200 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
74201   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
74202   return WRC_Continue;
74203 }
74204 static void incrAggFunctionDepth(Expr *pExpr, int N){
74205   if( N>0 ){
74206     Walker w;
74207     memset(&w, 0, sizeof(w));
74208     w.xExprCallback = incrAggDepth;
74209     w.u.i = N;
74210     sqlite3WalkExpr(&w, pExpr);
74211   }
74212 }
74213
74214 /*
74215 ** Turn the pExpr expression into an alias for the iCol-th column of the
74216 ** result set in pEList.
74217 **
74218 ** If the result set column is a simple column reference, then this routine
74219 ** makes an exact copy.  But for any other kind of expression, this
74220 ** routine make a copy of the result set column as the argument to the
74221 ** TK_AS operator.  The TK_AS operator causes the expression to be
74222 ** evaluated just once and then reused for each alias.
74223 **
74224 ** The reason for suppressing the TK_AS term when the expression is a simple
74225 ** column reference is so that the column reference will be recognized as
74226 ** usable by indices within the WHERE clause processing logic.
74227 **
74228 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
74229 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
74230 **
74231 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
74232 **
74233 ** Is equivalent to:
74234 **
74235 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
74236 **
74237 ** The result of random()%5 in the GROUP BY clause is probably different
74238 ** from the result in the result-set.  We might fix this someday.  Or
74239 ** then again, we might not...
74240 **
74241 ** If the reference is followed by a COLLATE operator, then make sure
74242 ** the COLLATE operator is preserved.  For example:
74243 **
74244 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
74245 **
74246 ** Should be transformed into:
74247 **
74248 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
74249 **
74250 ** The nSubquery parameter specifies how many levels of subquery the
74251 ** alias is removed from the original expression.  The usually value is
74252 ** zero but it might be more if the alias is contained within a subquery
74253 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
74254 ** structures must be increased by the nSubquery amount.
74255 */
74256 static void resolveAlias(
74257   Parse *pParse,         /* Parsing context */
74258   ExprList *pEList,      /* A result set */
74259   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
74260   Expr *pExpr,           /* Transform this into an alias to the result set */
74261   const char *zType,     /* "GROUP" or "ORDER" or "" */
74262   int nSubquery          /* Number of subqueries that the label is moving */
74263 ){
74264   Expr *pOrig;           /* The iCol-th column of the result set */
74265   Expr *pDup;            /* Copy of pOrig */
74266   sqlite3 *db;           /* The database connection */
74267
74268   assert( iCol>=0 && iCol<pEList->nExpr );
74269   pOrig = pEList->a[iCol].pExpr;
74270   assert( pOrig!=0 );
74271   assert( pOrig->flags & EP_Resolved );
74272   db = pParse->db;
74273   pDup = sqlite3ExprDup(db, pOrig, 0);
74274   if( pDup==0 ) return;
74275   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
74276     incrAggFunctionDepth(pDup, nSubquery);
74277     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
74278     if( pDup==0 ) return;
74279     if( pEList->a[iCol].iAlias==0 ){
74280       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
74281     }
74282     pDup->iTable = pEList->a[iCol].iAlias;
74283   }
74284   if( pExpr->op==TK_COLLATE ){
74285     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
74286   }
74287
74288   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
74289   ** prevents ExprDelete() from deleting the Expr structure itself,
74290   ** allowing it to be repopulated by the memcpy() on the following line.
74291   ** The pExpr->u.zToken might point into memory that will be freed by the
74292   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
74293   ** make a copy of the token before doing the sqlite3DbFree().
74294   */
74295   ExprSetProperty(pExpr, EP_Static);
74296   sqlite3ExprDelete(db, pExpr);
74297   memcpy(pExpr, pDup, sizeof(*pExpr));
74298   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
74299     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
74300     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
74301     pExpr->flags2 |= EP2_MallocedToken;
74302   }
74303   sqlite3DbFree(db, pDup);
74304 }
74305
74306
74307 /*
74308 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
74309 **
74310 ** Return FALSE if the USING clause is NULL or if it does not contain
74311 ** zCol.
74312 */
74313 static int nameInUsingClause(IdList *pUsing, const char *zCol){
74314   if( pUsing ){
74315     int k;
74316     for(k=0; k<pUsing->nId; k++){
74317       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
74318     }
74319   }
74320   return 0;
74321 }
74322
74323
74324 /*
74325 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
74326 ** that name in the set of source tables in pSrcList and make the pExpr
74327 ** expression node refer back to that source column.  The following changes
74328 ** are made to pExpr:
74329 **
74330 **    pExpr->iDb           Set the index in db->aDb[] of the database X
74331 **                         (even if X is implied).
74332 **    pExpr->iTable        Set to the cursor number for the table obtained
74333 **                         from pSrcList.
74334 **    pExpr->pTab          Points to the Table structure of X.Y (even if
74335 **                         X and/or Y are implied.)
74336 **    pExpr->iColumn       Set to the column number within the table.
74337 **    pExpr->op            Set to TK_COLUMN.
74338 **    pExpr->pLeft         Any expression this points to is deleted
74339 **    pExpr->pRight        Any expression this points to is deleted.
74340 **
74341 ** The zDb variable is the name of the database (the "X").  This value may be
74342 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
74343 ** can be used.  The zTable variable is the name of the table (the "Y").  This
74344 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
74345 ** means that the form of the name is Z and that columns from any table
74346 ** can be used.
74347 **
74348 ** If the name cannot be resolved unambiguously, leave an error message
74349 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
74350 */
74351 static int lookupName(
74352   Parse *pParse,       /* The parsing context */
74353   const char *zDb,     /* Name of the database containing table, or NULL */
74354   const char *zTab,    /* Name of table containing column, or NULL */
74355   const char *zCol,    /* Name of the column. */
74356   NameContext *pNC,    /* The name context used to resolve the name */
74357   Expr *pExpr          /* Make this EXPR node point to the selected column */
74358 ){
74359   int i, j;                         /* Loop counters */
74360   int cnt = 0;                      /* Number of matching column names */
74361   int cntTab = 0;                   /* Number of matching table names */
74362   int nSubquery = 0;                /* How many levels of subquery */
74363   sqlite3 *db = pParse->db;         /* The database connection */
74364   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
74365   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
74366   NameContext *pTopNC = pNC;        /* First namecontext in the list */
74367   Schema *pSchema = 0;              /* Schema of the expression */
74368   int isTrigger = 0;
74369
74370   assert( pNC );     /* the name context cannot be NULL. */
74371   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
74372   assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74373
74374   /* Initialize the node to no-match */
74375   pExpr->iTable = -1;
74376   pExpr->pTab = 0;
74377   ExprSetIrreducible(pExpr);
74378
74379   /* Start at the inner-most context and move outward until a match is found */
74380   while( pNC && cnt==0 ){
74381     ExprList *pEList;
74382     SrcList *pSrcList = pNC->pSrcList;
74383
74384     if( pSrcList ){
74385       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
74386         Table *pTab;
74387         int iDb;
74388         Column *pCol;
74389
74390         pTab = pItem->pTab;
74391         assert( pTab!=0 && pTab->zName!=0 );
74392         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74393         assert( pTab->nCol>0 );
74394         if( zTab ){
74395           if( pItem->zAlias ){
74396             char *zTabName = pItem->zAlias;
74397             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
74398           }else{
74399             char *zTabName = pTab->zName;
74400             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
74401               continue;
74402             }
74403             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
74404               continue;
74405             }
74406           }
74407         }
74408         if( 0==(cntTab++) ){
74409           pExpr->iTable = pItem->iCursor;
74410           pExpr->pTab = pTab;
74411           pSchema = pTab->pSchema;
74412           pMatch = pItem;
74413         }
74414         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
74415           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74416             /* If there has been exactly one prior match and this match
74417             ** is for the right-hand table of a NATURAL JOIN or is in a
74418             ** USING clause, then skip this match.
74419             */
74420             if( cnt==1 ){
74421               if( pItem->jointype & JT_NATURAL ) continue;
74422               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
74423             }
74424             cnt++;
74425             pExpr->iTable = pItem->iCursor;
74426             pExpr->pTab = pTab;
74427             pMatch = pItem;
74428             pSchema = pTab->pSchema;
74429             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
74430             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
74431             break;
74432           }
74433         }
74434       }
74435     }
74436
74437 #ifndef SQLITE_OMIT_TRIGGER
74438     /* If we have not already resolved the name, then maybe
74439     ** it is a new.* or old.* trigger argument reference
74440     */
74441     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
74442       int op = pParse->eTriggerOp;
74443       Table *pTab = 0;
74444       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
74445       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
74446         pExpr->iTable = 1;
74447         pTab = pParse->pTriggerTab;
74448       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
74449         pExpr->iTable = 0;
74450         pTab = pParse->pTriggerTab;
74451       }
74452
74453       if( pTab ){
74454         int iCol;
74455         pSchema = pTab->pSchema;
74456         cntTab++;
74457         for(iCol=0; iCol<pTab->nCol; iCol++){
74458           Column *pCol = &pTab->aCol[iCol];
74459           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74460             if( iCol==pTab->iPKey ){
74461               iCol = -1;
74462             }
74463             break;
74464           }
74465         }
74466         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
74467           iCol = -1;        /* IMP: R-44911-55124 */
74468         }
74469         if( iCol<pTab->nCol ){
74470           cnt++;
74471           if( iCol<0 ){
74472             pExpr->affinity = SQLITE_AFF_INTEGER;
74473           }else if( pExpr->iTable==0 ){
74474             testcase( iCol==31 );
74475             testcase( iCol==32 );
74476             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74477           }else{
74478             testcase( iCol==31 );
74479             testcase( iCol==32 );
74480             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74481           }
74482           pExpr->iColumn = (i16)iCol;
74483           pExpr->pTab = pTab;
74484           isTrigger = 1;
74485         }
74486       }
74487     }
74488 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
74489
74490     /*
74491     ** Perhaps the name is a reference to the ROWID
74492     */
74493     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
74494       cnt = 1;
74495       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
74496       pExpr->affinity = SQLITE_AFF_INTEGER;
74497     }
74498
74499     /*
74500     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
74501     ** might refer to an result-set alias.  This happens, for example, when
74502     ** we are resolving names in the WHERE clause of the following command:
74503     **
74504     **     SELECT a+b AS x FROM table WHERE x<10;
74505     **
74506     ** In cases like this, replace pExpr with a copy of the expression that
74507     ** forms the result set entry ("a+b" in the example) and return immediately.
74508     ** Note that the expression in the result set should have already been
74509     ** resolved by the time the WHERE clause is resolved.
74510     */
74511     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
74512       for(j=0; j<pEList->nExpr; j++){
74513         char *zAs = pEList->a[j].zName;
74514         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74515           Expr *pOrig;
74516           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
74517           assert( pExpr->x.pList==0 );
74518           assert( pExpr->x.pSelect==0 );
74519           pOrig = pEList->a[j].pExpr;
74520           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
74521             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
74522             return WRC_Abort;
74523           }
74524           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
74525           cnt = 1;
74526           pMatch = 0;
74527           assert( zTab==0 && zDb==0 );
74528           goto lookupname_end;
74529         }
74530       }
74531     }
74532
74533     /* Advance to the next name context.  The loop will exit when either
74534     ** we have a match (cnt>0) or when we run out of name contexts.
74535     */
74536     if( cnt==0 ){
74537       pNC = pNC->pNext;
74538       nSubquery++;
74539     }
74540   }
74541
74542   /*
74543   ** If X and Y are NULL (in other words if only the column name Z is
74544   ** supplied) and the value of Z is enclosed in double-quotes, then
74545   ** Z is a string literal if it doesn't match any column names.  In that
74546   ** case, we need to return right away and not make any changes to
74547   ** pExpr.
74548   **
74549   ** Because no reference was made to outer contexts, the pNC->nRef
74550   ** fields are not changed in any context.
74551   */
74552   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
74553     pExpr->op = TK_STRING;
74554     pExpr->pTab = 0;
74555     return WRC_Prune;
74556   }
74557
74558   /*
74559   ** cnt==0 means there was not match.  cnt>1 means there were two or
74560   ** more matches.  Either way, we have an error.
74561   */
74562   if( cnt!=1 ){
74563     const char *zErr;
74564     zErr = cnt==0 ? "no such column" : "ambiguous column name";
74565     if( zDb ){
74566       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
74567     }else if( zTab ){
74568       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
74569     }else{
74570       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
74571     }
74572     pParse->checkSchema = 1;
74573     pTopNC->nErr++;
74574   }
74575
74576   /* If a column from a table in pSrcList is referenced, then record
74577   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
74578   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
74579   ** column number is greater than the number of bits in the bitmask
74580   ** then set the high-order bit of the bitmask.
74581   */
74582   if( pExpr->iColumn>=0 && pMatch!=0 ){
74583     int n = pExpr->iColumn;
74584     testcase( n==BMS-1 );
74585     if( n>=BMS ){
74586       n = BMS-1;
74587     }
74588     assert( pMatch->iCursor==pExpr->iTable );
74589     pMatch->colUsed |= ((Bitmask)1)<<n;
74590   }
74591
74592   /* Clean up and return
74593   */
74594   sqlite3ExprDelete(db, pExpr->pLeft);
74595   pExpr->pLeft = 0;
74596   sqlite3ExprDelete(db, pExpr->pRight);
74597   pExpr->pRight = 0;
74598   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
74599 lookupname_end:
74600   if( cnt==1 ){
74601     assert( pNC!=0 );
74602     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
74603     /* Increment the nRef value on all name contexts from TopNC up to
74604     ** the point where the name matched. */
74605     for(;;){
74606       assert( pTopNC!=0 );
74607       pTopNC->nRef++;
74608       if( pTopNC==pNC ) break;
74609       pTopNC = pTopNC->pNext;
74610     }
74611     return WRC_Prune;
74612   } else {
74613     return WRC_Abort;
74614   }
74615 }
74616
74617 /*
74618 ** Allocate and return a pointer to an expression to load the column iCol
74619 ** from datasource iSrc in SrcList pSrc.
74620 */
74621 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
74622   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
74623   if( p ){
74624     struct SrcList_item *pItem = &pSrc->a[iSrc];
74625     p->pTab = pItem->pTab;
74626     p->iTable = pItem->iCursor;
74627     if( p->pTab->iPKey==iCol ){
74628       p->iColumn = -1;
74629     }else{
74630       p->iColumn = (ynVar)iCol;
74631       testcase( iCol==BMS );
74632       testcase( iCol==BMS-1 );
74633       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
74634     }
74635     ExprSetProperty(p, EP_Resolved);
74636   }
74637   return p;
74638 }
74639
74640 /*
74641 ** This routine is callback for sqlite3WalkExpr().
74642 **
74643 ** Resolve symbolic names into TK_COLUMN operators for the current
74644 ** node in the expression tree.  Return 0 to continue the search down
74645 ** the tree or 2 to abort the tree walk.
74646 **
74647 ** This routine also does error checking and name resolution for
74648 ** function names.  The operator for aggregate functions is changed
74649 ** to TK_AGG_FUNCTION.
74650 */
74651 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
74652   NameContext *pNC;
74653   Parse *pParse;
74654
74655   pNC = pWalker->u.pNC;
74656   assert( pNC!=0 );
74657   pParse = pNC->pParse;
74658   assert( pParse==pWalker->pParse );
74659
74660   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
74661   ExprSetProperty(pExpr, EP_Resolved);
74662 #ifndef NDEBUG
74663   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
74664     SrcList *pSrcList = pNC->pSrcList;
74665     int i;
74666     for(i=0; i<pNC->pSrcList->nSrc; i++){
74667       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
74668     }
74669   }
74670 #endif
74671   switch( pExpr->op ){
74672
74673 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
74674     /* The special operator TK_ROW means use the rowid for the first
74675     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
74676     ** clause processing on UPDATE and DELETE statements.
74677     */
74678     case TK_ROW: {
74679       SrcList *pSrcList = pNC->pSrcList;
74680       struct SrcList_item *pItem;
74681       assert( pSrcList && pSrcList->nSrc==1 );
74682       pItem = pSrcList->a;
74683       pExpr->op = TK_COLUMN;
74684       pExpr->pTab = pItem->pTab;
74685       pExpr->iTable = pItem->iCursor;
74686       pExpr->iColumn = -1;
74687       pExpr->affinity = SQLITE_AFF_INTEGER;
74688       break;
74689     }
74690 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
74691
74692     /* A lone identifier is the name of a column.
74693     */
74694     case TK_ID: {
74695       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
74696     }
74697
74698     /* A table name and column name:     ID.ID
74699     ** Or a database, table and column:  ID.ID.ID
74700     */
74701     case TK_DOT: {
74702       const char *zColumn;
74703       const char *zTable;
74704       const char *zDb;
74705       Expr *pRight;
74706
74707       /* if( pSrcList==0 ) break; */
74708       pRight = pExpr->pRight;
74709       if( pRight->op==TK_ID ){
74710         zDb = 0;
74711         zTable = pExpr->pLeft->u.zToken;
74712         zColumn = pRight->u.zToken;
74713       }else{
74714         assert( pRight->op==TK_DOT );
74715         zDb = pExpr->pLeft->u.zToken;
74716         zTable = pRight->pLeft->u.zToken;
74717         zColumn = pRight->pRight->u.zToken;
74718       }
74719       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
74720     }
74721
74722     /* Resolve function names
74723     */
74724     case TK_CONST_FUNC:
74725     case TK_FUNCTION: {
74726       ExprList *pList = pExpr->x.pList;    /* The argument list */
74727       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
74728       int no_such_func = 0;       /* True if no such function exists */
74729       int wrong_num_args = 0;     /* True if wrong number of arguments */
74730       int is_agg = 0;             /* True if is an aggregate function */
74731       int auth;                   /* Authorization to use the function */
74732       int nId;                    /* Number of characters in function name */
74733       const char *zId;            /* The function name. */
74734       FuncDef *pDef;              /* Information about the function */
74735       u8 enc = ENC(pParse->db);   /* The database encoding */
74736
74737       testcase( pExpr->op==TK_CONST_FUNC );
74738       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74739       zId = pExpr->u.zToken;
74740       nId = sqlite3Strlen30(zId);
74741       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
74742       if( pDef==0 ){
74743         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
74744         if( pDef==0 ){
74745           no_such_func = 1;
74746         }else{
74747           wrong_num_args = 1;
74748         }
74749       }else{
74750         is_agg = pDef->xFunc==0;
74751       }
74752 #ifndef SQLITE_OMIT_AUTHORIZATION
74753       if( pDef ){
74754         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
74755         if( auth!=SQLITE_OK ){
74756           if( auth==SQLITE_DENY ){
74757             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
74758                                     pDef->zName);
74759             pNC->nErr++;
74760           }
74761           pExpr->op = TK_NULL;
74762           return WRC_Prune;
74763         }
74764       }
74765 #endif
74766       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
74767         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
74768         pNC->nErr++;
74769         is_agg = 0;
74770       }else if( no_such_func ){
74771         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
74772         pNC->nErr++;
74773       }else if( wrong_num_args ){
74774         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
74775              nId, zId);
74776         pNC->nErr++;
74777       }
74778       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
74779       sqlite3WalkExprList(pWalker, pList);
74780       if( is_agg ){
74781         NameContext *pNC2 = pNC;
74782         pExpr->op = TK_AGG_FUNCTION;
74783         pExpr->op2 = 0;
74784         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
74785           pExpr->op2++;
74786           pNC2 = pNC2->pNext;
74787         }
74788         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
74789         pNC->ncFlags |= NC_AllowAgg;
74790       }
74791       /* FIX ME:  Compute pExpr->affinity based on the expected return
74792       ** type of the function
74793       */
74794       return WRC_Prune;
74795     }
74796 #ifndef SQLITE_OMIT_SUBQUERY
74797     case TK_SELECT:
74798     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
74799 #endif
74800     case TK_IN: {
74801       testcase( pExpr->op==TK_IN );
74802       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74803         int nRef = pNC->nRef;
74804 #ifndef SQLITE_OMIT_CHECK
74805         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74806           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
74807         }
74808 #endif
74809         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
74810         assert( pNC->nRef>=nRef );
74811         if( nRef!=pNC->nRef ){
74812           ExprSetProperty(pExpr, EP_VarSelect);
74813         }
74814       }
74815       break;
74816     }
74817 #ifndef SQLITE_OMIT_CHECK
74818     case TK_VARIABLE: {
74819       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74820         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
74821       }
74822       break;
74823     }
74824 #endif
74825   }
74826   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
74827 }
74828
74829 /*
74830 ** pEList is a list of expressions which are really the result set of the
74831 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
74832 ** This routine checks to see if pE is a simple identifier which corresponds
74833 ** to the AS-name of one of the terms of the expression list.  If it is,
74834 ** this routine return an integer between 1 and N where N is the number of
74835 ** elements in pEList, corresponding to the matching entry.  If there is
74836 ** no match, or if pE is not a simple identifier, then this routine
74837 ** return 0.
74838 **
74839 ** pEList has been resolved.  pE has not.
74840 */
74841 static int resolveAsName(
74842   Parse *pParse,     /* Parsing context for error messages */
74843   ExprList *pEList,  /* List of expressions to scan */
74844   Expr *pE           /* Expression we are trying to match */
74845 ){
74846   int i;             /* Loop counter */
74847
74848   UNUSED_PARAMETER(pParse);
74849
74850   if( pE->op==TK_ID ){
74851     char *zCol = pE->u.zToken;
74852     for(i=0; i<pEList->nExpr; i++){
74853       char *zAs = pEList->a[i].zName;
74854       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74855         return i+1;
74856       }
74857     }
74858   }
74859   return 0;
74860 }
74861
74862 /*
74863 ** pE is a pointer to an expression which is a single term in the
74864 ** ORDER BY of a compound SELECT.  The expression has not been
74865 ** name resolved.
74866 **
74867 ** At the point this routine is called, we already know that the
74868 ** ORDER BY term is not an integer index into the result set.  That
74869 ** case is handled by the calling routine.
74870 **
74871 ** Attempt to match pE against result set columns in the left-most
74872 ** SELECT statement.  Return the index i of the matching column,
74873 ** as an indication to the caller that it should sort by the i-th column.
74874 ** The left-most column is 1.  In other words, the value returned is the
74875 ** same integer value that would be used in the SQL statement to indicate
74876 ** the column.
74877 **
74878 ** If there is no match, return 0.  Return -1 if an error occurs.
74879 */
74880 static int resolveOrderByTermToExprList(
74881   Parse *pParse,     /* Parsing context for error messages */
74882   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
74883   Expr *pE           /* The specific ORDER BY term */
74884 ){
74885   int i;             /* Loop counter */
74886   ExprList *pEList;  /* The columns of the result set */
74887   NameContext nc;    /* Name context for resolving pE */
74888   sqlite3 *db;       /* Database connection */
74889   int rc;            /* Return code from subprocedures */
74890   u8 savedSuppErr;   /* Saved value of db->suppressErr */
74891
74892   assert( sqlite3ExprIsInteger(pE, &i)==0 );
74893   pEList = pSelect->pEList;
74894
74895   /* Resolve all names in the ORDER BY term expression
74896   */
74897   memset(&nc, 0, sizeof(nc));
74898   nc.pParse = pParse;
74899   nc.pSrcList = pSelect->pSrc;
74900   nc.pEList = pEList;
74901   nc.ncFlags = NC_AllowAgg;
74902   nc.nErr = 0;
74903   db = pParse->db;
74904   savedSuppErr = db->suppressErr;
74905   db->suppressErr = 1;
74906   rc = sqlite3ResolveExprNames(&nc, pE);
74907   db->suppressErr = savedSuppErr;
74908   if( rc ) return 0;
74909
74910   /* Try to match the ORDER BY expression against an expression
74911   ** in the result set.  Return an 1-based index of the matching
74912   ** result-set entry.
74913   */
74914   for(i=0; i<pEList->nExpr; i++){
74915     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
74916       return i+1;
74917     }
74918   }
74919
74920   /* If no match, return 0. */
74921   return 0;
74922 }
74923
74924 /*
74925 ** Generate an ORDER BY or GROUP BY term out-of-range error.
74926 */
74927 static void resolveOutOfRangeError(
74928   Parse *pParse,         /* The error context into which to write the error */
74929   const char *zType,     /* "ORDER" or "GROUP" */
74930   int i,                 /* The index (1-based) of the term out of range */
74931   int mx                 /* Largest permissible value of i */
74932 ){
74933   sqlite3ErrorMsg(pParse,
74934     "%r %s BY term out of range - should be "
74935     "between 1 and %d", i, zType, mx);
74936 }
74937
74938 /*
74939 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
74940 ** each term of the ORDER BY clause is a constant integer between 1
74941 ** and N where N is the number of columns in the compound SELECT.
74942 **
74943 ** ORDER BY terms that are already an integer between 1 and N are
74944 ** unmodified.  ORDER BY terms that are integers outside the range of
74945 ** 1 through N generate an error.  ORDER BY terms that are expressions
74946 ** are matched against result set expressions of compound SELECT
74947 ** beginning with the left-most SELECT and working toward the right.
74948 ** At the first match, the ORDER BY expression is transformed into
74949 ** the integer column number.
74950 **
74951 ** Return the number of errors seen.
74952 */
74953 static int resolveCompoundOrderBy(
74954   Parse *pParse,        /* Parsing context.  Leave error messages here */
74955   Select *pSelect       /* The SELECT statement containing the ORDER BY */
74956 ){
74957   int i;
74958   ExprList *pOrderBy;
74959   ExprList *pEList;
74960   sqlite3 *db;
74961   int moreToDo = 1;
74962
74963   pOrderBy = pSelect->pOrderBy;
74964   if( pOrderBy==0 ) return 0;
74965   db = pParse->db;
74966 #if SQLITE_MAX_COLUMN
74967   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74968     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
74969     return 1;
74970   }
74971 #endif
74972   for(i=0; i<pOrderBy->nExpr; i++){
74973     pOrderBy->a[i].done = 0;
74974   }
74975   pSelect->pNext = 0;
74976   while( pSelect->pPrior ){
74977     pSelect->pPrior->pNext = pSelect;
74978     pSelect = pSelect->pPrior;
74979   }
74980   while( pSelect && moreToDo ){
74981     struct ExprList_item *pItem;
74982     moreToDo = 0;
74983     pEList = pSelect->pEList;
74984     assert( pEList!=0 );
74985     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74986       int iCol = -1;
74987       Expr *pE, *pDup;
74988       if( pItem->done ) continue;
74989       pE = sqlite3ExprSkipCollate(pItem->pExpr);
74990       if( sqlite3ExprIsInteger(pE, &iCol) ){
74991         if( iCol<=0 || iCol>pEList->nExpr ){
74992           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
74993           return 1;
74994         }
74995       }else{
74996         iCol = resolveAsName(pParse, pEList, pE);
74997         if( iCol==0 ){
74998           pDup = sqlite3ExprDup(db, pE, 0);
74999           if( !db->mallocFailed ){
75000             assert(pDup);
75001             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
75002           }
75003           sqlite3ExprDelete(db, pDup);
75004         }
75005       }
75006       if( iCol>0 ){
75007         /* Convert the ORDER BY term into an integer column number iCol,
75008         ** taking care to preserve the COLLATE clause if it exists */
75009         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
75010         if( pNew==0 ) return 1;
75011         pNew->flags |= EP_IntValue;
75012         pNew->u.iValue = iCol;
75013         if( pItem->pExpr==pE ){
75014           pItem->pExpr = pNew;
75015         }else{
75016           assert( pItem->pExpr->op==TK_COLLATE );
75017           assert( pItem->pExpr->pLeft==pE );
75018           pItem->pExpr->pLeft = pNew;
75019         }
75020         sqlite3ExprDelete(db, pE);
75021         pItem->iOrderByCol = (u16)iCol;
75022         pItem->done = 1;
75023       }else{
75024         moreToDo = 1;
75025       }
75026     }
75027     pSelect = pSelect->pNext;
75028   }
75029   for(i=0; i<pOrderBy->nExpr; i++){
75030     if( pOrderBy->a[i].done==0 ){
75031       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
75032             "column in the result set", i+1);
75033       return 1;
75034     }
75035   }
75036   return 0;
75037 }
75038
75039 /*
75040 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
75041 ** the SELECT statement pSelect.  If any term is reference to a
75042 ** result set expression (as determined by the ExprList.a.iCol field)
75043 ** then convert that term into a copy of the corresponding result set
75044 ** column.
75045 **
75046 ** If any errors are detected, add an error message to pParse and
75047 ** return non-zero.  Return zero if no errors are seen.
75048 */
75049 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
75050   Parse *pParse,        /* Parsing context.  Leave error messages here */
75051   Select *pSelect,      /* The SELECT statement containing the clause */
75052   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
75053   const char *zType     /* "ORDER" or "GROUP" */
75054 ){
75055   int i;
75056   sqlite3 *db = pParse->db;
75057   ExprList *pEList;
75058   struct ExprList_item *pItem;
75059
75060   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
75061 #if SQLITE_MAX_COLUMN
75062   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
75063     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
75064     return 1;
75065   }
75066 #endif
75067   pEList = pSelect->pEList;
75068   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
75069   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
75070     if( pItem->iOrderByCol ){
75071       if( pItem->iOrderByCol>pEList->nExpr ){
75072         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
75073         return 1;
75074       }
75075       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
75076     }
75077   }
75078   return 0;
75079 }
75080
75081 /*
75082 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
75083 ** The Name context of the SELECT statement is pNC.  zType is either
75084 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
75085 **
75086 ** This routine resolves each term of the clause into an expression.
75087 ** If the order-by term is an integer I between 1 and N (where N is the
75088 ** number of columns in the result set of the SELECT) then the expression
75089 ** in the resolution is a copy of the I-th result-set expression.  If
75090 ** the order-by term is an identify that corresponds to the AS-name of
75091 ** a result-set expression, then the term resolves to a copy of the
75092 ** result-set expression.  Otherwise, the expression is resolved in
75093 ** the usual way - using sqlite3ResolveExprNames().
75094 **
75095 ** This routine returns the number of errors.  If errors occur, then
75096 ** an appropriate error message might be left in pParse.  (OOM errors
75097 ** excepted.)
75098 */
75099 static int resolveOrderGroupBy(
75100   NameContext *pNC,     /* The name context of the SELECT statement */
75101   Select *pSelect,      /* The SELECT statement holding pOrderBy */
75102   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
75103   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
75104 ){
75105   int i, j;                      /* Loop counters */
75106   int iCol;                      /* Column number */
75107   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
75108   Parse *pParse;                 /* Parsing context */
75109   int nResult;                   /* Number of terms in the result set */
75110
75111   if( pOrderBy==0 ) return 0;
75112   nResult = pSelect->pEList->nExpr;
75113   pParse = pNC->pParse;
75114   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
75115     Expr *pE = pItem->pExpr;
75116     iCol = resolveAsName(pParse, pSelect->pEList, pE);
75117     if( iCol>0 ){
75118       /* If an AS-name match is found, mark this ORDER BY column as being
75119       ** a copy of the iCol-th result-set column.  The subsequent call to
75120       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
75121       ** copy of the iCol-th result-set expression. */
75122       pItem->iOrderByCol = (u16)iCol;
75123       continue;
75124     }
75125     if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
75126       /* The ORDER BY term is an integer constant.  Again, set the column
75127       ** number so that sqlite3ResolveOrderGroupBy() will convert the
75128       ** order-by term to a copy of the result-set expression */
75129       if( iCol<1 || iCol>0xffff ){
75130         resolveOutOfRangeError(pParse, zType, i+1, nResult);
75131         return 1;
75132       }
75133       pItem->iOrderByCol = (u16)iCol;
75134       continue;
75135     }
75136
75137     /* Otherwise, treat the ORDER BY term as an ordinary expression */
75138     pItem->iOrderByCol = 0;
75139     if( sqlite3ResolveExprNames(pNC, pE) ){
75140       return 1;
75141     }
75142     for(j=0; j<pSelect->pEList->nExpr; j++){
75143       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
75144         pItem->iOrderByCol = j+1;
75145       }
75146     }
75147   }
75148   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
75149 }
75150
75151 /*
75152 ** Resolve names in the SELECT statement p and all of its descendents.
75153 */
75154 static int resolveSelectStep(Walker *pWalker, Select *p){
75155   NameContext *pOuterNC;  /* Context that contains this SELECT */
75156   NameContext sNC;        /* Name context of this SELECT */
75157   int isCompound;         /* True if p is a compound select */
75158   int nCompound;          /* Number of compound terms processed so far */
75159   Parse *pParse;          /* Parsing context */
75160   ExprList *pEList;       /* Result set expression list */
75161   int i;                  /* Loop counter */
75162   ExprList *pGroupBy;     /* The GROUP BY clause */
75163   Select *pLeftmost;      /* Left-most of SELECT of a compound */
75164   sqlite3 *db;            /* Database connection */
75165
75166
75167   assert( p!=0 );
75168   if( p->selFlags & SF_Resolved ){
75169     return WRC_Prune;
75170   }
75171   pOuterNC = pWalker->u.pNC;
75172   pParse = pWalker->pParse;
75173   db = pParse->db;
75174
75175   /* Normally sqlite3SelectExpand() will be called first and will have
75176   ** already expanded this SELECT.  However, if this is a subquery within
75177   ** an expression, sqlite3ResolveExprNames() will be called without a
75178   ** prior call to sqlite3SelectExpand().  When that happens, let
75179   ** sqlite3SelectPrep() do all of the processing for this SELECT.
75180   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
75181   ** this routine in the correct order.
75182   */
75183   if( (p->selFlags & SF_Expanded)==0 ){
75184     sqlite3SelectPrep(pParse, p, pOuterNC);
75185     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
75186   }
75187
75188   isCompound = p->pPrior!=0;
75189   nCompound = 0;
75190   pLeftmost = p;
75191   while( p ){
75192     assert( (p->selFlags & SF_Expanded)!=0 );
75193     assert( (p->selFlags & SF_Resolved)==0 );
75194     p->selFlags |= SF_Resolved;
75195
75196     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
75197     ** are not allowed to refer to any names, so pass an empty NameContext.
75198     */
75199     memset(&sNC, 0, sizeof(sNC));
75200     sNC.pParse = pParse;
75201     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
75202         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
75203       return WRC_Abort;
75204     }
75205
75206     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
75207     ** resolve the result-set expression list.
75208     */
75209     sNC.ncFlags = NC_AllowAgg;
75210     sNC.pSrcList = p->pSrc;
75211     sNC.pNext = pOuterNC;
75212
75213     /* Resolve names in the result set. */
75214     pEList = p->pEList;
75215     assert( pEList!=0 );
75216     for(i=0; i<pEList->nExpr; i++){
75217       Expr *pX = pEList->a[i].pExpr;
75218       if( sqlite3ResolveExprNames(&sNC, pX) ){
75219         return WRC_Abort;
75220       }
75221     }
75222
75223     /* Recursively resolve names in all subqueries
75224     */
75225     for(i=0; i<p->pSrc->nSrc; i++){
75226       struct SrcList_item *pItem = &p->pSrc->a[i];
75227       if( pItem->pSelect ){
75228         NameContext *pNC;         /* Used to iterate name contexts */
75229         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
75230         const char *zSavedContext = pParse->zAuthContext;
75231
75232         /* Count the total number of references to pOuterNC and all of its
75233         ** parent contexts. After resolving references to expressions in
75234         ** pItem->pSelect, check if this value has changed. If so, then
75235         ** SELECT statement pItem->pSelect must be correlated. Set the
75236         ** pItem->isCorrelated flag if this is the case. */
75237         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
75238
75239         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
75240         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
75241         pParse->zAuthContext = zSavedContext;
75242         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
75243
75244         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
75245         assert( pItem->isCorrelated==0 && nRef<=0 );
75246         pItem->isCorrelated = (nRef!=0);
75247       }
75248     }
75249
75250     /* If there are no aggregate functions in the result-set, and no GROUP BY
75251     ** expression, do not allow aggregates in any of the other expressions.
75252     */
75253     assert( (p->selFlags & SF_Aggregate)==0 );
75254     pGroupBy = p->pGroupBy;
75255     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
75256       p->selFlags |= SF_Aggregate;
75257     }else{
75258       sNC.ncFlags &= ~NC_AllowAgg;
75259     }
75260
75261     /* If a HAVING clause is present, then there must be a GROUP BY clause.
75262     */
75263     if( p->pHaving && !pGroupBy ){
75264       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
75265       return WRC_Abort;
75266     }
75267
75268     /* Add the expression list to the name-context before parsing the
75269     ** other expressions in the SELECT statement. This is so that
75270     ** expressions in the WHERE clause (etc.) can refer to expressions by
75271     ** aliases in the result set.
75272     **
75273     ** Minor point: If this is the case, then the expression will be
75274     ** re-evaluated for each reference to it.
75275     */
75276     sNC.pEList = p->pEList;
75277     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
75278        sqlite3ResolveExprNames(&sNC, p->pHaving)
75279     ){
75280       return WRC_Abort;
75281     }
75282
75283     /* The ORDER BY and GROUP BY clauses may not refer to terms in
75284     ** outer queries
75285     */
75286     sNC.pNext = 0;
75287     sNC.ncFlags |= NC_AllowAgg;
75288
75289     /* Process the ORDER BY clause for singleton SELECT statements.
75290     ** The ORDER BY clause for compounds SELECT statements is handled
75291     ** below, after all of the result-sets for all of the elements of
75292     ** the compound have been resolved.
75293     */
75294     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
75295       return WRC_Abort;
75296     }
75297     if( db->mallocFailed ){
75298       return WRC_Abort;
75299     }
75300
75301     /* Resolve the GROUP BY clause.  At the same time, make sure
75302     ** the GROUP BY clause does not contain aggregate functions.
75303     */
75304     if( pGroupBy ){
75305       struct ExprList_item *pItem;
75306
75307       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
75308         return WRC_Abort;
75309       }
75310       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
75311         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
75312           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
75313               "the GROUP BY clause");
75314           return WRC_Abort;
75315         }
75316       }
75317     }
75318
75319     /* Advance to the next term of the compound
75320     */
75321     p = p->pPrior;
75322     nCompound++;
75323   }
75324
75325   /* Resolve the ORDER BY on a compound SELECT after all terms of
75326   ** the compound have been resolved.
75327   */
75328   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
75329     return WRC_Abort;
75330   }
75331
75332   return WRC_Prune;
75333 }
75334
75335 /*
75336 ** This routine walks an expression tree and resolves references to
75337 ** table columns and result-set columns.  At the same time, do error
75338 ** checking on function usage and set a flag if any aggregate functions
75339 ** are seen.
75340 **
75341 ** To resolve table columns references we look for nodes (or subtrees) of the
75342 ** form X.Y.Z or Y.Z or just Z where
75343 **
75344 **      X:   The name of a database.  Ex:  "main" or "temp" or
75345 **           the symbolic name assigned to an ATTACH-ed database.
75346 **
75347 **      Y:   The name of a table in a FROM clause.  Or in a trigger
75348 **           one of the special names "old" or "new".
75349 **
75350 **      Z:   The name of a column in table Y.
75351 **
75352 ** The node at the root of the subtree is modified as follows:
75353 **
75354 **    Expr.op        Changed to TK_COLUMN
75355 **    Expr.pTab      Points to the Table object for X.Y
75356 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
75357 **    Expr.iTable    The VDBE cursor number for X.Y
75358 **
75359 **
75360 ** To resolve result-set references, look for expression nodes of the
75361 ** form Z (with no X and Y prefix) where the Z matches the right-hand
75362 ** size of an AS clause in the result-set of a SELECT.  The Z expression
75363 ** is replaced by a copy of the left-hand side of the result-set expression.
75364 ** Table-name and function resolution occurs on the substituted expression
75365 ** tree.  For example, in:
75366 **
75367 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
75368 **
75369 ** The "x" term of the order by is replaced by "a+b" to render:
75370 **
75371 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
75372 **
75373 ** Function calls are checked to make sure that the function is
75374 ** defined and that the correct number of arguments are specified.
75375 ** If the function is an aggregate function, then the NC_HasAgg flag is
75376 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
75377 ** If an expression contains aggregate functions then the EP_Agg
75378 ** property on the expression is set.
75379 **
75380 ** An error message is left in pParse if anything is amiss.  The number
75381 ** if errors is returned.
75382 */
75383 SQLITE_PRIVATE int sqlite3ResolveExprNames(
75384   NameContext *pNC,       /* Namespace to resolve expressions in. */
75385   Expr *pExpr             /* The expression to be analyzed. */
75386 ){
75387   u8 savedHasAgg;
75388   Walker w;
75389
75390   if( pExpr==0 ) return 0;
75391 #if SQLITE_MAX_EXPR_DEPTH>0
75392   {
75393     Parse *pParse = pNC->pParse;
75394     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
75395       return 1;
75396     }
75397     pParse->nHeight += pExpr->nHeight;
75398   }
75399 #endif
75400   savedHasAgg = pNC->ncFlags & NC_HasAgg;
75401   pNC->ncFlags &= ~NC_HasAgg;
75402   w.xExprCallback = resolveExprStep;
75403   w.xSelectCallback = resolveSelectStep;
75404   w.pParse = pNC->pParse;
75405   w.u.pNC = pNC;
75406   sqlite3WalkExpr(&w, pExpr);
75407 #if SQLITE_MAX_EXPR_DEPTH>0
75408   pNC->pParse->nHeight -= pExpr->nHeight;
75409 #endif
75410   if( pNC->nErr>0 || w.pParse->nErr>0 ){
75411     ExprSetProperty(pExpr, EP_Error);
75412   }
75413   if( pNC->ncFlags & NC_HasAgg ){
75414     ExprSetProperty(pExpr, EP_Agg);
75415   }else if( savedHasAgg ){
75416     pNC->ncFlags |= NC_HasAgg;
75417   }
75418   return ExprHasProperty(pExpr, EP_Error);
75419 }
75420
75421
75422 /*
75423 ** Resolve all names in all expressions of a SELECT and in all
75424 ** decendents of the SELECT, including compounds off of p->pPrior,
75425 ** subqueries in expressions, and subqueries used as FROM clause
75426 ** terms.
75427 **
75428 ** See sqlite3ResolveExprNames() for a description of the kinds of
75429 ** transformations that occur.
75430 **
75431 ** All SELECT statements should have been expanded using
75432 ** sqlite3SelectExpand() prior to invoking this routine.
75433 */
75434 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
75435   Parse *pParse,         /* The parser context */
75436   Select *p,             /* The SELECT statement being coded. */
75437   NameContext *pOuterNC  /* Name context for parent SELECT statement */
75438 ){
75439   Walker w;
75440
75441   assert( p!=0 );
75442   w.xExprCallback = resolveExprStep;
75443   w.xSelectCallback = resolveSelectStep;
75444   w.pParse = pParse;
75445   w.u.pNC = pOuterNC;
75446   sqlite3WalkSelect(&w, p);
75447 }
75448
75449 /************** End of resolve.c *********************************************/
75450 /************** Begin file expr.c ********************************************/
75451 /*
75452 ** 2001 September 15
75453 **
75454 ** The author disclaims copyright to this source code.  In place of
75455 ** a legal notice, here is a blessing:
75456 **
75457 **    May you do good and not evil.
75458 **    May you find forgiveness for yourself and forgive others.
75459 **    May you share freely, never taking more than you give.
75460 **
75461 *************************************************************************
75462 ** This file contains routines used for analyzing expressions and
75463 ** for generating VDBE code that evaluates expressions in SQLite.
75464 */
75465
75466 /*
75467 ** Return the 'affinity' of the expression pExpr if any.
75468 **
75469 ** If pExpr is a column, a reference to a column via an 'AS' alias,
75470 ** or a sub-select with a column as the return value, then the
75471 ** affinity of that column is returned. Otherwise, 0x00 is returned,
75472 ** indicating no affinity for the expression.
75473 **
75474 ** i.e. the WHERE clause expresssions in the following statements all
75475 ** have an affinity:
75476 **
75477 ** CREATE TABLE t1(a);
75478 ** SELECT * FROM t1 WHERE a;
75479 ** SELECT a AS b FROM t1 WHERE b;
75480 ** SELECT * FROM t1 WHERE (select a from t1);
75481 */
75482 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
75483   int op;
75484   pExpr = sqlite3ExprSkipCollate(pExpr);
75485   op = pExpr->op;
75486   if( op==TK_SELECT ){
75487     assert( pExpr->flags&EP_xIsSelect );
75488     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
75489   }
75490 #ifndef SQLITE_OMIT_CAST
75491   if( op==TK_CAST ){
75492     assert( !ExprHasProperty(pExpr, EP_IntValue) );
75493     return sqlite3AffinityType(pExpr->u.zToken);
75494   }
75495 #endif
75496   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
75497    && pExpr->pTab!=0
75498   ){
75499     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
75500     ** a TK_COLUMN but was previously evaluated and cached in a register */
75501     int j = pExpr->iColumn;
75502     if( j<0 ) return SQLITE_AFF_INTEGER;
75503     assert( pExpr->pTab && j<pExpr->pTab->nCol );
75504     return pExpr->pTab->aCol[j].affinity;
75505   }
75506   return pExpr->affinity;
75507 }
75508
75509 /*
75510 ** Set the collating sequence for expression pExpr to be the collating
75511 ** sequence named by pToken.   Return a pointer to a new Expr node that
75512 ** implements the COLLATE operator.
75513 **
75514 ** If a memory allocation error occurs, that fact is recorded in pParse->db
75515 ** and the pExpr parameter is returned unchanged.
75516 */
75517 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
75518   if( pCollName->n>0 ){
75519     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
75520     if( pNew ){
75521       pNew->pLeft = pExpr;
75522       pNew->flags |= EP_Collate;
75523       pExpr = pNew;
75524     }
75525   }
75526   return pExpr;
75527 }
75528 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
75529   Token s;
75530   assert( zC!=0 );
75531   s.z = zC;
75532   s.n = sqlite3Strlen30(s.z);
75533   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
75534 }
75535
75536 /*
75537 ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
75538 ** an expression.
75539 */
75540 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
75541   while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
75542     pExpr = pExpr->pLeft;
75543   }
75544   return pExpr;
75545 }
75546
75547 /*
75548 ** Return the collation sequence for the expression pExpr. If
75549 ** there is no defined collating sequence, return NULL.
75550 **
75551 ** The collating sequence might be determined by a COLLATE operator
75552 ** or by the presence of a column with a defined collating sequence.
75553 ** COLLATE operators take first precedence.  Left operands take
75554 ** precedence over right operands.
75555 */
75556 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
75557   sqlite3 *db = pParse->db;
75558   CollSeq *pColl = 0;
75559   Expr *p = pExpr;
75560   while( p ){
75561     int op = p->op;
75562     if( op==TK_CAST || op==TK_UPLUS ){
75563       p = p->pLeft;
75564       continue;
75565     }
75566     assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
75567     if( op==TK_COLLATE ){
75568       if( db->init.busy ){
75569         /* Do not report errors when parsing while the schema */
75570         pColl = sqlite3FindCollSeq(db, ENC(db), p->u.zToken, 0);
75571       }else{
75572         pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
75573       }
75574       break;
75575     }
75576     if( p->pTab!=0
75577      && (op==TK_AGG_COLUMN || op==TK_COLUMN
75578           || op==TK_REGISTER || op==TK_TRIGGER)
75579     ){
75580       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
75581       ** a TK_COLUMN but was previously evaluated and cached in a register */
75582       int j = p->iColumn;
75583       if( j>=0 ){
75584         const char *zColl = p->pTab->aCol[j].zColl;
75585         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
75586       }
75587       break;
75588     }
75589     if( p->flags & EP_Collate ){
75590       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
75591         p = p->pLeft;
75592       }else{
75593         p = p->pRight;
75594       }
75595     }else{
75596       break;
75597     }
75598   }
75599   if( sqlite3CheckCollSeq(pParse, pColl) ){
75600     pColl = 0;
75601   }
75602   return pColl;
75603 }
75604
75605 /*
75606 ** pExpr is an operand of a comparison operator.  aff2 is the
75607 ** type affinity of the other operand.  This routine returns the
75608 ** type affinity that should be used for the comparison operator.
75609 */
75610 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
75611   char aff1 = sqlite3ExprAffinity(pExpr);
75612   if( aff1 && aff2 ){
75613     /* Both sides of the comparison are columns. If one has numeric
75614     ** affinity, use that. Otherwise use no affinity.
75615     */
75616     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
75617       return SQLITE_AFF_NUMERIC;
75618     }else{
75619       return SQLITE_AFF_NONE;
75620     }
75621   }else if( !aff1 && !aff2 ){
75622     /* Neither side of the comparison is a column.  Compare the
75623     ** results directly.
75624     */
75625     return SQLITE_AFF_NONE;
75626   }else{
75627     /* One side is a column, the other is not. Use the columns affinity. */
75628     assert( aff1==0 || aff2==0 );
75629     return (aff1 + aff2);
75630   }
75631 }
75632
75633 /*
75634 ** pExpr is a comparison operator.  Return the type affinity that should
75635 ** be applied to both operands prior to doing the comparison.
75636 */
75637 static char comparisonAffinity(Expr *pExpr){
75638   char aff;
75639   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
75640           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
75641           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
75642   assert( pExpr->pLeft );
75643   aff = sqlite3ExprAffinity(pExpr->pLeft);
75644   if( pExpr->pRight ){
75645     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
75646   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75647     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
75648   }else if( !aff ){
75649     aff = SQLITE_AFF_NONE;
75650   }
75651   return aff;
75652 }
75653
75654 /*
75655 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
75656 ** idx_affinity is the affinity of an indexed column. Return true
75657 ** if the index with affinity idx_affinity may be used to implement
75658 ** the comparison in pExpr.
75659 */
75660 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
75661   char aff = comparisonAffinity(pExpr);
75662   switch( aff ){
75663     case SQLITE_AFF_NONE:
75664       return 1;
75665     case SQLITE_AFF_TEXT:
75666       return idx_affinity==SQLITE_AFF_TEXT;
75667     default:
75668       return sqlite3IsNumericAffinity(idx_affinity);
75669   }
75670 }
75671
75672 /*
75673 ** Return the P5 value that should be used for a binary comparison
75674 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
75675 */
75676 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
75677   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
75678   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
75679   return aff;
75680 }
75681
75682 /*
75683 ** Return a pointer to the collation sequence that should be used by
75684 ** a binary comparison operator comparing pLeft and pRight.
75685 **
75686 ** If the left hand expression has a collating sequence type, then it is
75687 ** used. Otherwise the collation sequence for the right hand expression
75688 ** is used, or the default (BINARY) if neither expression has a collating
75689 ** type.
75690 **
75691 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
75692 ** it is not considered.
75693 */
75694 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
75695   Parse *pParse,
75696   Expr *pLeft,
75697   Expr *pRight
75698 ){
75699   CollSeq *pColl;
75700   assert( pLeft );
75701   if( pLeft->flags & EP_Collate ){
75702     pColl = sqlite3ExprCollSeq(pParse, pLeft);
75703   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
75704     pColl = sqlite3ExprCollSeq(pParse, pRight);
75705   }else{
75706     pColl = sqlite3ExprCollSeq(pParse, pLeft);
75707     if( !pColl ){
75708       pColl = sqlite3ExprCollSeq(pParse, pRight);
75709     }
75710   }
75711   return pColl;
75712 }
75713
75714 /*
75715 ** Generate code for a comparison operator.
75716 */
75717 static int codeCompare(
75718   Parse *pParse,    /* The parsing (and code generating) context */
75719   Expr *pLeft,      /* The left operand */
75720   Expr *pRight,     /* The right operand */
75721   int opcode,       /* The comparison opcode */
75722   int in1, int in2, /* Register holding operands */
75723   int dest,         /* Jump here if true.  */
75724   int jumpIfNull    /* If true, jump if either operand is NULL */
75725 ){
75726   int p5;
75727   int addr;
75728   CollSeq *p4;
75729
75730   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
75731   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
75732   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
75733                            (void*)p4, P4_COLLSEQ);
75734   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
75735   return addr;
75736 }
75737
75738 #if SQLITE_MAX_EXPR_DEPTH>0
75739 /*
75740 ** Check that argument nHeight is less than or equal to the maximum
75741 ** expression depth allowed. If it is not, leave an error message in
75742 ** pParse.
75743 */
75744 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
75745   int rc = SQLITE_OK;
75746   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
75747   if( nHeight>mxHeight ){
75748     sqlite3ErrorMsg(pParse,
75749        "Expression tree is too large (maximum depth %d)", mxHeight
75750     );
75751     rc = SQLITE_ERROR;
75752   }
75753   return rc;
75754 }
75755
75756 /* The following three functions, heightOfExpr(), heightOfExprList()
75757 ** and heightOfSelect(), are used to determine the maximum height
75758 ** of any expression tree referenced by the structure passed as the
75759 ** first argument.
75760 **
75761 ** If this maximum height is greater than the current value pointed
75762 ** to by pnHeight, the second parameter, then set *pnHeight to that
75763 ** value.
75764 */
75765 static void heightOfExpr(Expr *p, int *pnHeight){
75766   if( p ){
75767     if( p->nHeight>*pnHeight ){
75768       *pnHeight = p->nHeight;
75769     }
75770   }
75771 }
75772 static void heightOfExprList(ExprList *p, int *pnHeight){
75773   if( p ){
75774     int i;
75775     for(i=0; i<p->nExpr; i++){
75776       heightOfExpr(p->a[i].pExpr, pnHeight);
75777     }
75778   }
75779 }
75780 static void heightOfSelect(Select *p, int *pnHeight){
75781   if( p ){
75782     heightOfExpr(p->pWhere, pnHeight);
75783     heightOfExpr(p->pHaving, pnHeight);
75784     heightOfExpr(p->pLimit, pnHeight);
75785     heightOfExpr(p->pOffset, pnHeight);
75786     heightOfExprList(p->pEList, pnHeight);
75787     heightOfExprList(p->pGroupBy, pnHeight);
75788     heightOfExprList(p->pOrderBy, pnHeight);
75789     heightOfSelect(p->pPrior, pnHeight);
75790   }
75791 }
75792
75793 /*
75794 ** Set the Expr.nHeight variable in the structure passed as an
75795 ** argument. An expression with no children, Expr.pList or
75796 ** Expr.pSelect member has a height of 1. Any other expression
75797 ** has a height equal to the maximum height of any other
75798 ** referenced Expr plus one.
75799 */
75800 static void exprSetHeight(Expr *p){
75801   int nHeight = 0;
75802   heightOfExpr(p->pLeft, &nHeight);
75803   heightOfExpr(p->pRight, &nHeight);
75804   if( ExprHasProperty(p, EP_xIsSelect) ){
75805     heightOfSelect(p->x.pSelect, &nHeight);
75806   }else{
75807     heightOfExprList(p->x.pList, &nHeight);
75808   }
75809   p->nHeight = nHeight + 1;
75810 }
75811
75812 /*
75813 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
75814 ** the height is greater than the maximum allowed expression depth,
75815 ** leave an error in pParse.
75816 */
75817 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
75818   exprSetHeight(p);
75819   sqlite3ExprCheckHeight(pParse, p->nHeight);
75820 }
75821
75822 /*
75823 ** Return the maximum height of any expression tree referenced
75824 ** by the select statement passed as an argument.
75825 */
75826 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
75827   int nHeight = 0;
75828   heightOfSelect(p, &nHeight);
75829   return nHeight;
75830 }
75831 #else
75832   #define exprSetHeight(y)
75833 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
75834
75835 /*
75836 ** This routine is the core allocator for Expr nodes.
75837 **
75838 ** Construct a new expression node and return a pointer to it.  Memory
75839 ** for this node and for the pToken argument is a single allocation
75840 ** obtained from sqlite3DbMalloc().  The calling function
75841 ** is responsible for making sure the node eventually gets freed.
75842 **
75843 ** If dequote is true, then the token (if it exists) is dequoted.
75844 ** If dequote is false, no dequoting is performance.  The deQuote
75845 ** parameter is ignored if pToken is NULL or if the token does not
75846 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
75847 ** then the EP_DblQuoted flag is set on the expression node.
75848 **
75849 ** Special case:  If op==TK_INTEGER and pToken points to a string that
75850 ** can be translated into a 32-bit integer, then the token is not
75851 ** stored in u.zToken.  Instead, the integer values is written
75852 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
75853 ** is allocated to hold the integer text and the dequote flag is ignored.
75854 */
75855 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
75856   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75857   int op,                 /* Expression opcode */
75858   const Token *pToken,    /* Token argument.  Might be NULL */
75859   int dequote             /* True to dequote */
75860 ){
75861   Expr *pNew;
75862   int nExtra = 0;
75863   int iValue = 0;
75864
75865   if( pToken ){
75866     if( op!=TK_INTEGER || pToken->z==0
75867           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
75868       nExtra = pToken->n+1;
75869       assert( iValue>=0 );
75870     }
75871   }
75872   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
75873   if( pNew ){
75874     pNew->op = (u8)op;
75875     pNew->iAgg = -1;
75876     if( pToken ){
75877       if( nExtra==0 ){
75878         pNew->flags |= EP_IntValue;
75879         pNew->u.iValue = iValue;
75880       }else{
75881         int c;
75882         pNew->u.zToken = (char*)&pNew[1];
75883         assert( pToken->z!=0 || pToken->n==0 );
75884         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
75885         pNew->u.zToken[pToken->n] = 0;
75886         if( dequote && nExtra>=3
75887              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
75888           sqlite3Dequote(pNew->u.zToken);
75889           if( c=='"' ) pNew->flags |= EP_DblQuoted;
75890         }
75891       }
75892     }
75893 #if SQLITE_MAX_EXPR_DEPTH>0
75894     pNew->nHeight = 1;
75895 #endif
75896   }
75897   return pNew;
75898 }
75899
75900 /*
75901 ** Allocate a new expression node from a zero-terminated token that has
75902 ** already been dequoted.
75903 */
75904 SQLITE_PRIVATE Expr *sqlite3Expr(
75905   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75906   int op,                 /* Expression opcode */
75907   const char *zToken      /* Token argument.  Might be NULL */
75908 ){
75909   Token x;
75910   x.z = zToken;
75911   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
75912   return sqlite3ExprAlloc(db, op, &x, 0);
75913 }
75914
75915 /*
75916 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
75917 **
75918 ** If pRoot==NULL that means that a memory allocation error has occurred.
75919 ** In that case, delete the subtrees pLeft and pRight.
75920 */
75921 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
75922   sqlite3 *db,
75923   Expr *pRoot,
75924   Expr *pLeft,
75925   Expr *pRight
75926 ){
75927   if( pRoot==0 ){
75928     assert( db->mallocFailed );
75929     sqlite3ExprDelete(db, pLeft);
75930     sqlite3ExprDelete(db, pRight);
75931   }else{
75932     if( pRight ){
75933       pRoot->pRight = pRight;
75934       pRoot->flags |= EP_Collate & pRight->flags;
75935     }
75936     if( pLeft ){
75937       pRoot->pLeft = pLeft;
75938       pRoot->flags |= EP_Collate & pLeft->flags;
75939     }
75940     exprSetHeight(pRoot);
75941   }
75942 }
75943
75944 /*
75945 ** Allocate a Expr node which joins as many as two subtrees.
75946 **
75947 ** One or both of the subtrees can be NULL.  Return a pointer to the new
75948 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
75949 ** free the subtrees and return NULL.
75950 */
75951 SQLITE_PRIVATE Expr *sqlite3PExpr(
75952   Parse *pParse,          /* Parsing context */
75953   int op,                 /* Expression opcode */
75954   Expr *pLeft,            /* Left operand */
75955   Expr *pRight,           /* Right operand */
75956   const Token *pToken     /* Argument token */
75957 ){
75958   Expr *p;
75959   if( op==TK_AND && pLeft && pRight ){
75960     /* Take advantage of short-circuit false optimization for AND */
75961     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
75962   }else{
75963     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
75964     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
75965   }
75966   if( p ) {
75967     sqlite3ExprCheckHeight(pParse, p->nHeight);
75968   }
75969   return p;
75970 }
75971
75972 /*
75973 ** Return 1 if an expression must be FALSE in all cases and 0 if the
75974 ** expression might be true.  This is an optimization.  If is OK to
75975 ** return 0 here even if the expression really is always false (a
75976 ** false negative).  But it is a bug to return 1 if the expression
75977 ** might be true in some rare circumstances (a false positive.)
75978 **
75979 ** Note that if the expression is part of conditional for a
75980 ** LEFT JOIN, then we cannot determine at compile-time whether or not
75981 ** is it true or false, so always return 0.
75982 */
75983 static int exprAlwaysFalse(Expr *p){
75984   int v = 0;
75985   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
75986   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
75987   return v==0;
75988 }
75989
75990 /*
75991 ** Join two expressions using an AND operator.  If either expression is
75992 ** NULL, then just return the other expression.
75993 **
75994 ** If one side or the other of the AND is known to be false, then instead
75995 ** of returning an AND expression, just return a constant expression with
75996 ** a value of false.
75997 */
75998 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
75999   if( pLeft==0 ){
76000     return pRight;
76001   }else if( pRight==0 ){
76002     return pLeft;
76003   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
76004     sqlite3ExprDelete(db, pLeft);
76005     sqlite3ExprDelete(db, pRight);
76006     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
76007   }else{
76008     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
76009     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
76010     return pNew;
76011   }
76012 }
76013
76014 /*
76015 ** Construct a new expression node for a function with multiple
76016 ** arguments.
76017 */
76018 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
76019   Expr *pNew;
76020   sqlite3 *db = pParse->db;
76021   assert( pToken );
76022   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
76023   if( pNew==0 ){
76024     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
76025     return 0;
76026   }
76027   pNew->x.pList = pList;
76028   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
76029   sqlite3ExprSetHeight(pParse, pNew);
76030   return pNew;
76031 }
76032
76033 /*
76034 ** Assign a variable number to an expression that encodes a wildcard
76035 ** in the original SQL statement.
76036 **
76037 ** Wildcards consisting of a single "?" are assigned the next sequential
76038 ** variable number.
76039 **
76040 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
76041 ** sure "nnn" is not too be to avoid a denial of service attack when
76042 ** the SQL statement comes from an external source.
76043 **
76044 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
76045 ** as the previous instance of the same wildcard.  Or if this is the first
76046 ** instance of the wildcard, the next sequenial variable number is
76047 ** assigned.
76048 */
76049 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
76050   sqlite3 *db = pParse->db;
76051   const char *z;
76052
76053   if( pExpr==0 ) return;
76054   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
76055   z = pExpr->u.zToken;
76056   assert( z!=0 );
76057   assert( z[0]!=0 );
76058   if( z[1]==0 ){
76059     /* Wildcard of the form "?".  Assign the next variable number */
76060     assert( z[0]=='?' );
76061     pExpr->iColumn = (ynVar)(++pParse->nVar);
76062   }else{
76063     ynVar x = 0;
76064     u32 n = sqlite3Strlen30(z);
76065     if( z[0]=='?' ){
76066       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
76067       ** use it as the variable number */
76068       i64 i;
76069       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
76070       pExpr->iColumn = x = (ynVar)i;
76071       testcase( i==0 );
76072       testcase( i==1 );
76073       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
76074       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
76075       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
76076         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
76077             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
76078         x = 0;
76079       }
76080       if( i>pParse->nVar ){
76081         pParse->nVar = (int)i;
76082       }
76083     }else{
76084       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
76085       ** number as the prior appearance of the same name, or if the name
76086       ** has never appeared before, reuse the same variable number
76087       */
76088       ynVar i;
76089       for(i=0; i<pParse->nzVar; i++){
76090         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
76091           pExpr->iColumn = x = (ynVar)i+1;
76092           break;
76093         }
76094       }
76095       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
76096     }
76097     if( x>0 ){
76098       if( x>pParse->nzVar ){
76099         char **a;
76100         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
76101         if( a==0 ) return;  /* Error reported through db->mallocFailed */
76102         pParse->azVar = a;
76103         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
76104         pParse->nzVar = x;
76105       }
76106       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
76107         sqlite3DbFree(db, pParse->azVar[x-1]);
76108         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
76109       }
76110     }
76111   }
76112   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
76113     sqlite3ErrorMsg(pParse, "too many SQL variables");
76114   }
76115 }
76116
76117 /*
76118 ** Recursively delete an expression tree.
76119 */
76120 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
76121   if( p==0 ) return;
76122   /* Sanity check: Assert that the IntValue is non-negative if it exists */
76123   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
76124   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
76125     sqlite3ExprDelete(db, p->pLeft);
76126     sqlite3ExprDelete(db, p->pRight);
76127     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
76128       sqlite3DbFree(db, p->u.zToken);
76129     }
76130     if( ExprHasProperty(p, EP_xIsSelect) ){
76131       sqlite3SelectDelete(db, p->x.pSelect);
76132     }else{
76133       sqlite3ExprListDelete(db, p->x.pList);
76134     }
76135   }
76136   if( !ExprHasProperty(p, EP_Static) ){
76137     sqlite3DbFree(db, p);
76138   }
76139 }
76140
76141 /*
76142 ** Return the number of bytes allocated for the expression structure
76143 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
76144 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
76145 */
76146 static int exprStructSize(Expr *p){
76147   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
76148   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
76149   return EXPR_FULLSIZE;
76150 }
76151
76152 /*
76153 ** The dupedExpr*Size() routines each return the number of bytes required
76154 ** to store a copy of an expression or expression tree.  They differ in
76155 ** how much of the tree is measured.
76156 **
76157 **     dupedExprStructSize()     Size of only the Expr structure
76158 **     dupedExprNodeSize()       Size of Expr + space for token
76159 **     dupedExprSize()           Expr + token + subtree components
76160 **
76161 ***************************************************************************
76162 **
76163 ** The dupedExprStructSize() function returns two values OR-ed together:
76164 ** (1) the space required for a copy of the Expr structure only and
76165 ** (2) the EP_xxx flags that indicate what the structure size should be.
76166 ** The return values is always one of:
76167 **
76168 **      EXPR_FULLSIZE
76169 **      EXPR_REDUCEDSIZE   | EP_Reduced
76170 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
76171 **
76172 ** The size of the structure can be found by masking the return value
76173 ** of this routine with 0xfff.  The flags can be found by masking the
76174 ** return value with EP_Reduced|EP_TokenOnly.
76175 **
76176 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
76177 ** (unreduced) Expr objects as they or originally constructed by the parser.
76178 ** During expression analysis, extra information is computed and moved into
76179 ** later parts of teh Expr object and that extra information might get chopped
76180 ** off if the expression is reduced.  Note also that it does not work to
76181 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
76182 ** to reduce a pristine expression tree from the parser.  The implementation
76183 ** of dupedExprStructSize() contain multiple assert() statements that attempt
76184 ** to enforce this constraint.
76185 */
76186 static int dupedExprStructSize(Expr *p, int flags){
76187   int nSize;
76188   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
76189   if( 0==(flags&EXPRDUP_REDUCE) ){
76190     nSize = EXPR_FULLSIZE;
76191   }else{
76192     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
76193     assert( !ExprHasProperty(p, EP_FromJoin) );
76194     assert( (p->flags2 & EP2_MallocedToken)==0 );
76195     assert( (p->flags2 & EP2_Irreducible)==0 );
76196     if( p->pLeft || p->pRight || p->x.pList ){
76197       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
76198     }else{
76199       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
76200     }
76201   }
76202   return nSize;
76203 }
76204
76205 /*
76206 ** This function returns the space in bytes required to store the copy
76207 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
76208 ** string is defined.)
76209 */
76210 static int dupedExprNodeSize(Expr *p, int flags){
76211   int nByte = dupedExprStructSize(p, flags) & 0xfff;
76212   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76213     nByte += sqlite3Strlen30(p->u.zToken)+1;
76214   }
76215   return ROUND8(nByte);
76216 }
76217
76218 /*
76219 ** Return the number of bytes required to create a duplicate of the
76220 ** expression passed as the first argument. The second argument is a
76221 ** mask containing EXPRDUP_XXX flags.
76222 **
76223 ** The value returned includes space to create a copy of the Expr struct
76224 ** itself and the buffer referred to by Expr.u.zToken, if any.
76225 **
76226 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
76227 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
76228 ** and Expr.pRight variables (but not for any structures pointed to or
76229 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
76230 */
76231 static int dupedExprSize(Expr *p, int flags){
76232   int nByte = 0;
76233   if( p ){
76234     nByte = dupedExprNodeSize(p, flags);
76235     if( flags&EXPRDUP_REDUCE ){
76236       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
76237     }
76238   }
76239   return nByte;
76240 }
76241
76242 /*
76243 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
76244 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
76245 ** to store the copy of expression p, the copies of p->u.zToken
76246 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
76247 ** if any. Before returning, *pzBuffer is set to the first byte passed the
76248 ** portion of the buffer copied into by this function.
76249 */
76250 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
76251   Expr *pNew = 0;                      /* Value to return */
76252   if( p ){
76253     const int isReduced = (flags&EXPRDUP_REDUCE);
76254     u8 *zAlloc;
76255     u32 staticFlag = 0;
76256
76257     assert( pzBuffer==0 || isReduced );
76258
76259     /* Figure out where to write the new Expr structure. */
76260     if( pzBuffer ){
76261       zAlloc = *pzBuffer;
76262       staticFlag = EP_Static;
76263     }else{
76264       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
76265     }
76266     pNew = (Expr *)zAlloc;
76267
76268     if( pNew ){
76269       /* Set nNewSize to the size allocated for the structure pointed to
76270       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
76271       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
76272       ** by the copy of the p->u.zToken string (if any).
76273       */
76274       const unsigned nStructSize = dupedExprStructSize(p, flags);
76275       const int nNewSize = nStructSize & 0xfff;
76276       int nToken;
76277       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76278         nToken = sqlite3Strlen30(p->u.zToken) + 1;
76279       }else{
76280         nToken = 0;
76281       }
76282       if( isReduced ){
76283         assert( ExprHasProperty(p, EP_Reduced)==0 );
76284         memcpy(zAlloc, p, nNewSize);
76285       }else{
76286         int nSize = exprStructSize(p);
76287         memcpy(zAlloc, p, nSize);
76288         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
76289       }
76290
76291       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
76292       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
76293       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
76294       pNew->flags |= staticFlag;
76295
76296       /* Copy the p->u.zToken string, if any. */
76297       if( nToken ){
76298         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
76299         memcpy(zToken, p->u.zToken, nToken);
76300       }
76301
76302       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
76303         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
76304         if( ExprHasProperty(p, EP_xIsSelect) ){
76305           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
76306         }else{
76307           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
76308         }
76309       }
76310
76311       /* Fill in pNew->pLeft and pNew->pRight. */
76312       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
76313         zAlloc += dupedExprNodeSize(p, flags);
76314         if( ExprHasProperty(pNew, EP_Reduced) ){
76315           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
76316           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
76317         }
76318         if( pzBuffer ){
76319           *pzBuffer = zAlloc;
76320         }
76321       }else{
76322         pNew->flags2 = 0;
76323         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
76324           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
76325           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
76326         }
76327       }
76328
76329     }
76330   }
76331   return pNew;
76332 }
76333
76334 /*
76335 ** The following group of routines make deep copies of expressions,
76336 ** expression lists, ID lists, and select statements.  The copies can
76337 ** be deleted (by being passed to their respective ...Delete() routines)
76338 ** without effecting the originals.
76339 **
76340 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
76341 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
76342 ** by subsequent calls to sqlite*ListAppend() routines.
76343 **
76344 ** Any tables that the SrcList might point to are not duplicated.
76345 **
76346 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
76347 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
76348 ** truncated version of the usual Expr structure that will be stored as
76349 ** part of the in-memory representation of the database schema.
76350 */
76351 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
76352   return exprDup(db, p, flags, 0);
76353 }
76354 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
76355   ExprList *pNew;
76356   struct ExprList_item *pItem, *pOldItem;
76357   int i;
76358   if( p==0 ) return 0;
76359   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76360   if( pNew==0 ) return 0;
76361   pNew->iECursor = 0;
76362   pNew->nExpr = i = p->nExpr;
76363   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
76364   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
76365   if( pItem==0 ){
76366     sqlite3DbFree(db, pNew);
76367     return 0;
76368   }
76369   pOldItem = p->a;
76370   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
76371     Expr *pOldExpr = pOldItem->pExpr;
76372     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
76373     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76374     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
76375     pItem->sortOrder = pOldItem->sortOrder;
76376     pItem->done = 0;
76377     pItem->iOrderByCol = pOldItem->iOrderByCol;
76378     pItem->iAlias = pOldItem->iAlias;
76379   }
76380   return pNew;
76381 }
76382
76383 /*
76384 ** If cursors, triggers, views and subqueries are all omitted from
76385 ** the build, then none of the following routines, except for
76386 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
76387 ** called with a NULL argument.
76388 */
76389 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
76390  || !defined(SQLITE_OMIT_SUBQUERY)
76391 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
76392   SrcList *pNew;
76393   int i;
76394   int nByte;
76395   if( p==0 ) return 0;
76396   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
76397   pNew = sqlite3DbMallocRaw(db, nByte );
76398   if( pNew==0 ) return 0;
76399   pNew->nSrc = pNew->nAlloc = p->nSrc;
76400   for(i=0; i<p->nSrc; i++){
76401     struct SrcList_item *pNewItem = &pNew->a[i];
76402     struct SrcList_item *pOldItem = &p->a[i];
76403     Table *pTab;
76404     pNewItem->pSchema = pOldItem->pSchema;
76405     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
76406     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76407     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
76408     pNewItem->jointype = pOldItem->jointype;
76409     pNewItem->iCursor = pOldItem->iCursor;
76410     pNewItem->addrFillSub = pOldItem->addrFillSub;
76411     pNewItem->regReturn = pOldItem->regReturn;
76412     pNewItem->isCorrelated = pOldItem->isCorrelated;
76413     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
76414     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
76415     pNewItem->notIndexed = pOldItem->notIndexed;
76416     pNewItem->pIndex = pOldItem->pIndex;
76417     pTab = pNewItem->pTab = pOldItem->pTab;
76418     if( pTab ){
76419       pTab->nRef++;
76420     }
76421     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
76422     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
76423     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
76424     pNewItem->colUsed = pOldItem->colUsed;
76425   }
76426   return pNew;
76427 }
76428 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
76429   IdList *pNew;
76430   int i;
76431   if( p==0 ) return 0;
76432   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76433   if( pNew==0 ) return 0;
76434   pNew->nId = p->nId;
76435   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
76436   if( pNew->a==0 ){
76437     sqlite3DbFree(db, pNew);
76438     return 0;
76439   }
76440   /* Note that because the size of the allocation for p->a[] is not
76441   ** necessarily a power of two, sqlite3IdListAppend() may not be called
76442   ** on the duplicate created by this function. */
76443   for(i=0; i<p->nId; i++){
76444     struct IdList_item *pNewItem = &pNew->a[i];
76445     struct IdList_item *pOldItem = &p->a[i];
76446     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76447     pNewItem->idx = pOldItem->idx;
76448   }
76449   return pNew;
76450 }
76451 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76452   Select *pNew, *pPrior;
76453   if( p==0 ) return 0;
76454   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
76455   if( pNew==0 ) return 0;
76456   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
76457   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
76458   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
76459   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
76460   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
76461   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
76462   pNew->op = p->op;
76463   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
76464   if( pPrior ) pPrior->pNext = pNew;
76465   pNew->pNext = 0;
76466   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
76467   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
76468   pNew->iLimit = 0;
76469   pNew->iOffset = 0;
76470   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
76471   pNew->pRightmost = 0;
76472   pNew->addrOpenEphm[0] = -1;
76473   pNew->addrOpenEphm[1] = -1;
76474   pNew->addrOpenEphm[2] = -1;
76475   return pNew;
76476 }
76477 #else
76478 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76479   assert( p==0 );
76480   return 0;
76481 }
76482 #endif
76483
76484
76485 /*
76486 ** Add a new element to the end of an expression list.  If pList is
76487 ** initially NULL, then create a new expression list.
76488 **
76489 ** If a memory allocation error occurs, the entire list is freed and
76490 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
76491 ** that the new entry was successfully appended.
76492 */
76493 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
76494   Parse *pParse,          /* Parsing context */
76495   ExprList *pList,        /* List to which to append. Might be NULL */
76496   Expr *pExpr             /* Expression to be appended. Might be NULL */
76497 ){
76498   sqlite3 *db = pParse->db;
76499   if( pList==0 ){
76500     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
76501     if( pList==0 ){
76502       goto no_mem;
76503     }
76504     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
76505     if( pList->a==0 ) goto no_mem;
76506   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
76507     struct ExprList_item *a;
76508     assert( pList->nExpr>0 );
76509     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
76510     if( a==0 ){
76511       goto no_mem;
76512     }
76513     pList->a = a;
76514   }
76515   assert( pList->a!=0 );
76516   if( 1 ){
76517     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
76518     memset(pItem, 0, sizeof(*pItem));
76519     pItem->pExpr = pExpr;
76520   }
76521   return pList;
76522
76523 no_mem:
76524   /* Avoid leaking memory if malloc has failed. */
76525   sqlite3ExprDelete(db, pExpr);
76526   sqlite3ExprListDelete(db, pList);
76527   return 0;
76528 }
76529
76530 /*
76531 ** Set the ExprList.a[].zName element of the most recently added item
76532 ** on the expression list.
76533 **
76534 ** pList might be NULL following an OOM error.  But pName should never be
76535 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76536 ** is set.
76537 */
76538 SQLITE_PRIVATE void sqlite3ExprListSetName(
76539   Parse *pParse,          /* Parsing context */
76540   ExprList *pList,        /* List to which to add the span. */
76541   Token *pName,           /* Name to be added */
76542   int dequote             /* True to cause the name to be dequoted */
76543 ){
76544   assert( pList!=0 || pParse->db->mallocFailed!=0 );
76545   if( pList ){
76546     struct ExprList_item *pItem;
76547     assert( pList->nExpr>0 );
76548     pItem = &pList->a[pList->nExpr-1];
76549     assert( pItem->zName==0 );
76550     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
76551     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
76552   }
76553 }
76554
76555 /*
76556 ** Set the ExprList.a[].zSpan element of the most recently added item
76557 ** on the expression list.
76558 **
76559 ** pList might be NULL following an OOM error.  But pSpan should never be
76560 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76561 ** is set.
76562 */
76563 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
76564   Parse *pParse,          /* Parsing context */
76565   ExprList *pList,        /* List to which to add the span. */
76566   ExprSpan *pSpan         /* The span to be added */
76567 ){
76568   sqlite3 *db = pParse->db;
76569   assert( pList!=0 || db->mallocFailed!=0 );
76570   if( pList ){
76571     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
76572     assert( pList->nExpr>0 );
76573     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
76574     sqlite3DbFree(db, pItem->zSpan);
76575     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
76576                                     (int)(pSpan->zEnd - pSpan->zStart));
76577   }
76578 }
76579
76580 /*
76581 ** If the expression list pEList contains more than iLimit elements,
76582 ** leave an error message in pParse.
76583 */
76584 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
76585   Parse *pParse,
76586   ExprList *pEList,
76587   const char *zObject
76588 ){
76589   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
76590   testcase( pEList && pEList->nExpr==mx );
76591   testcase( pEList && pEList->nExpr==mx+1 );
76592   if( pEList && pEList->nExpr>mx ){
76593     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
76594   }
76595 }
76596
76597 /*
76598 ** Delete an entire expression list.
76599 */
76600 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
76601   int i;
76602   struct ExprList_item *pItem;
76603   if( pList==0 ) return;
76604   assert( pList->a!=0 || pList->nExpr==0 );
76605   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
76606     sqlite3ExprDelete(db, pItem->pExpr);
76607     sqlite3DbFree(db, pItem->zName);
76608     sqlite3DbFree(db, pItem->zSpan);
76609   }
76610   sqlite3DbFree(db, pList->a);
76611   sqlite3DbFree(db, pList);
76612 }
76613
76614 /*
76615 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
76616 ** to an integer.  These routines are checking an expression to see
76617 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
76618 ** not constant.
76619 **
76620 ** These callback routines are used to implement the following:
76621 **
76622 **     sqlite3ExprIsConstant()
76623 **     sqlite3ExprIsConstantNotJoin()
76624 **     sqlite3ExprIsConstantOrFunction()
76625 **
76626 */
76627 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
76628
76629   /* If pWalker->u.i is 3 then any term of the expression that comes from
76630   ** the ON or USING clauses of a join disqualifies the expression
76631   ** from being considered constant. */
76632   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
76633     pWalker->u.i = 0;
76634     return WRC_Abort;
76635   }
76636
76637   switch( pExpr->op ){
76638     /* Consider functions to be constant if all their arguments are constant
76639     ** and pWalker->u.i==2 */
76640     case TK_FUNCTION:
76641       if( pWalker->u.i==2 ) return 0;
76642       /* Fall through */
76643     case TK_ID:
76644     case TK_COLUMN:
76645     case TK_AGG_FUNCTION:
76646     case TK_AGG_COLUMN:
76647       testcase( pExpr->op==TK_ID );
76648       testcase( pExpr->op==TK_COLUMN );
76649       testcase( pExpr->op==TK_AGG_FUNCTION );
76650       testcase( pExpr->op==TK_AGG_COLUMN );
76651       pWalker->u.i = 0;
76652       return WRC_Abort;
76653     default:
76654       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
76655       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
76656       return WRC_Continue;
76657   }
76658 }
76659 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
76660   UNUSED_PARAMETER(NotUsed);
76661   pWalker->u.i = 0;
76662   return WRC_Abort;
76663 }
76664 static int exprIsConst(Expr *p, int initFlag){
76665   Walker w;
76666   w.u.i = initFlag;
76667   w.xExprCallback = exprNodeIsConstant;
76668   w.xSelectCallback = selectNodeIsConstant;
76669   sqlite3WalkExpr(&w, p);
76670   return w.u.i;
76671 }
76672
76673 /*
76674 ** Walk an expression tree.  Return 1 if the expression is constant
76675 ** and 0 if it involves variables or function calls.
76676 **
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.
76680 */
76681 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
76682   return exprIsConst(p, 1);
76683 }
76684
76685 /*
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.
76690 */
76691 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
76692   return exprIsConst(p, 3);
76693 }
76694
76695 /*
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.
76699 **
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.
76703 */
76704 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
76705   return exprIsConst(p, 2);
76706 }
76707
76708 /*
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.
76713 */
76714 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
76715   int rc = 0;
76716
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 );
76721
76722   if( p->flags & EP_IntValue ){
76723     *pValue = p->u.iValue;
76724     return 1;
76725   }
76726   switch( p->op ){
76727     case TK_UPLUS: {
76728       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
76729       break;
76730     }
76731     case TK_UMINUS: {
76732       int v;
76733       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
76734         *pValue = -v;
76735         rc = 1;
76736       }
76737       break;
76738     }
76739     default: break;
76740   }
76741   return rc;
76742 }
76743
76744 /*
76745 ** Return FALSE if there is no chance that the expression can be NULL.
76746 **
76747 ** If the expression might be NULL or if the expression is too complex
76748 ** to tell return TRUE.
76749 **
76750 ** This routine is used as an optimization, to skip OP_IsNull opcodes
76751 ** when we know that a value cannot be NULL.  Hence, a false positive
76752 ** (returning TRUE when in fact the expression can never be NULL) might
76753 ** be a small performance hit but is otherwise harmless.  On the other
76754 ** hand, a false negative (returning FALSE when the result could be NULL)
76755 ** will likely result in an incorrect answer.  So when in doubt, return
76756 ** TRUE.
76757 */
76758 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
76759   u8 op;
76760   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76761   op = p->op;
76762   if( op==TK_REGISTER ) op = p->op2;
76763   switch( op ){
76764     case TK_INTEGER:
76765     case TK_STRING:
76766     case TK_FLOAT:
76767     case TK_BLOB:
76768       return 0;
76769     default:
76770       return 1;
76771   }
76772 }
76773
76774 /*
76775 ** Generate an OP_IsNull instruction that tests register iReg and jumps
76776 ** to location iDest if the value in iReg is NULL.  The value in iReg
76777 ** was computed by pExpr.  If we can look at pExpr at compile-time and
76778 ** determine that it can never generate a NULL, then the OP_IsNull operation
76779 ** can be omitted.
76780 */
76781 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
76782   Vdbe *v,            /* The VDBE under construction */
76783   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
76784   int iReg,           /* Test the value in this register for NULL */
76785   int iDest           /* Jump here if the value is null */
76786 ){
76787   if( sqlite3ExprCanBeNull(pExpr) ){
76788     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
76789   }
76790 }
76791
76792 /*
76793 ** Return TRUE if the given expression is a constant which would be
76794 ** unchanged by OP_Affinity with the affinity given in the second
76795 ** argument.
76796 **
76797 ** This routine is used to determine if the OP_Affinity operation
76798 ** can be omitted.  When in doubt return FALSE.  A false negative
76799 ** is harmless.  A false positive, however, can result in the wrong
76800 ** answer.
76801 */
76802 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
76803   u8 op;
76804   if( aff==SQLITE_AFF_NONE ) return 1;
76805   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76806   op = p->op;
76807   if( op==TK_REGISTER ) op = p->op2;
76808   switch( op ){
76809     case TK_INTEGER: {
76810       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
76811     }
76812     case TK_FLOAT: {
76813       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
76814     }
76815     case TK_STRING: {
76816       return aff==SQLITE_AFF_TEXT;
76817     }
76818     case TK_BLOB: {
76819       return 1;
76820     }
76821     case TK_COLUMN: {
76822       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
76823       return p->iColumn<0
76824           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
76825     }
76826     default: {
76827       return 0;
76828     }
76829   }
76830 }
76831
76832 /*
76833 ** Return TRUE if the given string is a row-id column name.
76834 */
76835 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
76836   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
76837   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
76838   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
76839   return 0;
76840 }
76841
76842 /*
76843 ** Return true if we are able to the IN operator optimization on a
76844 ** query of the form
76845 **
76846 **       x IN (SELECT ...)
76847 **
76848 ** Where the SELECT... clause is as specified by the parameter to this
76849 ** routine.
76850 **
76851 ** The Select object passed in has already been preprocessed and no
76852 ** errors have been found.
76853 */
76854 #ifndef SQLITE_OMIT_SUBQUERY
76855 static int isCandidateForInOpt(Select *p){
76856   SrcList *pSrc;
76857   ExprList *pEList;
76858   Table *pTab;
76859   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
76860   if( p->pPrior ) return 0;              /* Not a compound SELECT */
76861   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
76862     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
76863     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
76864     return 0; /* No DISTINCT keyword and no aggregate functions */
76865   }
76866   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
76867   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
76868   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
76869   if( p->pWhere ) return 0;              /* Has no WHERE clause */
76870   pSrc = p->pSrc;
76871   assert( pSrc!=0 );
76872   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
76873   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
76874   pTab = pSrc->a[0].pTab;
76875   if( NEVER(pTab==0) ) return 0;
76876   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
76877   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
76878   pEList = p->pEList;
76879   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
76880   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
76881   return 1;
76882 }
76883 #endif /* SQLITE_OMIT_SUBQUERY */
76884
76885 /*
76886 ** Code an OP_Once instruction and allocate space for its flag. Return the
76887 ** address of the new instruction.
76888 */
76889 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
76890   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
76891   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
76892 }
76893
76894 /*
76895 ** This function is used by the implementation of the IN (...) operator.
76896 ** The pX parameter is the expression on the RHS of the IN operator, which
76897 ** might be either a list of expressions or a subquery.
76898 **
76899 ** The job of this routine is to find or create a b-tree object that can
76900 ** be used either to test for membership in the RHS set or to iterate through
76901 ** all members of the RHS set, skipping duplicates.
76902 **
76903 ** A cursor is opened on the b-tree object that the RHS of the IN operator
76904 ** and pX->iTable is set to the index of that cursor.
76905 **
76906 ** The returned value of this function indicates the b-tree type, as follows:
76907 **
76908 **   IN_INDEX_ROWID - The cursor was opened on a database table.
76909 **   IN_INDEX_INDEX - The cursor was opened on a database index.
76910 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
76911 **                    populated epheremal table.
76912 **
76913 ** An existing b-tree might be used if the RHS expression pX is a simple
76914 ** subquery such as:
76915 **
76916 **     SELECT <column> FROM <table>
76917 **
76918 ** If the RHS of the IN operator is a list or a more complex subquery, then
76919 ** an ephemeral table might need to be generated from the RHS and then
76920 ** pX->iTable made to point to the ephermeral table instead of an
76921 ** existing table.
76922 **
76923 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
76924 ** through the set members, skipping any duplicates. In this case an
76925 ** epheremal table must be used unless the selected <column> is guaranteed
76926 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
76927 ** has a UNIQUE constraint or UNIQUE index.
76928 **
76929 ** If the prNotFound parameter is not 0, then the b-tree will be used
76930 ** for fast set membership tests. In this case an epheremal table must
76931 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
76932 ** be found with <column> as its left-most column.
76933 **
76934 ** When the b-tree is being used for membership tests, the calling function
76935 ** needs to know whether or not the structure contains an SQL NULL
76936 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
76937 ** If there is any chance that the (...) might contain a NULL value at
76938 ** runtime, then a register is allocated and the register number written
76939 ** to *prNotFound. If there is no chance that the (...) contains a
76940 ** NULL value, then *prNotFound is left unchanged.
76941 **
76942 ** If a register is allocated and its location stored in *prNotFound, then
76943 ** its initial value is NULL.  If the (...) does not remain constant
76944 ** for the duration of the query (i.e. the SELECT within the (...)
76945 ** is a correlated subquery) then the value of the allocated register is
76946 ** reset to NULL each time the subquery is rerun. This allows the
76947 ** caller to use vdbe code equivalent to the following:
76948 **
76949 **   if( register==NULL ){
76950 **     has_null = <test if data structure contains null>
76951 **     register = 1
76952 **   }
76953 **
76954 ** in order to avoid running the <test if data structure contains null>
76955 ** test more often than is necessary.
76956 */
76957 #ifndef SQLITE_OMIT_SUBQUERY
76958 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
76959   Select *p;                            /* SELECT to the right of IN operator */
76960   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
76961   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
76962   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
76963   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
76964
76965   assert( pX->op==TK_IN );
76966
76967   /* Check to see if an existing table or index can be used to
76968   ** satisfy the query.  This is preferable to generating a new
76969   ** ephemeral table.
76970   */
76971   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
76972   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
76973     sqlite3 *db = pParse->db;              /* Database connection */
76974     Table *pTab;                           /* Table <table>. */
76975     Expr *pExpr;                           /* Expression <column> */
76976     int iCol;                              /* Index of column <column> */
76977     int iDb;                               /* Database idx for pTab */
76978
76979     assert( p );                        /* Because of isCandidateForInOpt(p) */
76980     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
76981     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
76982     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
76983     pTab = p->pSrc->a[0].pTab;
76984     pExpr = p->pEList->a[0].pExpr;
76985     iCol = pExpr->iColumn;
76986
76987     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
76988     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76989     sqlite3CodeVerifySchema(pParse, iDb);
76990     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
76991
76992     /* This function is only called from two places. In both cases the vdbe
76993     ** has already been allocated. So assume sqlite3GetVdbe() is always
76994     ** successful here.
76995     */
76996     assert(v);
76997     if( iCol<0 ){
76998       int iAddr;
76999
77000       iAddr = sqlite3CodeOnce(pParse);
77001
77002       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
77003       eType = IN_INDEX_ROWID;
77004
77005       sqlite3VdbeJumpHere(v, iAddr);
77006     }else{
77007       Index *pIdx;                         /* Iterator variable */
77008
77009       /* The collation sequence used by the comparison. If an index is to
77010       ** be used in place of a temp-table, it must be ordered according
77011       ** to this collation sequence.  */
77012       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
77013
77014       /* Check that the affinity that will be used to perform the
77015       ** comparison is the same as the affinity of the column. If
77016       ** it is not, it is not possible to use any index.
77017       */
77018       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
77019
77020       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
77021         if( (pIdx->aiColumn[0]==iCol)
77022          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
77023          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
77024         ){
77025           int iAddr;
77026           char *pKey;
77027
77028           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
77029           iAddr = sqlite3CodeOnce(pParse);
77030
77031           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
77032                                pKey,P4_KEYINFO_HANDOFF);
77033           VdbeComment((v, "%s", pIdx->zName));
77034           eType = IN_INDEX_INDEX;
77035
77036           sqlite3VdbeJumpHere(v, iAddr);
77037           if( prNotFound && !pTab->aCol[iCol].notNull ){
77038             *prNotFound = ++pParse->nMem;
77039             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
77040           }
77041         }
77042       }
77043     }
77044   }
77045
77046   if( eType==0 ){
77047     /* Could not found an existing table or index to use as the RHS b-tree.
77048     ** We will have to generate an ephemeral table to do the job.
77049     */
77050     double savedNQueryLoop = pParse->nQueryLoop;
77051     int rMayHaveNull = 0;
77052     eType = IN_INDEX_EPH;
77053     if( prNotFound ){
77054       *prNotFound = rMayHaveNull = ++pParse->nMem;
77055       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
77056     }else{
77057       testcase( pParse->nQueryLoop>(double)1 );
77058       pParse->nQueryLoop = (double)1;
77059       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
77060         eType = IN_INDEX_ROWID;
77061       }
77062     }
77063     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
77064     pParse->nQueryLoop = savedNQueryLoop;
77065   }else{
77066     pX->iTable = iTab;
77067   }
77068   return eType;
77069 }
77070 #endif
77071
77072 /*
77073 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
77074 ** or IN operators.  Examples:
77075 **
77076 **     (SELECT a FROM b)          -- subquery
77077 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
77078 **     x IN (4,5,11)              -- IN operator with list on right-hand side
77079 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
77080 **
77081 ** The pExpr parameter describes the expression that contains the IN
77082 ** operator or subquery.
77083 **
77084 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
77085 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
77086 ** to some integer key column of a table B-Tree. In this case, use an
77087 ** intkey B-Tree to store the set of IN(...) values instead of the usual
77088 ** (slower) variable length keys B-Tree.
77089 **
77090 ** If rMayHaveNull is non-zero, that means that the operation is an IN
77091 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
77092 ** Furthermore, the IN is in a WHERE clause and that we really want
77093 ** to iterate over the RHS of the IN operator in order to quickly locate
77094 ** all corresponding LHS elements.  All this routine does is initialize
77095 ** the register given by rMayHaveNull to NULL.  Calling routines will take
77096 ** care of changing this register value to non-NULL if the RHS is NULL-free.
77097 **
77098 ** If rMayHaveNull is zero, that means that the subquery is being used
77099 ** for membership testing only.  There is no need to initialize any
77100 ** registers to indicate the presense or absence of NULLs on the RHS.
77101 **
77102 ** For a SELECT or EXISTS operator, return the register that holds the
77103 ** result.  For IN operators or if an error occurs, the return value is 0.
77104 */
77105 #ifndef SQLITE_OMIT_SUBQUERY
77106 SQLITE_PRIVATE int sqlite3CodeSubselect(
77107   Parse *pParse,          /* Parsing context */
77108   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
77109   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
77110   int isRowid             /* If true, LHS of IN operator is a rowid */
77111 ){
77112   int testAddr = -1;                      /* One-time test address */
77113   int rReg = 0;                           /* Register storing resulting */
77114   Vdbe *v = sqlite3GetVdbe(pParse);
77115   if( NEVER(v==0) ) return 0;
77116   sqlite3ExprCachePush(pParse);
77117
77118   /* This code must be run in its entirety every time it is encountered
77119   ** if any of the following is true:
77120   **
77121   **    *  The right-hand side is a correlated subquery
77122   **    *  The right-hand side is an expression list containing variables
77123   **    *  We are inside a trigger
77124   **
77125   ** If all of the above are false, then we can run this code just once
77126   ** save the results, and reuse the same result on subsequent invocations.
77127   */
77128   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
77129     testAddr = sqlite3CodeOnce(pParse);
77130   }
77131
77132 #ifndef SQLITE_OMIT_EXPLAIN
77133   if( pParse->explain==2 ){
77134     char *zMsg = sqlite3MPrintf(
77135         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
77136         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
77137     );
77138     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
77139   }
77140 #endif
77141
77142   switch( pExpr->op ){
77143     case TK_IN: {
77144       char affinity;              /* Affinity of the LHS of the IN */
77145       KeyInfo keyInfo;            /* Keyinfo for the generated table */
77146       static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
77147       int addr;                   /* Address of OP_OpenEphemeral instruction */
77148       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
77149
77150       if( rMayHaveNull ){
77151         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
77152       }
77153
77154       affinity = sqlite3ExprAffinity(pLeft);
77155
77156       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
77157       ** expression it is handled the same way.  An ephemeral table is
77158       ** filled with single-field index keys representing the results
77159       ** from the SELECT or the <exprlist>.
77160       **
77161       ** If the 'x' expression is a column value, or the SELECT...
77162       ** statement returns a column value, then the affinity of that
77163       ** column is used to build the index keys. If both 'x' and the
77164       ** SELECT... statement are columns, then numeric affinity is used
77165       ** if either column has NUMERIC or INTEGER affinity. If neither
77166       ** 'x' nor the SELECT... statement are columns, then numeric affinity
77167       ** is used.
77168       */
77169       pExpr->iTable = pParse->nTab++;
77170       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
77171       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
77172       memset(&keyInfo, 0, sizeof(keyInfo));
77173       keyInfo.nField = 1;
77174       keyInfo.aSortOrder = &sortOrder;
77175
77176       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77177         /* Case 1:     expr IN (SELECT ...)
77178         **
77179         ** Generate code to write the results of the select into the temporary
77180         ** table allocated and opened above.
77181         */
77182         SelectDest dest;
77183         ExprList *pEList;
77184
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         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
77191           return 0;
77192         }
77193         pEList = pExpr->x.pSelect->pEList;
77194         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
77195           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
77196               pEList->a[0].pExpr);
77197         }
77198       }else if( ALWAYS(pExpr->x.pList!=0) ){
77199         /* Case 2:     expr IN (exprlist)
77200         **
77201         ** For each expression, build an index key from the evaluation and
77202         ** store it in the temporary table. If <expr> is a column, then use
77203         ** that columns affinity when building index keys. If <expr> is not
77204         ** a column, use numeric affinity.
77205         */
77206         int i;
77207         ExprList *pList = pExpr->x.pList;
77208         struct ExprList_item *pItem;
77209         int r1, r2, r3;
77210
77211         if( !affinity ){
77212           affinity = SQLITE_AFF_NONE;
77213         }
77214         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
77215         keyInfo.aSortOrder = &sortOrder;
77216
77217         /* Loop through each expression in <exprlist>. */
77218         r1 = sqlite3GetTempReg(pParse);
77219         r2 = sqlite3GetTempReg(pParse);
77220         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
77221         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
77222           Expr *pE2 = pItem->pExpr;
77223           int iValToIns;
77224
77225           /* If the expression is not constant then we will need to
77226           ** disable the test that was generated above that makes sure
77227           ** this code only executes once.  Because for a non-constant
77228           ** expression we need to rerun this code each time.
77229           */
77230           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
77231             sqlite3VdbeChangeToNoop(v, testAddr);
77232             testAddr = -1;
77233           }
77234
77235           /* Evaluate the expression and insert it into the temp table */
77236           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
77237             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
77238           }else{
77239             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
77240             if( isRowid ){
77241               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
77242                                 sqlite3VdbeCurrentAddr(v)+2);
77243               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
77244             }else{
77245               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
77246               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
77247               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
77248             }
77249           }
77250         }
77251         sqlite3ReleaseTempReg(pParse, r1);
77252         sqlite3ReleaseTempReg(pParse, r2);
77253       }
77254       if( !isRowid ){
77255         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
77256       }
77257       break;
77258     }
77259
77260     case TK_EXISTS:
77261     case TK_SELECT:
77262     default: {
77263       /* If this has to be a scalar SELECT.  Generate code to put the
77264       ** value of this select in a memory cell and record the number
77265       ** of the memory cell in iColumn.  If this is an EXISTS, write
77266       ** an integer 0 (not exists) or 1 (exists) into a memory cell
77267       ** and record that memory cell in iColumn.
77268       */
77269       Select *pSel;                         /* SELECT statement to encode */
77270       SelectDest dest;                      /* How to deal with SELECt result */
77271
77272       testcase( pExpr->op==TK_EXISTS );
77273       testcase( pExpr->op==TK_SELECT );
77274       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
77275
77276       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
77277       pSel = pExpr->x.pSelect;
77278       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
77279       if( pExpr->op==TK_SELECT ){
77280         dest.eDest = SRT_Mem;
77281         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
77282         VdbeComment((v, "Init subquery result"));
77283       }else{
77284         dest.eDest = SRT_Exists;
77285         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
77286         VdbeComment((v, "Init EXISTS result"));
77287       }
77288       sqlite3ExprDelete(pParse->db, pSel->pLimit);
77289       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
77290                                   &sqlite3IntTokens[1]);
77291       pSel->iLimit = 0;
77292       if( sqlite3Select(pParse, pSel, &dest) ){
77293         return 0;
77294       }
77295       rReg = dest.iSDParm;
77296       ExprSetIrreducible(pExpr);
77297       break;
77298     }
77299   }
77300
77301   if( testAddr>=0 ){
77302     sqlite3VdbeJumpHere(v, testAddr);
77303   }
77304   sqlite3ExprCachePop(pParse, 1);
77305
77306   return rReg;
77307 }
77308 #endif /* SQLITE_OMIT_SUBQUERY */
77309
77310 #ifndef SQLITE_OMIT_SUBQUERY
77311 /*
77312 ** Generate code for an IN expression.
77313 **
77314 **      x IN (SELECT ...)
77315 **      x IN (value, value, ...)
77316 **
77317 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
77318 ** is an array of zero or more values.  The expression is true if the LHS is
77319 ** contained within the RHS.  The value of the expression is unknown (NULL)
77320 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
77321 ** RHS contains one or more NULL values.
77322 **
77323 ** This routine generates code will jump to destIfFalse if the LHS is not
77324 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
77325 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
77326 ** within the RHS then fall through.
77327 */
77328 static void sqlite3ExprCodeIN(
77329   Parse *pParse,        /* Parsing and code generating context */
77330   Expr *pExpr,          /* The IN expression */
77331   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
77332   int destIfNull        /* Jump here if the results are unknown due to NULLs */
77333 ){
77334   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
77335   char affinity;        /* Comparison affinity to use */
77336   int eType;            /* Type of the RHS */
77337   int r1;               /* Temporary use register */
77338   Vdbe *v;              /* Statement under construction */
77339
77340   /* Compute the RHS.   After this step, the table with cursor
77341   ** pExpr->iTable will contains the values that make up the RHS.
77342   */
77343   v = pParse->pVdbe;
77344   assert( v!=0 );       /* OOM detected prior to this routine */
77345   VdbeNoopComment((v, "begin IN expr"));
77346   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
77347
77348   /* Figure out the affinity to use to create a key from the results
77349   ** of the expression. affinityStr stores a static string suitable for
77350   ** P4 of OP_MakeRecord.
77351   */
77352   affinity = comparisonAffinity(pExpr);
77353
77354   /* Code the LHS, the <expr> from "<expr> IN (...)".
77355   */
77356   sqlite3ExprCachePush(pParse);
77357   r1 = sqlite3GetTempReg(pParse);
77358   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
77359
77360   /* If the LHS is NULL, then the result is either false or NULL depending
77361   ** on whether the RHS is empty or not, respectively.
77362   */
77363   if( destIfNull==destIfFalse ){
77364     /* Shortcut for the common case where the false and NULL outcomes are
77365     ** the same. */
77366     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
77367   }else{
77368     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
77369     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
77370     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
77371     sqlite3VdbeJumpHere(v, addr1);
77372   }
77373
77374   if( eType==IN_INDEX_ROWID ){
77375     /* In this case, the RHS is the ROWID of table b-tree
77376     */
77377     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
77378     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
77379   }else{
77380     /* In this case, the RHS is an index b-tree.
77381     */
77382     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
77383
77384     /* If the set membership test fails, then the result of the
77385     ** "x IN (...)" expression must be either 0 or NULL. If the set
77386     ** contains no NULL values, then the result is 0. If the set
77387     ** contains one or more NULL values, then the result of the
77388     ** expression is also NULL.
77389     */
77390     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
77391       /* This branch runs if it is known at compile time that the RHS
77392       ** cannot contain NULL values. This happens as the result
77393       ** of a "NOT NULL" constraint in the database schema.
77394       **
77395       ** Also run this branch if NULL is equivalent to FALSE
77396       ** for this particular IN operator.
77397       */
77398       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
77399
77400     }else{
77401       /* In this branch, the RHS of the IN might contain a NULL and
77402       ** the presence of a NULL on the RHS makes a difference in the
77403       ** outcome.
77404       */
77405       int j1, j2, j3;
77406
77407       /* First check to see if the LHS is contained in the RHS.  If so,
77408       ** then the presence of NULLs in the RHS does not matter, so jump
77409       ** over all of the code that follows.
77410       */
77411       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
77412
77413       /* Here we begin generating code that runs if the LHS is not
77414       ** contained within the RHS.  Generate additional code that
77415       ** tests the RHS for NULLs.  If the RHS contains a NULL then
77416       ** jump to destIfNull.  If there are no NULLs in the RHS then
77417       ** jump to destIfFalse.
77418       */
77419       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
77420       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
77421       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
77422       sqlite3VdbeJumpHere(v, j3);
77423       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
77424       sqlite3VdbeJumpHere(v, j2);
77425
77426       /* Jump to the appropriate target depending on whether or not
77427       ** the RHS contains a NULL
77428       */
77429       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
77430       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
77431
77432       /* The OP_Found at the top of this branch jumps here when true,
77433       ** causing the overall IN expression evaluation to fall through.
77434       */
77435       sqlite3VdbeJumpHere(v, j1);
77436     }
77437   }
77438   sqlite3ReleaseTempReg(pParse, r1);
77439   sqlite3ExprCachePop(pParse, 1);
77440   VdbeComment((v, "end IN expr"));
77441 }
77442 #endif /* SQLITE_OMIT_SUBQUERY */
77443
77444 /*
77445 ** Duplicate an 8-byte value
77446 */
77447 static char *dup8bytes(Vdbe *v, const char *in){
77448   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
77449   if( out ){
77450     memcpy(out, in, 8);
77451   }
77452   return out;
77453 }
77454
77455 #ifndef SQLITE_OMIT_FLOATING_POINT
77456 /*
77457 ** Generate an instruction that will put the floating point
77458 ** value described by z[0..n-1] into register iMem.
77459 **
77460 ** The z[] string will probably not be zero-terminated.  But the
77461 ** z[n] character is guaranteed to be something that does not look
77462 ** like the continuation of the number.
77463 */
77464 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
77465   if( ALWAYS(z!=0) ){
77466     double value;
77467     char *zV;
77468     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77469     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
77470     if( negateFlag ) value = -value;
77471     zV = dup8bytes(v, (char*)&value);
77472     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
77473   }
77474 }
77475 #endif
77476
77477
77478 /*
77479 ** Generate an instruction that will put the integer describe by
77480 ** text z[0..n-1] into register iMem.
77481 **
77482 ** Expr.u.zToken is always UTF8 and zero-terminated.
77483 */
77484 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
77485   Vdbe *v = pParse->pVdbe;
77486   if( pExpr->flags & EP_IntValue ){
77487     int i = pExpr->u.iValue;
77488     assert( i>=0 );
77489     if( negFlag ) i = -i;
77490     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
77491   }else{
77492     int c;
77493     i64 value;
77494     const char *z = pExpr->u.zToken;
77495     assert( z!=0 );
77496     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77497     if( c==0 || (c==2 && negFlag) ){
77498       char *zV;
77499       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
77500       zV = dup8bytes(v, (char*)&value);
77501       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
77502     }else{
77503 #ifdef SQLITE_OMIT_FLOATING_POINT
77504       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
77505 #else
77506       codeReal(v, z, negFlag, iMem);
77507 #endif
77508     }
77509   }
77510 }
77511
77512 /*
77513 ** Clear a cache entry.
77514 */
77515 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
77516   if( p->tempReg ){
77517     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
77518       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
77519     }
77520     p->tempReg = 0;
77521   }
77522 }
77523
77524
77525 /*
77526 ** Record in the column cache that a particular column from a
77527 ** particular table is stored in a particular register.
77528 */
77529 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
77530   int i;
77531   int minLru;
77532   int idxLru;
77533   struct yColCache *p;
77534
77535   assert( iReg>0 );  /* Register numbers are always positive */
77536   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
77537
77538   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
77539   ** for testing only - to verify that SQLite always gets the same answer
77540   ** with and without the column cache.
77541   */
77542   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
77543
77544   /* First replace any existing entry.
77545   **
77546   ** Actually, the way the column cache is currently used, we are guaranteed
77547   ** that the object will never already be in cache.  Verify this guarantee.
77548   */
77549 #ifndef NDEBUG
77550   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77551     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
77552   }
77553 #endif
77554
77555   /* Find an empty slot and replace it */
77556   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77557     if( p->iReg==0 ){
77558       p->iLevel = pParse->iCacheLevel;
77559       p->iTable = iTab;
77560       p->iColumn = iCol;
77561       p->iReg = iReg;
77562       p->tempReg = 0;
77563       p->lru = pParse->iCacheCnt++;
77564       return;
77565     }
77566   }
77567
77568   /* Replace the last recently used */
77569   minLru = 0x7fffffff;
77570   idxLru = -1;
77571   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77572     if( p->lru<minLru ){
77573       idxLru = i;
77574       minLru = p->lru;
77575     }
77576   }
77577   if( ALWAYS(idxLru>=0) ){
77578     p = &pParse->aColCache[idxLru];
77579     p->iLevel = pParse->iCacheLevel;
77580     p->iTable = iTab;
77581     p->iColumn = iCol;
77582     p->iReg = iReg;
77583     p->tempReg = 0;
77584     p->lru = pParse->iCacheCnt++;
77585     return;
77586   }
77587 }
77588
77589 /*
77590 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
77591 ** Purge the range of registers from the column cache.
77592 */
77593 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
77594   int i;
77595   int iLast = iReg + nReg - 1;
77596   struct yColCache *p;
77597   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77598     int r = p->iReg;
77599     if( r>=iReg && r<=iLast ){
77600       cacheEntryClear(pParse, p);
77601       p->iReg = 0;
77602     }
77603   }
77604 }
77605
77606 /*
77607 ** Remember the current column cache context.  Any new entries added
77608 ** added to the column cache after this call are removed when the
77609 ** corresponding pop occurs.
77610 */
77611 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
77612   pParse->iCacheLevel++;
77613 }
77614
77615 /*
77616 ** Remove from the column cache any entries that were added since the
77617 ** the previous N Push operations.  In other words, restore the cache
77618 ** to the state it was in N Pushes ago.
77619 */
77620 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
77621   int i;
77622   struct yColCache *p;
77623   assert( N>0 );
77624   assert( pParse->iCacheLevel>=N );
77625   pParse->iCacheLevel -= N;
77626   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77627     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
77628       cacheEntryClear(pParse, p);
77629       p->iReg = 0;
77630     }
77631   }
77632 }
77633
77634 /*
77635 ** When a cached column is reused, make sure that its register is
77636 ** no longer available as a temp register.  ticket #3879:  that same
77637 ** register might be in the cache in multiple places, so be sure to
77638 ** get them all.
77639 */
77640 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
77641   int i;
77642   struct yColCache *p;
77643   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77644     if( p->iReg==iReg ){
77645       p->tempReg = 0;
77646     }
77647   }
77648 }
77649
77650 /*
77651 ** Generate code to extract the value of the iCol-th column of a table.
77652 */
77653 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
77654   Vdbe *v,        /* The VDBE under construction */
77655   Table *pTab,    /* The table containing the value */
77656   int iTabCur,    /* The cursor for this table */
77657   int iCol,       /* Index of the column to extract */
77658   int regOut      /* Extract the valud into this register */
77659 ){
77660   if( iCol<0 || iCol==pTab->iPKey ){
77661     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
77662   }else{
77663     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
77664     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
77665   }
77666   if( iCol>=0 ){
77667     sqlite3ColumnDefault(v, pTab, iCol, regOut);
77668   }
77669 }
77670
77671 /*
77672 ** Generate code that will extract the iColumn-th column from
77673 ** table pTab and store the column value in a register.  An effort
77674 ** is made to store the column value in register iReg, but this is
77675 ** not guaranteed.  The location of the column value is returned.
77676 **
77677 ** There must be an open cursor to pTab in iTable when this routine
77678 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
77679 */
77680 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
77681   Parse *pParse,   /* Parsing and code generating context */
77682   Table *pTab,     /* Description of the table we are reading from */
77683   int iColumn,     /* Index of the table column */
77684   int iTable,      /* The cursor pointing to the table */
77685   int iReg,        /* Store results here */
77686   u8 p5            /* P5 value for OP_Column */
77687 ){
77688   Vdbe *v = pParse->pVdbe;
77689   int i;
77690   struct yColCache *p;
77691
77692   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77693     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
77694       p->lru = pParse->iCacheCnt++;
77695       sqlite3ExprCachePinRegister(pParse, p->iReg);
77696       return p->iReg;
77697     }
77698   }
77699   assert( v!=0 );
77700   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
77701   if( p5 ){
77702     sqlite3VdbeChangeP5(v, p5);
77703   }else{
77704     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
77705   }
77706   return iReg;
77707 }
77708
77709 /*
77710 ** Clear all column cache entries.
77711 */
77712 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
77713   int i;
77714   struct yColCache *p;
77715
77716   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77717     if( p->iReg ){
77718       cacheEntryClear(pParse, p);
77719       p->iReg = 0;
77720     }
77721   }
77722 }
77723
77724 /*
77725 ** Record the fact that an affinity change has occurred on iCount
77726 ** registers starting with iStart.
77727 */
77728 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
77729   sqlite3ExprCacheRemove(pParse, iStart, iCount);
77730 }
77731
77732 /*
77733 ** Generate code to move content from registers iFrom...iFrom+nReg-1
77734 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
77735 */
77736 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
77737   int i;
77738   struct yColCache *p;
77739   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
77740   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
77741   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77742     int x = p->iReg;
77743     if( x>=iFrom && x<iFrom+nReg ){
77744       p->iReg += iTo-iFrom;
77745     }
77746   }
77747 }
77748
77749 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
77750 /*
77751 ** Return true if any register in the range iFrom..iTo (inclusive)
77752 ** is used as part of the column cache.
77753 **
77754 ** This routine is used within assert() and testcase() macros only
77755 ** and does not appear in a normal build.
77756 */
77757 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
77758   int i;
77759   struct yColCache *p;
77760   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77761     int r = p->iReg;
77762     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
77763   }
77764   return 0;
77765 }
77766 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
77767
77768 /*
77769 ** Generate code into the current Vdbe to evaluate the given
77770 ** expression.  Attempt to store the results in register "target".
77771 ** Return the register where results are stored.
77772 **
77773 ** With this routine, there is no guarantee that results will
77774 ** be stored in target.  The result might be stored in some other
77775 ** register if it is convenient to do so.  The calling function
77776 ** must check the return code and move the results to the desired
77777 ** register.
77778 */
77779 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
77780   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
77781   int op;                   /* The opcode being coded */
77782   int inReg = target;       /* Results stored in register inReg */
77783   int regFree1 = 0;         /* If non-zero free this temporary register */
77784   int regFree2 = 0;         /* If non-zero free this temporary register */
77785   int r1, r2, r3, r4;       /* Various register numbers */
77786   sqlite3 *db = pParse->db; /* The database connection */
77787
77788   assert( target>0 && target<=pParse->nMem );
77789   if( v==0 ){
77790     assert( pParse->db->mallocFailed );
77791     return 0;
77792   }
77793
77794   if( pExpr==0 ){
77795     op = TK_NULL;
77796   }else{
77797     op = pExpr->op;
77798   }
77799   switch( op ){
77800     case TK_AGG_COLUMN: {
77801       AggInfo *pAggInfo = pExpr->pAggInfo;
77802       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
77803       if( !pAggInfo->directMode ){
77804         assert( pCol->iMem>0 );
77805         inReg = pCol->iMem;
77806         break;
77807       }else if( pAggInfo->useSortingIdx ){
77808         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
77809                               pCol->iSorterColumn, target);
77810         break;
77811       }
77812       /* Otherwise, fall thru into the TK_COLUMN case */
77813     }
77814     case TK_COLUMN: {
77815       if( pExpr->iTable<0 ){
77816         /* This only happens when coding check constraints */
77817         assert( pParse->ckBase>0 );
77818         inReg = pExpr->iColumn + pParse->ckBase;
77819       }else{
77820         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
77821                                  pExpr->iColumn, pExpr->iTable, target,
77822                                  pExpr->op2);
77823       }
77824       break;
77825     }
77826     case TK_INTEGER: {
77827       codeInteger(pParse, pExpr, 0, target);
77828       break;
77829     }
77830 #ifndef SQLITE_OMIT_FLOATING_POINT
77831     case TK_FLOAT: {
77832       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77833       codeReal(v, pExpr->u.zToken, 0, target);
77834       break;
77835     }
77836 #endif
77837     case TK_STRING: {
77838       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77839       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
77840       break;
77841     }
77842     case TK_NULL: {
77843       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77844       break;
77845     }
77846 #ifndef SQLITE_OMIT_BLOB_LITERAL
77847     case TK_BLOB: {
77848       int n;
77849       const char *z;
77850       char *zBlob;
77851       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77852       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
77853       assert( pExpr->u.zToken[1]=='\'' );
77854       z = &pExpr->u.zToken[2];
77855       n = sqlite3Strlen30(z) - 1;
77856       assert( z[n]=='\'' );
77857       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
77858       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
77859       break;
77860     }
77861 #endif
77862     case TK_VARIABLE: {
77863       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77864       assert( pExpr->u.zToken!=0 );
77865       assert( pExpr->u.zToken[0]!=0 );
77866       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
77867       if( pExpr->u.zToken[1]!=0 ){
77868         assert( pExpr->u.zToken[0]=='?'
77869              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
77870         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
77871       }
77872       break;
77873     }
77874     case TK_REGISTER: {
77875       inReg = pExpr->iTable;
77876       break;
77877     }
77878     case TK_AS: {
77879       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77880       break;
77881     }
77882 #ifndef SQLITE_OMIT_CAST
77883     case TK_CAST: {
77884       /* Expressions of the form:   CAST(pLeft AS token) */
77885       int aff, to_op;
77886       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77887       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77888       aff = sqlite3AffinityType(pExpr->u.zToken);
77889       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
77890       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
77891       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
77892       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
77893       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
77894       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
77895       testcase( to_op==OP_ToText );
77896       testcase( to_op==OP_ToBlob );
77897       testcase( to_op==OP_ToNumeric );
77898       testcase( to_op==OP_ToInt );
77899       testcase( to_op==OP_ToReal );
77900       if( inReg!=target ){
77901         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
77902         inReg = target;
77903       }
77904       sqlite3VdbeAddOp1(v, to_op, inReg);
77905       testcase( usedAsColumnCache(pParse, inReg, inReg) );
77906       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
77907       break;
77908     }
77909 #endif /* SQLITE_OMIT_CAST */
77910     case TK_LT:
77911     case TK_LE:
77912     case TK_GT:
77913     case TK_GE:
77914     case TK_NE:
77915     case TK_EQ: {
77916       assert( TK_LT==OP_Lt );
77917       assert( TK_LE==OP_Le );
77918       assert( TK_GT==OP_Gt );
77919       assert( TK_GE==OP_Ge );
77920       assert( TK_EQ==OP_Eq );
77921       assert( TK_NE==OP_Ne );
77922       testcase( op==TK_LT );
77923       testcase( op==TK_LE );
77924       testcase( op==TK_GT );
77925       testcase( op==TK_GE );
77926       testcase( op==TK_EQ );
77927       testcase( op==TK_NE );
77928       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77929       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77930       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77931                   r1, r2, inReg, SQLITE_STOREP2);
77932       testcase( regFree1==0 );
77933       testcase( regFree2==0 );
77934       break;
77935     }
77936     case TK_IS:
77937     case TK_ISNOT: {
77938       testcase( op==TK_IS );
77939       testcase( op==TK_ISNOT );
77940       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77941       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77942       op = (op==TK_IS) ? TK_EQ : TK_NE;
77943       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77944                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
77945       testcase( regFree1==0 );
77946       testcase( regFree2==0 );
77947       break;
77948     }
77949     case TK_AND:
77950     case TK_OR:
77951     case TK_PLUS:
77952     case TK_STAR:
77953     case TK_MINUS:
77954     case TK_REM:
77955     case TK_BITAND:
77956     case TK_BITOR:
77957     case TK_SLASH:
77958     case TK_LSHIFT:
77959     case TK_RSHIFT:
77960     case TK_CONCAT: {
77961       assert( TK_AND==OP_And );
77962       assert( TK_OR==OP_Or );
77963       assert( TK_PLUS==OP_Add );
77964       assert( TK_MINUS==OP_Subtract );
77965       assert( TK_REM==OP_Remainder );
77966       assert( TK_BITAND==OP_BitAnd );
77967       assert( TK_BITOR==OP_BitOr );
77968       assert( TK_SLASH==OP_Divide );
77969       assert( TK_LSHIFT==OP_ShiftLeft );
77970       assert( TK_RSHIFT==OP_ShiftRight );
77971       assert( TK_CONCAT==OP_Concat );
77972       testcase( op==TK_AND );
77973       testcase( op==TK_OR );
77974       testcase( op==TK_PLUS );
77975       testcase( op==TK_MINUS );
77976       testcase( op==TK_REM );
77977       testcase( op==TK_BITAND );
77978       testcase( op==TK_BITOR );
77979       testcase( op==TK_SLASH );
77980       testcase( op==TK_LSHIFT );
77981       testcase( op==TK_RSHIFT );
77982       testcase( op==TK_CONCAT );
77983       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77984       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77985       sqlite3VdbeAddOp3(v, op, r2, r1, target);
77986       testcase( regFree1==0 );
77987       testcase( regFree2==0 );
77988       break;
77989     }
77990     case TK_UMINUS: {
77991       Expr *pLeft = pExpr->pLeft;
77992       assert( pLeft );
77993       if( pLeft->op==TK_INTEGER ){
77994         codeInteger(pParse, pLeft, 1, target);
77995 #ifndef SQLITE_OMIT_FLOATING_POINT
77996       }else if( pLeft->op==TK_FLOAT ){
77997         assert( !ExprHasProperty(pExpr, EP_IntValue) );
77998         codeReal(v, pLeft->u.zToken, 1, target);
77999 #endif
78000       }else{
78001         regFree1 = r1 = sqlite3GetTempReg(pParse);
78002         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
78003         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
78004         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
78005         testcase( regFree2==0 );
78006       }
78007       inReg = target;
78008       break;
78009     }
78010     case TK_BITNOT:
78011     case TK_NOT: {
78012       assert( TK_BITNOT==OP_BitNot );
78013       assert( TK_NOT==OP_Not );
78014       testcase( op==TK_BITNOT );
78015       testcase( op==TK_NOT );
78016       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78017       testcase( regFree1==0 );
78018       inReg = target;
78019       sqlite3VdbeAddOp2(v, op, r1, inReg);
78020       break;
78021     }
78022     case TK_ISNULL:
78023     case TK_NOTNULL: {
78024       int addr;
78025       assert( TK_ISNULL==OP_IsNull );
78026       assert( TK_NOTNULL==OP_NotNull );
78027       testcase( op==TK_ISNULL );
78028       testcase( op==TK_NOTNULL );
78029       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
78030       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78031       testcase( regFree1==0 );
78032       addr = sqlite3VdbeAddOp1(v, op, r1);
78033       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
78034       sqlite3VdbeJumpHere(v, addr);
78035       break;
78036     }
78037     case TK_AGG_FUNCTION: {
78038       AggInfo *pInfo = pExpr->pAggInfo;
78039       if( pInfo==0 ){
78040         assert( !ExprHasProperty(pExpr, EP_IntValue) );
78041         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
78042       }else{
78043         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
78044       }
78045       break;
78046     }
78047     case TK_CONST_FUNC:
78048     case TK_FUNCTION: {
78049       ExprList *pFarg;       /* List of function arguments */
78050       int nFarg;             /* Number of function arguments */
78051       FuncDef *pDef;         /* The function definition object */
78052       int nId;               /* Length of the function name in bytes */
78053       const char *zId;       /* The function name */
78054       int constMask = 0;     /* Mask of function arguments that are constant */
78055       int i;                 /* Loop counter */
78056       u8 enc = ENC(db);      /* The text encoding used by this database */
78057       CollSeq *pColl = 0;    /* A collating sequence */
78058
78059       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78060       testcase( op==TK_CONST_FUNC );
78061       testcase( op==TK_FUNCTION );
78062       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
78063         pFarg = 0;
78064       }else{
78065         pFarg = pExpr->x.pList;
78066       }
78067       nFarg = pFarg ? pFarg->nExpr : 0;
78068       assert( !ExprHasProperty(pExpr, EP_IntValue) );
78069       zId = pExpr->u.zToken;
78070       nId = sqlite3Strlen30(zId);
78071       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
78072       if( pDef==0 ){
78073         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
78074         break;
78075       }
78076
78077       /* Attempt a direct implementation of the built-in COALESCE() and
78078       ** IFNULL() functions.  This avoids unnecessary evalation of
78079       ** arguments past the first non-NULL argument.
78080       */
78081       if( pDef->flags & SQLITE_FUNC_COALESCE ){
78082         int endCoalesce = sqlite3VdbeMakeLabel(v);
78083         assert( nFarg>=2 );
78084         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
78085         for(i=1; i<nFarg; i++){
78086           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
78087           sqlite3ExprCacheRemove(pParse, target, 1);
78088           sqlite3ExprCachePush(pParse);
78089           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
78090           sqlite3ExprCachePop(pParse, 1);
78091         }
78092         sqlite3VdbeResolveLabel(v, endCoalesce);
78093         break;
78094       }
78095
78096
78097       if( pFarg ){
78098         r1 = sqlite3GetTempRange(pParse, nFarg);
78099
78100         /* For length() and typeof() functions with a column argument,
78101         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
78102         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
78103         ** loading.
78104         */
78105         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
78106           u8 exprOp;
78107           assert( nFarg==1 );
78108           assert( pFarg->a[0].pExpr!=0 );
78109           exprOp = pFarg->a[0].pExpr->op;
78110           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
78111             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
78112             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
78113             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
78114             pFarg->a[0].pExpr->op2 = pDef->flags;
78115           }
78116         }
78117
78118         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
78119         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
78120         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
78121       }else{
78122         r1 = 0;
78123       }
78124 #ifndef SQLITE_OMIT_VIRTUALTABLE
78125       /* Possibly overload the function if the first argument is
78126       ** a virtual table column.
78127       **
78128       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
78129       ** second argument, not the first, as the argument to test to
78130       ** see if it is a column in a virtual table.  This is done because
78131       ** the left operand of infix functions (the operand we want to
78132       ** control overloading) ends up as the second argument to the
78133       ** function.  The expression "A glob B" is equivalent to
78134       ** "glob(B,A).  We want to use the A in "A glob B" to test
78135       ** for function overloading.  But we use the B term in "glob(B,A)".
78136       */
78137       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
78138         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
78139       }else if( nFarg>0 ){
78140         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
78141       }
78142 #endif
78143       for(i=0; i<nFarg; i++){
78144         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
78145           constMask |= (1<<i);
78146         }
78147         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
78148           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
78149         }
78150       }
78151       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
78152         if( !pColl ) pColl = db->pDfltColl;
78153         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
78154       }
78155       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
78156                         (char*)pDef, P4_FUNCDEF);
78157       sqlite3VdbeChangeP5(v, (u8)nFarg);
78158       if( nFarg ){
78159         sqlite3ReleaseTempRange(pParse, r1, nFarg);
78160       }
78161       break;
78162     }
78163 #ifndef SQLITE_OMIT_SUBQUERY
78164     case TK_EXISTS:
78165     case TK_SELECT: {
78166       testcase( op==TK_EXISTS );
78167       testcase( op==TK_SELECT );
78168       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
78169       break;
78170     }
78171     case TK_IN: {
78172       int destIfFalse = sqlite3VdbeMakeLabel(v);
78173       int destIfNull = sqlite3VdbeMakeLabel(v);
78174       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78175       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
78176       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
78177       sqlite3VdbeResolveLabel(v, destIfFalse);
78178       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
78179       sqlite3VdbeResolveLabel(v, destIfNull);
78180       break;
78181     }
78182 #endif /* SQLITE_OMIT_SUBQUERY */
78183
78184
78185     /*
78186     **    x BETWEEN y AND z
78187     **
78188     ** This is equivalent to
78189     **
78190     **    x>=y AND x<=z
78191     **
78192     ** X is stored in pExpr->pLeft.
78193     ** Y is stored in pExpr->pList->a[0].pExpr.
78194     ** Z is stored in pExpr->pList->a[1].pExpr.
78195     */
78196     case TK_BETWEEN: {
78197       Expr *pLeft = pExpr->pLeft;
78198       struct ExprList_item *pLItem = pExpr->x.pList->a;
78199       Expr *pRight = pLItem->pExpr;
78200
78201       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
78202       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
78203       testcase( regFree1==0 );
78204       testcase( regFree2==0 );
78205       r3 = sqlite3GetTempReg(pParse);
78206       r4 = sqlite3GetTempReg(pParse);
78207       codeCompare(pParse, pLeft, pRight, OP_Ge,
78208                   r1, r2, r3, SQLITE_STOREP2);
78209       pLItem++;
78210       pRight = pLItem->pExpr;
78211       sqlite3ReleaseTempReg(pParse, regFree2);
78212       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
78213       testcase( regFree2==0 );
78214       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
78215       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
78216       sqlite3ReleaseTempReg(pParse, r3);
78217       sqlite3ReleaseTempReg(pParse, r4);
78218       break;
78219     }
78220     case TK_COLLATE:
78221     case TK_UPLUS: {
78222       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
78223       break;
78224     }
78225
78226     case TK_TRIGGER: {
78227       /* If the opcode is TK_TRIGGER, then the expression is a reference
78228       ** to a column in the new.* or old.* pseudo-tables available to
78229       ** trigger programs. In this case Expr.iTable is set to 1 for the
78230       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78231       ** is set to the column of the pseudo-table to read, or to -1 to
78232       ** read the rowid field.
78233       **
78234       ** The expression is implemented using an OP_Param opcode. The p1
78235       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
78236       ** to reference another column of the old.* pseudo-table, where
78237       ** i is the index of the column. For a new.rowid reference, p1 is
78238       ** set to (n+1), where n is the number of columns in each pseudo-table.
78239       ** For a reference to any other column in the new.* pseudo-table, p1
78240       ** is set to (n+2+i), where n and i are as defined previously. For
78241       ** example, if the table on which triggers are being fired is
78242       ** declared as:
78243       **
78244       **   CREATE TABLE t1(a, b);
78245       **
78246       ** Then p1 is interpreted as follows:
78247       **
78248       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
78249       **   p1==1   ->    old.a         p1==4   ->    new.a
78250       **   p1==2   ->    old.b         p1==5   ->    new.b
78251       */
78252       Table *pTab = pExpr->pTab;
78253       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
78254
78255       assert( pExpr->iTable==0 || pExpr->iTable==1 );
78256       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
78257       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
78258       assert( p1>=0 && p1<(pTab->nCol*2+2) );
78259
78260       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
78261       VdbeComment((v, "%s.%s -> $%d",
78262         (pExpr->iTable ? "new" : "old"),
78263         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
78264         target
78265       ));
78266
78267 #ifndef SQLITE_OMIT_FLOATING_POINT
78268       /* If the column has REAL affinity, it may currently be stored as an
78269       ** integer. Use OP_RealAffinity to make sure it is really real.  */
78270       if( pExpr->iColumn>=0
78271        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
78272       ){
78273         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
78274       }
78275 #endif
78276       break;
78277     }
78278
78279
78280     /*
78281     ** Form A:
78282     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78283     **
78284     ** Form B:
78285     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78286     **
78287     ** Form A is can be transformed into the equivalent form B as follows:
78288     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
78289     **        WHEN x=eN THEN rN ELSE y END
78290     **
78291     ** X (if it exists) is in pExpr->pLeft.
78292     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
78293     ** ELSE clause and no other term matches, then the result of the
78294     ** exprssion is NULL.
78295     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
78296     **
78297     ** The result of the expression is the Ri for the first matching Ei,
78298     ** or if there is no matching Ei, the ELSE term Y, or if there is
78299     ** no ELSE term, NULL.
78300     */
78301     default: assert( op==TK_CASE ); {
78302       int endLabel;                     /* GOTO label for end of CASE stmt */
78303       int nextCase;                     /* GOTO label for next WHEN clause */
78304       int nExpr;                        /* 2x number of WHEN terms */
78305       int i;                            /* Loop counter */
78306       ExprList *pEList;                 /* List of WHEN terms */
78307       struct ExprList_item *aListelem;  /* Array of WHEN terms */
78308       Expr opCompare;                   /* The X==Ei expression */
78309       Expr cacheX;                      /* Cached expression X */
78310       Expr *pX;                         /* The X expression */
78311       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
78312       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
78313
78314       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
78315       assert((pExpr->x.pList->nExpr % 2) == 0);
78316       assert(pExpr->x.pList->nExpr > 0);
78317       pEList = pExpr->x.pList;
78318       aListelem = pEList->a;
78319       nExpr = pEList->nExpr;
78320       endLabel = sqlite3VdbeMakeLabel(v);
78321       if( (pX = pExpr->pLeft)!=0 ){
78322         cacheX = *pX;
78323         testcase( pX->op==TK_COLUMN );
78324         testcase( pX->op==TK_REGISTER );
78325         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
78326         testcase( regFree1==0 );
78327         cacheX.op = TK_REGISTER;
78328         opCompare.op = TK_EQ;
78329         opCompare.pLeft = &cacheX;
78330         pTest = &opCompare;
78331         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
78332         ** The value in regFree1 might get SCopy-ed into the file result.
78333         ** So make sure that the regFree1 register is not reused for other
78334         ** purposes and possibly overwritten.  */
78335         regFree1 = 0;
78336       }
78337       for(i=0; i<nExpr; i=i+2){
78338         sqlite3ExprCachePush(pParse);
78339         if( pX ){
78340           assert( pTest!=0 );
78341           opCompare.pRight = aListelem[i].pExpr;
78342         }else{
78343           pTest = aListelem[i].pExpr;
78344         }
78345         nextCase = sqlite3VdbeMakeLabel(v);
78346         testcase( pTest->op==TK_COLUMN );
78347         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
78348         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
78349         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
78350         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
78351         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
78352         sqlite3ExprCachePop(pParse, 1);
78353         sqlite3VdbeResolveLabel(v, nextCase);
78354       }
78355       if( pExpr->pRight ){
78356         sqlite3ExprCachePush(pParse);
78357         sqlite3ExprCode(pParse, pExpr->pRight, target);
78358         sqlite3ExprCachePop(pParse, 1);
78359       }else{
78360         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78361       }
78362       assert( db->mallocFailed || pParse->nErr>0
78363            || pParse->iCacheLevel==iCacheLevel );
78364       sqlite3VdbeResolveLabel(v, endLabel);
78365       break;
78366     }
78367 #ifndef SQLITE_OMIT_TRIGGER
78368     case TK_RAISE: {
78369       assert( pExpr->affinity==OE_Rollback
78370            || pExpr->affinity==OE_Abort
78371            || pExpr->affinity==OE_Fail
78372            || pExpr->affinity==OE_Ignore
78373       );
78374       if( !pParse->pTriggerTab ){
78375         sqlite3ErrorMsg(pParse,
78376                        "RAISE() may only be used within a trigger-program");
78377         return 0;
78378       }
78379       if( pExpr->affinity==OE_Abort ){
78380         sqlite3MayAbort(pParse);
78381       }
78382       assert( !ExprHasProperty(pExpr, EP_IntValue) );
78383       if( pExpr->affinity==OE_Ignore ){
78384         sqlite3VdbeAddOp4(
78385             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
78386       }else{
78387         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
78388       }
78389
78390       break;
78391     }
78392 #endif
78393   }
78394   sqlite3ReleaseTempReg(pParse, regFree1);
78395   sqlite3ReleaseTempReg(pParse, regFree2);
78396   return inReg;
78397 }
78398
78399 /*
78400 ** Generate code to evaluate an expression and store the results
78401 ** into a register.  Return the register number where the results
78402 ** are stored.
78403 **
78404 ** If the register is a temporary register that can be deallocated,
78405 ** then write its number into *pReg.  If the result register is not
78406 ** a temporary, then set *pReg to zero.
78407 */
78408 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
78409   int r1 = sqlite3GetTempReg(pParse);
78410   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78411   if( r2==r1 ){
78412     *pReg = r1;
78413   }else{
78414     sqlite3ReleaseTempReg(pParse, r1);
78415     *pReg = 0;
78416   }
78417   return r2;
78418 }
78419
78420 /*
78421 ** Generate code that will evaluate expression pExpr and store the
78422 ** results in register target.  The results are guaranteed to appear
78423 ** in register target.
78424 */
78425 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
78426   int inReg;
78427
78428   assert( target>0 && target<=pParse->nMem );
78429   if( pExpr && pExpr->op==TK_REGISTER ){
78430     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
78431   }else{
78432     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
78433     assert( pParse->pVdbe || pParse->db->mallocFailed );
78434     if( inReg!=target && pParse->pVdbe ){
78435       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
78436     }
78437   }
78438   return target;
78439 }
78440
78441 /*
78442 ** Generate code that evalutes the given expression and puts the result
78443 ** in register target.
78444 **
78445 ** Also make a copy of the expression results into another "cache" register
78446 ** and modify the expression so that the next time it is evaluated,
78447 ** the result is a copy of the cache register.
78448 **
78449 ** This routine is used for expressions that are used multiple
78450 ** times.  They are evaluated once and the results of the expression
78451 ** are reused.
78452 */
78453 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
78454   Vdbe *v = pParse->pVdbe;
78455   int inReg;
78456   inReg = sqlite3ExprCode(pParse, pExpr, target);
78457   assert( target>0 );
78458   /* This routine is called for terms to INSERT or UPDATE.  And the only
78459   ** other place where expressions can be converted into TK_REGISTER is
78460   ** in WHERE clause processing.  So as currently implemented, there is
78461   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
78462   ** keep the ALWAYS() in case the conditions above change with future
78463   ** modifications or enhancements. */
78464   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
78465     int iMem;
78466     iMem = ++pParse->nMem;
78467     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
78468     pExpr->iTable = iMem;
78469     pExpr->op2 = pExpr->op;
78470     pExpr->op = TK_REGISTER;
78471   }
78472   return inReg;
78473 }
78474
78475 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78476 /*
78477 ** Generate a human-readable explanation of an expression tree.
78478 */
78479 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
78480   int op;                   /* The opcode being coded */
78481   const char *zBinOp = 0;   /* Binary operator */
78482   const char *zUniOp = 0;   /* Unary operator */
78483   if( pExpr==0 ){
78484     op = TK_NULL;
78485   }else{
78486     op = pExpr->op;
78487   }
78488   switch( op ){
78489     case TK_AGG_COLUMN: {
78490       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
78491             pExpr->iTable, pExpr->iColumn);
78492       break;
78493     }
78494     case TK_COLUMN: {
78495       if( pExpr->iTable<0 ){
78496         /* This only happens when coding check constraints */
78497         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
78498       }else{
78499         sqlite3ExplainPrintf(pOut, "{%d:%d}",
78500                              pExpr->iTable, pExpr->iColumn);
78501       }
78502       break;
78503     }
78504     case TK_INTEGER: {
78505       if( pExpr->flags & EP_IntValue ){
78506         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
78507       }else{
78508         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
78509       }
78510       break;
78511     }
78512 #ifndef SQLITE_OMIT_FLOATING_POINT
78513     case TK_FLOAT: {
78514       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78515       break;
78516     }
78517 #endif
78518     case TK_STRING: {
78519       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
78520       break;
78521     }
78522     case TK_NULL: {
78523       sqlite3ExplainPrintf(pOut,"NULL");
78524       break;
78525     }
78526 #ifndef SQLITE_OMIT_BLOB_LITERAL
78527     case TK_BLOB: {
78528       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78529       break;
78530     }
78531 #endif
78532     case TK_VARIABLE: {
78533       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
78534                            pExpr->u.zToken, pExpr->iColumn);
78535       break;
78536     }
78537     case TK_REGISTER: {
78538       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
78539       break;
78540     }
78541     case TK_AS: {
78542       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78543       break;
78544     }
78545 #ifndef SQLITE_OMIT_CAST
78546     case TK_CAST: {
78547       /* Expressions of the form:   CAST(pLeft AS token) */
78548       const char *zAff = "unk";
78549       switch( sqlite3AffinityType(pExpr->u.zToken) ){
78550         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
78551         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
78552         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
78553         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
78554         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
78555       }
78556       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
78557       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78558       sqlite3ExplainPrintf(pOut, ")");
78559       break;
78560     }
78561 #endif /* SQLITE_OMIT_CAST */
78562     case TK_LT:      zBinOp = "LT";     break;
78563     case TK_LE:      zBinOp = "LE";     break;
78564     case TK_GT:      zBinOp = "GT";     break;
78565     case TK_GE:      zBinOp = "GE";     break;
78566     case TK_NE:      zBinOp = "NE";     break;
78567     case TK_EQ:      zBinOp = "EQ";     break;
78568     case TK_IS:      zBinOp = "IS";     break;
78569     case TK_ISNOT:   zBinOp = "ISNOT";  break;
78570     case TK_AND:     zBinOp = "AND";    break;
78571     case TK_OR:      zBinOp = "OR";     break;
78572     case TK_PLUS:    zBinOp = "ADD";    break;
78573     case TK_STAR:    zBinOp = "MUL";    break;
78574     case TK_MINUS:   zBinOp = "SUB";    break;
78575     case TK_REM:     zBinOp = "REM";    break;
78576     case TK_BITAND:  zBinOp = "BITAND"; break;
78577     case TK_BITOR:   zBinOp = "BITOR";  break;
78578     case TK_SLASH:   zBinOp = "DIV";    break;
78579     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
78580     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
78581     case TK_CONCAT:  zBinOp = "CONCAT"; break;
78582
78583     case TK_UMINUS:  zUniOp = "UMINUS"; break;
78584     case TK_UPLUS:   zUniOp = "UPLUS";  break;
78585     case TK_BITNOT:  zUniOp = "BITNOT"; break;
78586     case TK_NOT:     zUniOp = "NOT";    break;
78587     case TK_ISNULL:  zUniOp = "ISNULL"; break;
78588     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
78589
78590     case TK_COLLATE: {
78591       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78592       sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
78593       break;
78594     }
78595
78596     case TK_AGG_FUNCTION:
78597     case TK_CONST_FUNC:
78598     case TK_FUNCTION: {
78599       ExprList *pFarg;       /* List of function arguments */
78600       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
78601         pFarg = 0;
78602       }else{
78603         pFarg = pExpr->x.pList;
78604       }
78605       if( op==TK_AGG_FUNCTION ){
78606         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
78607                              pExpr->op2, pExpr->u.zToken);
78608       }else{
78609         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
78610       }
78611       if( pFarg ){
78612         sqlite3ExplainExprList(pOut, pFarg);
78613       }
78614       sqlite3ExplainPrintf(pOut, ")");
78615       break;
78616     }
78617 #ifndef SQLITE_OMIT_SUBQUERY
78618     case TK_EXISTS: {
78619       sqlite3ExplainPrintf(pOut, "EXISTS(");
78620       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78621       sqlite3ExplainPrintf(pOut,")");
78622       break;
78623     }
78624     case TK_SELECT: {
78625       sqlite3ExplainPrintf(pOut, "(");
78626       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78627       sqlite3ExplainPrintf(pOut, ")");
78628       break;
78629     }
78630     case TK_IN: {
78631       sqlite3ExplainPrintf(pOut, "IN(");
78632       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78633       sqlite3ExplainPrintf(pOut, ",");
78634       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
78635         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78636       }else{
78637         sqlite3ExplainExprList(pOut, pExpr->x.pList);
78638       }
78639       sqlite3ExplainPrintf(pOut, ")");
78640       break;
78641     }
78642 #endif /* SQLITE_OMIT_SUBQUERY */
78643
78644     /*
78645     **    x BETWEEN y AND z
78646     **
78647     ** This is equivalent to
78648     **
78649     **    x>=y AND x<=z
78650     **
78651     ** X is stored in pExpr->pLeft.
78652     ** Y is stored in pExpr->pList->a[0].pExpr.
78653     ** Z is stored in pExpr->pList->a[1].pExpr.
78654     */
78655     case TK_BETWEEN: {
78656       Expr *pX = pExpr->pLeft;
78657       Expr *pY = pExpr->x.pList->a[0].pExpr;
78658       Expr *pZ = pExpr->x.pList->a[1].pExpr;
78659       sqlite3ExplainPrintf(pOut, "BETWEEN(");
78660       sqlite3ExplainExpr(pOut, pX);
78661       sqlite3ExplainPrintf(pOut, ",");
78662       sqlite3ExplainExpr(pOut, pY);
78663       sqlite3ExplainPrintf(pOut, ",");
78664       sqlite3ExplainExpr(pOut, pZ);
78665       sqlite3ExplainPrintf(pOut, ")");
78666       break;
78667     }
78668     case TK_TRIGGER: {
78669       /* If the opcode is TK_TRIGGER, then the expression is a reference
78670       ** to a column in the new.* or old.* pseudo-tables available to
78671       ** trigger programs. In this case Expr.iTable is set to 1 for the
78672       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78673       ** is set to the column of the pseudo-table to read, or to -1 to
78674       ** read the rowid field.
78675       */
78676       sqlite3ExplainPrintf(pOut, "%s(%d)",
78677           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
78678       break;
78679     }
78680     case TK_CASE: {
78681       sqlite3ExplainPrintf(pOut, "CASE(");
78682       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78683       sqlite3ExplainPrintf(pOut, ",");
78684       sqlite3ExplainExprList(pOut, pExpr->x.pList);
78685       break;
78686     }
78687 #ifndef SQLITE_OMIT_TRIGGER
78688     case TK_RAISE: {
78689       const char *zType = "unk";
78690       switch( pExpr->affinity ){
78691         case OE_Rollback:   zType = "rollback";  break;
78692         case OE_Abort:      zType = "abort";     break;
78693         case OE_Fail:       zType = "fail";      break;
78694         case OE_Ignore:     zType = "ignore";    break;
78695       }
78696       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
78697       break;
78698     }
78699 #endif
78700   }
78701   if( zBinOp ){
78702     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
78703     sqlite3ExplainExpr(pOut, pExpr->pLeft);
78704     sqlite3ExplainPrintf(pOut,",");
78705     sqlite3ExplainExpr(pOut, pExpr->pRight);
78706     sqlite3ExplainPrintf(pOut,")");
78707   }else if( zUniOp ){
78708     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
78709     sqlite3ExplainExpr(pOut, pExpr->pLeft);
78710     sqlite3ExplainPrintf(pOut,")");
78711   }
78712 }
78713 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
78714
78715 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78716 /*
78717 ** Generate a human-readable explanation of an expression list.
78718 */
78719 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
78720   int i;
78721   if( pList==0 || pList->nExpr==0 ){
78722     sqlite3ExplainPrintf(pOut, "(empty-list)");
78723     return;
78724   }else if( pList->nExpr==1 ){
78725     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
78726   }else{
78727     sqlite3ExplainPush(pOut);
78728     for(i=0; i<pList->nExpr; i++){
78729       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
78730       sqlite3ExplainPush(pOut);
78731       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
78732       sqlite3ExplainPop(pOut);
78733       if( i<pList->nExpr-1 ){
78734         sqlite3ExplainNL(pOut);
78735       }
78736     }
78737     sqlite3ExplainPop(pOut);
78738   }
78739 }
78740 #endif /* SQLITE_DEBUG */
78741
78742 /*
78743 ** Return TRUE if pExpr is an constant expression that is appropriate
78744 ** for factoring out of a loop.  Appropriate expressions are:
78745 **
78746 **    *  Any expression that evaluates to two or more opcodes.
78747 **
78748 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
78749 **       or OP_Variable that does not need to be placed in a
78750 **       specific register.
78751 **
78752 ** There is no point in factoring out single-instruction constant
78753 ** expressions that need to be placed in a particular register.
78754 ** We could factor them out, but then we would end up adding an
78755 ** OP_SCopy instruction to move the value into the correct register
78756 ** later.  We might as well just use the original instruction and
78757 ** avoid the OP_SCopy.
78758 */
78759 static int isAppropriateForFactoring(Expr *p){
78760   if( !sqlite3ExprIsConstantNotJoin(p) ){
78761     return 0;  /* Only constant expressions are appropriate for factoring */
78762   }
78763   if( (p->flags & EP_FixedDest)==0 ){
78764     return 1;  /* Any constant without a fixed destination is appropriate */
78765   }
78766   while( p->op==TK_UPLUS ) p = p->pLeft;
78767   switch( p->op ){
78768 #ifndef SQLITE_OMIT_BLOB_LITERAL
78769     case TK_BLOB:
78770 #endif
78771     case TK_VARIABLE:
78772     case TK_INTEGER:
78773     case TK_FLOAT:
78774     case TK_NULL:
78775     case TK_STRING: {
78776       testcase( p->op==TK_BLOB );
78777       testcase( p->op==TK_VARIABLE );
78778       testcase( p->op==TK_INTEGER );
78779       testcase( p->op==TK_FLOAT );
78780       testcase( p->op==TK_NULL );
78781       testcase( p->op==TK_STRING );
78782       /* Single-instruction constants with a fixed destination are
78783       ** better done in-line.  If we factor them, they will just end
78784       ** up generating an OP_SCopy to move the value to the destination
78785       ** register. */
78786       return 0;
78787     }
78788     case TK_UMINUS: {
78789       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
78790         return 0;
78791       }
78792       break;
78793     }
78794     default: {
78795       break;
78796     }
78797   }
78798   return 1;
78799 }
78800
78801 /*
78802 ** If pExpr is a constant expression that is appropriate for
78803 ** factoring out of a loop, then evaluate the expression
78804 ** into a register and convert the expression into a TK_REGISTER
78805 ** expression.
78806 */
78807 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
78808   Parse *pParse = pWalker->pParse;
78809   switch( pExpr->op ){
78810     case TK_IN:
78811     case TK_REGISTER: {
78812       return WRC_Prune;
78813     }
78814     case TK_COLLATE: {
78815       return WRC_Continue;
78816     }
78817     case TK_FUNCTION:
78818     case TK_AGG_FUNCTION:
78819     case TK_CONST_FUNC: {
78820       /* The arguments to a function have a fixed destination.
78821       ** Mark them this way to avoid generated unneeded OP_SCopy
78822       ** instructions.
78823       */
78824       ExprList *pList = pExpr->x.pList;
78825       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78826       if( pList ){
78827         int i = pList->nExpr;
78828         struct ExprList_item *pItem = pList->a;
78829         for(; i>0; i--, pItem++){
78830           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
78831         }
78832       }
78833       break;
78834     }
78835   }
78836   if( isAppropriateForFactoring(pExpr) ){
78837     int r1 = ++pParse->nMem;
78838     int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78839     /* If r2!=r1, it means that register r1 is never used.  That is harmless
78840     ** but suboptimal, so we want to know about the situation to fix it.
78841     ** Hence the following assert: */
78842     assert( r2==r1 );
78843     pExpr->op2 = pExpr->op;
78844     pExpr->op = TK_REGISTER;
78845     pExpr->iTable = r2;
78846     return WRC_Prune;
78847   }
78848   return WRC_Continue;
78849 }
78850
78851 /*
78852 ** Preevaluate constant subexpressions within pExpr and store the
78853 ** results in registers.  Modify pExpr so that the constant subexpresions
78854 ** are TK_REGISTER opcodes that refer to the precomputed values.
78855 **
78856 ** This routine is a no-op if the jump to the cookie-check code has
78857 ** already occur.  Since the cookie-check jump is generated prior to
78858 ** any other serious processing, this check ensures that there is no
78859 ** way to accidently bypass the constant initializations.
78860 **
78861 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
78862 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
78863 ** interface.  This allows test logic to verify that the same answer is
78864 ** obtained for queries regardless of whether or not constants are
78865 ** precomputed into registers or if they are inserted in-line.
78866 */
78867 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
78868   Walker w;
78869   if( pParse->cookieGoto ) return;
78870   if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
78871   w.xExprCallback = evalConstExpr;
78872   w.xSelectCallback = 0;
78873   w.pParse = pParse;
78874   sqlite3WalkExpr(&w, pExpr);
78875 }
78876
78877
78878 /*
78879 ** Generate code that pushes the value of every element of the given
78880 ** expression list into a sequence of registers beginning at target.
78881 **
78882 ** Return the number of elements evaluated.
78883 */
78884 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
78885   Parse *pParse,     /* Parsing context */
78886   ExprList *pList,   /* The expression list to be coded */
78887   int target,        /* Where to write results */
78888   int doHardCopy     /* Make a hard copy of every element */
78889 ){
78890   struct ExprList_item *pItem;
78891   int i, n;
78892   assert( pList!=0 );
78893   assert( target>0 );
78894   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
78895   n = pList->nExpr;
78896   for(pItem=pList->a, i=0; i<n; i++, pItem++){
78897     Expr *pExpr = pItem->pExpr;
78898     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
78899     if( inReg!=target+i ){
78900       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
78901                         inReg, target+i);
78902     }
78903   }
78904   return n;
78905 }
78906
78907 /*
78908 ** Generate code for a BETWEEN operator.
78909 **
78910 **    x BETWEEN y AND z
78911 **
78912 ** The above is equivalent to
78913 **
78914 **    x>=y AND x<=z
78915 **
78916 ** Code it as such, taking care to do the common subexpression
78917 ** elementation of x.
78918 */
78919 static void exprCodeBetween(
78920   Parse *pParse,    /* Parsing and code generating context */
78921   Expr *pExpr,      /* The BETWEEN expression */
78922   int dest,         /* Jump here if the jump is taken */
78923   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
78924   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
78925 ){
78926   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
78927   Expr compLeft;    /* The  x>=y  term */
78928   Expr compRight;   /* The  x<=z  term */
78929   Expr exprX;       /* The  x  subexpression */
78930   int regFree1 = 0; /* Temporary use register */
78931
78932   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78933   exprX = *pExpr->pLeft;
78934   exprAnd.op = TK_AND;
78935   exprAnd.pLeft = &compLeft;
78936   exprAnd.pRight = &compRight;
78937   compLeft.op = TK_GE;
78938   compLeft.pLeft = &exprX;
78939   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
78940   compRight.op = TK_LE;
78941   compRight.pLeft = &exprX;
78942   compRight.pRight = pExpr->x.pList->a[1].pExpr;
78943   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
78944   exprX.op = TK_REGISTER;
78945   if( jumpIfTrue ){
78946     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
78947   }else{
78948     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
78949   }
78950   sqlite3ReleaseTempReg(pParse, regFree1);
78951
78952   /* Ensure adequate test coverage */
78953   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
78954   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
78955   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
78956   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
78957   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
78958   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
78959   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
78960   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
78961 }
78962
78963 /*
78964 ** Generate code for a boolean expression such that a jump is made
78965 ** to the label "dest" if the expression is true but execution
78966 ** continues straight thru if the expression is false.
78967 **
78968 ** If the expression evaluates to NULL (neither true nor false), then
78969 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
78970 **
78971 ** This code depends on the fact that certain token values (ex: TK_EQ)
78972 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
78973 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
78974 ** the make process cause these values to align.  Assert()s in the code
78975 ** below verify that the numbers are aligned correctly.
78976 */
78977 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78978   Vdbe *v = pParse->pVdbe;
78979   int op = 0;
78980   int regFree1 = 0;
78981   int regFree2 = 0;
78982   int r1, r2;
78983
78984   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
78985   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
78986   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
78987   op = pExpr->op;
78988   switch( op ){
78989     case TK_AND: {
78990       int d2 = sqlite3VdbeMakeLabel(v);
78991       testcase( jumpIfNull==0 );
78992       sqlite3ExprCachePush(pParse);
78993       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
78994       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
78995       sqlite3VdbeResolveLabel(v, d2);
78996       sqlite3ExprCachePop(pParse, 1);
78997       break;
78998     }
78999     case TK_OR: {
79000       testcase( jumpIfNull==0 );
79001       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
79002       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
79003       break;
79004     }
79005     case TK_NOT: {
79006       testcase( jumpIfNull==0 );
79007       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
79008       break;
79009     }
79010     case TK_LT:
79011     case TK_LE:
79012     case TK_GT:
79013     case TK_GE:
79014     case TK_NE:
79015     case TK_EQ: {
79016       assert( TK_LT==OP_Lt );
79017       assert( TK_LE==OP_Le );
79018       assert( TK_GT==OP_Gt );
79019       assert( TK_GE==OP_Ge );
79020       assert( TK_EQ==OP_Eq );
79021       assert( TK_NE==OP_Ne );
79022       testcase( op==TK_LT );
79023       testcase( op==TK_LE );
79024       testcase( op==TK_GT );
79025       testcase( op==TK_GE );
79026       testcase( op==TK_EQ );
79027       testcase( op==TK_NE );
79028       testcase( jumpIfNull==0 );
79029       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79030       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79031       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79032                   r1, r2, dest, jumpIfNull);
79033       testcase( regFree1==0 );
79034       testcase( regFree2==0 );
79035       break;
79036     }
79037     case TK_IS:
79038     case TK_ISNOT: {
79039       testcase( op==TK_IS );
79040       testcase( op==TK_ISNOT );
79041       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79042       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79043       op = (op==TK_IS) ? TK_EQ : TK_NE;
79044       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79045                   r1, r2, dest, SQLITE_NULLEQ);
79046       testcase( regFree1==0 );
79047       testcase( regFree2==0 );
79048       break;
79049     }
79050     case TK_ISNULL:
79051     case TK_NOTNULL: {
79052       assert( TK_ISNULL==OP_IsNull );
79053       assert( TK_NOTNULL==OP_NotNull );
79054       testcase( op==TK_ISNULL );
79055       testcase( op==TK_NOTNULL );
79056       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79057       sqlite3VdbeAddOp2(v, op, r1, dest);
79058       testcase( regFree1==0 );
79059       break;
79060     }
79061     case TK_BETWEEN: {
79062       testcase( jumpIfNull==0 );
79063       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
79064       break;
79065     }
79066 #ifndef SQLITE_OMIT_SUBQUERY
79067     case TK_IN: {
79068       int destIfFalse = sqlite3VdbeMakeLabel(v);
79069       int destIfNull = jumpIfNull ? dest : destIfFalse;
79070       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
79071       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
79072       sqlite3VdbeResolveLabel(v, destIfFalse);
79073       break;
79074     }
79075 #endif
79076     default: {
79077       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
79078       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
79079       testcase( regFree1==0 );
79080       testcase( jumpIfNull==0 );
79081       break;
79082     }
79083   }
79084   sqlite3ReleaseTempReg(pParse, regFree1);
79085   sqlite3ReleaseTempReg(pParse, regFree2);
79086 }
79087
79088 /*
79089 ** Generate code for a boolean expression such that a jump is made
79090 ** to the label "dest" if the expression is false but execution
79091 ** continues straight thru if the expression is true.
79092 **
79093 ** If the expression evaluates to NULL (neither true nor false) then
79094 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
79095 ** is 0.
79096 */
79097 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
79098   Vdbe *v = pParse->pVdbe;
79099   int op = 0;
79100   int regFree1 = 0;
79101   int regFree2 = 0;
79102   int r1, r2;
79103
79104   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
79105   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
79106   if( pExpr==0 )    return;
79107
79108   /* The value of pExpr->op and op are related as follows:
79109   **
79110   **       pExpr->op            op
79111   **       ---------          ----------
79112   **       TK_ISNULL          OP_NotNull
79113   **       TK_NOTNULL         OP_IsNull
79114   **       TK_NE              OP_Eq
79115   **       TK_EQ              OP_Ne
79116   **       TK_GT              OP_Le
79117   **       TK_LE              OP_Gt
79118   **       TK_GE              OP_Lt
79119   **       TK_LT              OP_Ge
79120   **
79121   ** For other values of pExpr->op, op is undefined and unused.
79122   ** The value of TK_ and OP_ constants are arranged such that we
79123   ** can compute the mapping above using the following expression.
79124   ** Assert()s verify that the computation is correct.
79125   */
79126   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
79127
79128   /* Verify correct alignment of TK_ and OP_ constants
79129   */
79130   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
79131   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
79132   assert( pExpr->op!=TK_NE || op==OP_Eq );
79133   assert( pExpr->op!=TK_EQ || op==OP_Ne );
79134   assert( pExpr->op!=TK_LT || op==OP_Ge );
79135   assert( pExpr->op!=TK_LE || op==OP_Gt );
79136   assert( pExpr->op!=TK_GT || op==OP_Le );
79137   assert( pExpr->op!=TK_GE || op==OP_Lt );
79138
79139   switch( pExpr->op ){
79140     case TK_AND: {
79141       testcase( jumpIfNull==0 );
79142       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
79143       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
79144       break;
79145     }
79146     case TK_OR: {
79147       int d2 = sqlite3VdbeMakeLabel(v);
79148       testcase( jumpIfNull==0 );
79149       sqlite3ExprCachePush(pParse);
79150       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
79151       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
79152       sqlite3VdbeResolveLabel(v, d2);
79153       sqlite3ExprCachePop(pParse, 1);
79154       break;
79155     }
79156     case TK_NOT: {
79157       testcase( jumpIfNull==0 );
79158       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
79159       break;
79160     }
79161     case TK_LT:
79162     case TK_LE:
79163     case TK_GT:
79164     case TK_GE:
79165     case TK_NE:
79166     case TK_EQ: {
79167       testcase( op==TK_LT );
79168       testcase( op==TK_LE );
79169       testcase( op==TK_GT );
79170       testcase( op==TK_GE );
79171       testcase( op==TK_EQ );
79172       testcase( op==TK_NE );
79173       testcase( jumpIfNull==0 );
79174       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79175       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79176       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79177                   r1, r2, dest, jumpIfNull);
79178       testcase( regFree1==0 );
79179       testcase( regFree2==0 );
79180       break;
79181     }
79182     case TK_IS:
79183     case TK_ISNOT: {
79184       testcase( pExpr->op==TK_IS );
79185       testcase( pExpr->op==TK_ISNOT );
79186       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79187       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79188       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
79189       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79190                   r1, r2, dest, SQLITE_NULLEQ);
79191       testcase( regFree1==0 );
79192       testcase( regFree2==0 );
79193       break;
79194     }
79195     case TK_ISNULL:
79196     case TK_NOTNULL: {
79197       testcase( op==TK_ISNULL );
79198       testcase( op==TK_NOTNULL );
79199       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79200       sqlite3VdbeAddOp2(v, op, r1, dest);
79201       testcase( regFree1==0 );
79202       break;
79203     }
79204     case TK_BETWEEN: {
79205       testcase( jumpIfNull==0 );
79206       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
79207       break;
79208     }
79209 #ifndef SQLITE_OMIT_SUBQUERY
79210     case TK_IN: {
79211       if( jumpIfNull ){
79212         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
79213       }else{
79214         int destIfNull = sqlite3VdbeMakeLabel(v);
79215         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
79216         sqlite3VdbeResolveLabel(v, destIfNull);
79217       }
79218       break;
79219     }
79220 #endif
79221     default: {
79222       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
79223       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
79224       testcase( regFree1==0 );
79225       testcase( jumpIfNull==0 );
79226       break;
79227     }
79228   }
79229   sqlite3ReleaseTempReg(pParse, regFree1);
79230   sqlite3ReleaseTempReg(pParse, regFree2);
79231 }
79232
79233 /*
79234 ** Do a deep comparison of two expression trees.  Return 0 if the two
79235 ** expressions are completely identical.  Return 1 if they differ only
79236 ** by a COLLATE operator at the top level.  Return 2 if there are differences
79237 ** other than the top-level COLLATE operator.
79238 **
79239 ** Sometimes this routine will return 2 even if the two expressions
79240 ** really are equivalent.  If we cannot prove that the expressions are
79241 ** identical, we return 2 just to be safe.  So if this routine
79242 ** returns 2, then you do not really know for certain if the two
79243 ** expressions are the same.  But if you get a 0 or 1 return, then you
79244 ** can be sure the expressions are the same.  In the places where
79245 ** this routine is used, it does not hurt to get an extra 2 - that
79246 ** just might result in some slightly slower code.  But returning
79247 ** an incorrect 0 or 1 could lead to a malfunction.
79248 */
79249 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
79250   if( pA==0||pB==0 ){
79251     return pB==pA ? 0 : 2;
79252   }
79253   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
79254   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
79255   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
79256     return 2;
79257   }
79258   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
79259   if( pA->op!=pB->op ){
79260     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
79261       return 1;
79262     }
79263     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
79264       return 1;
79265     }
79266     return 2;
79267   }
79268   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
79269   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
79270   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
79271   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
79272   if( ExprHasProperty(pA, EP_IntValue) ){
79273     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
79274       return 2;
79275     }
79276   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
79277     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
79278     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
79279       return pA->op==TK_COLLATE ? 1 : 2;
79280     }
79281   }
79282   return 0;
79283 }
79284
79285 /*
79286 ** Compare two ExprList objects.  Return 0 if they are identical and
79287 ** non-zero if they differ in any way.
79288 **
79289 ** This routine might return non-zero for equivalent ExprLists.  The
79290 ** only consequence will be disabled optimizations.  But this routine
79291 ** must never return 0 if the two ExprList objects are different, or
79292 ** a malfunction will result.
79293 **
79294 ** Two NULL pointers are considered to be the same.  But a NULL pointer
79295 ** always differs from a non-NULL pointer.
79296 */
79297 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
79298   int i;
79299   if( pA==0 && pB==0 ) return 0;
79300   if( pA==0 || pB==0 ) return 1;
79301   if( pA->nExpr!=pB->nExpr ) return 1;
79302   for(i=0; i<pA->nExpr; i++){
79303     Expr *pExprA = pA->a[i].pExpr;
79304     Expr *pExprB = pB->a[i].pExpr;
79305     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
79306     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
79307   }
79308   return 0;
79309 }
79310
79311 /*
79312 ** An instance of the following structure is used by the tree walker
79313 ** to count references to table columns in the arguments of an
79314 ** aggregate function, in order to implement the
79315 ** sqlite3FunctionThisSrc() routine.
79316 */
79317 struct SrcCount {
79318   SrcList *pSrc;   /* One particular FROM clause in a nested query */
79319   int nThis;       /* Number of references to columns in pSrcList */
79320   int nOther;      /* Number of references to columns in other FROM clauses */
79321 };
79322
79323 /*
79324 ** Count the number of references to columns.
79325 */
79326 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
79327   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
79328   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
79329   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
79330   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
79331   ** NEVER() will need to be removed. */
79332   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
79333     int i;
79334     struct SrcCount *p = pWalker->u.pSrcCount;
79335     SrcList *pSrc = p->pSrc;
79336     for(i=0; i<pSrc->nSrc; i++){
79337       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
79338     }
79339     if( i<pSrc->nSrc ){
79340       p->nThis++;
79341     }else{
79342       p->nOther++;
79343     }
79344   }
79345   return WRC_Continue;
79346 }
79347
79348 /*
79349 ** Determine if any of the arguments to the pExpr Function reference
79350 ** pSrcList.  Return true if they do.  Also return true if the function
79351 ** has no arguments or has only constant arguments.  Return false if pExpr
79352 ** references columns but not columns of tables found in pSrcList.
79353 */
79354 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
79355   Walker w;
79356   struct SrcCount cnt;
79357   assert( pExpr->op==TK_AGG_FUNCTION );
79358   memset(&w, 0, sizeof(w));
79359   w.xExprCallback = exprSrcCount;
79360   w.u.pSrcCount = &cnt;
79361   cnt.pSrc = pSrcList;
79362   cnt.nThis = 0;
79363   cnt.nOther = 0;
79364   sqlite3WalkExprList(&w, pExpr->x.pList);
79365   return cnt.nThis>0 || cnt.nOther==0;
79366 }
79367
79368 /*
79369 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
79370 ** the new element.  Return a negative number if malloc fails.
79371 */
79372 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
79373   int i;
79374   pInfo->aCol = sqlite3ArrayAllocate(
79375        db,
79376        pInfo->aCol,
79377        sizeof(pInfo->aCol[0]),
79378        &pInfo->nColumn,
79379        &i
79380   );
79381   return i;
79382 }
79383
79384 /*
79385 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
79386 ** the new element.  Return a negative number if malloc fails.
79387 */
79388 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
79389   int i;
79390   pInfo->aFunc = sqlite3ArrayAllocate(
79391        db,
79392        pInfo->aFunc,
79393        sizeof(pInfo->aFunc[0]),
79394        &pInfo->nFunc,
79395        &i
79396   );
79397   return i;
79398 }
79399
79400 /*
79401 ** This is the xExprCallback for a tree walker.  It is used to
79402 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
79403 ** for additional information.
79404 */
79405 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
79406   int i;
79407   NameContext *pNC = pWalker->u.pNC;
79408   Parse *pParse = pNC->pParse;
79409   SrcList *pSrcList = pNC->pSrcList;
79410   AggInfo *pAggInfo = pNC->pAggInfo;
79411
79412   switch( pExpr->op ){
79413     case TK_AGG_COLUMN:
79414     case TK_COLUMN: {
79415       testcase( pExpr->op==TK_AGG_COLUMN );
79416       testcase( pExpr->op==TK_COLUMN );
79417       /* Check to see if the column is in one of the tables in the FROM
79418       ** clause of the aggregate query */
79419       if( ALWAYS(pSrcList!=0) ){
79420         struct SrcList_item *pItem = pSrcList->a;
79421         for(i=0; i<pSrcList->nSrc; i++, pItem++){
79422           struct AggInfo_col *pCol;
79423           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79424           if( pExpr->iTable==pItem->iCursor ){
79425             /* If we reach this point, it means that pExpr refers to a table
79426             ** that is in the FROM clause of the aggregate query.
79427             **
79428             ** Make an entry for the column in pAggInfo->aCol[] if there
79429             ** is not an entry there already.
79430             */
79431             int k;
79432             pCol = pAggInfo->aCol;
79433             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
79434               if( pCol->iTable==pExpr->iTable &&
79435                   pCol->iColumn==pExpr->iColumn ){
79436                 break;
79437               }
79438             }
79439             if( (k>=pAggInfo->nColumn)
79440              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
79441             ){
79442               pCol = &pAggInfo->aCol[k];
79443               pCol->pTab = pExpr->pTab;
79444               pCol->iTable = pExpr->iTable;
79445               pCol->iColumn = pExpr->iColumn;
79446               pCol->iMem = ++pParse->nMem;
79447               pCol->iSorterColumn = -1;
79448               pCol->pExpr = pExpr;
79449               if( pAggInfo->pGroupBy ){
79450                 int j, n;
79451                 ExprList *pGB = pAggInfo->pGroupBy;
79452                 struct ExprList_item *pTerm = pGB->a;
79453                 n = pGB->nExpr;
79454                 for(j=0; j<n; j++, pTerm++){
79455                   Expr *pE = pTerm->pExpr;
79456                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
79457                       pE->iColumn==pExpr->iColumn ){
79458                     pCol->iSorterColumn = j;
79459                     break;
79460                   }
79461                 }
79462               }
79463               if( pCol->iSorterColumn<0 ){
79464                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
79465               }
79466             }
79467             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
79468             ** because it was there before or because we just created it).
79469             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
79470             ** pAggInfo->aCol[] entry.
79471             */
79472             ExprSetIrreducible(pExpr);
79473             pExpr->pAggInfo = pAggInfo;
79474             pExpr->op = TK_AGG_COLUMN;
79475             pExpr->iAgg = (i16)k;
79476             break;
79477           } /* endif pExpr->iTable==pItem->iCursor */
79478         } /* end loop over pSrcList */
79479       }
79480       return WRC_Prune;
79481     }
79482     case TK_AGG_FUNCTION: {
79483       if( (pNC->ncFlags & NC_InAggFunc)==0
79484        && pWalker->walkerDepth==pExpr->op2
79485       ){
79486         /* Check to see if pExpr is a duplicate of another aggregate
79487         ** function that is already in the pAggInfo structure
79488         */
79489         struct AggInfo_func *pItem = pAggInfo->aFunc;
79490         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
79491           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
79492             break;
79493           }
79494         }
79495         if( i>=pAggInfo->nFunc ){
79496           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
79497           */
79498           u8 enc = ENC(pParse->db);
79499           i = addAggInfoFunc(pParse->db, pAggInfo);
79500           if( i>=0 ){
79501             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79502             pItem = &pAggInfo->aFunc[i];
79503             pItem->pExpr = pExpr;
79504             pItem->iMem = ++pParse->nMem;
79505             assert( !ExprHasProperty(pExpr, EP_IntValue) );
79506             pItem->pFunc = sqlite3FindFunction(pParse->db,
79507                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
79508                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
79509             if( pExpr->flags & EP_Distinct ){
79510               pItem->iDistinct = pParse->nTab++;
79511             }else{
79512               pItem->iDistinct = -1;
79513             }
79514           }
79515         }
79516         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
79517         */
79518         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79519         ExprSetIrreducible(pExpr);
79520         pExpr->iAgg = (i16)i;
79521         pExpr->pAggInfo = pAggInfo;
79522         return WRC_Prune;
79523       }else{
79524         return WRC_Continue;
79525       }
79526     }
79527   }
79528   return WRC_Continue;
79529 }
79530 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
79531   UNUSED_PARAMETER(pWalker);
79532   UNUSED_PARAMETER(pSelect);
79533   return WRC_Continue;
79534 }
79535
79536 /*
79537 ** Analyze the pExpr expression looking for aggregate functions and
79538 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
79539 ** points to.  Additional entries are made on the AggInfo object as
79540 ** necessary.
79541 **
79542 ** This routine should only be called after the expression has been
79543 ** analyzed by sqlite3ResolveExprNames().
79544 */
79545 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
79546   Walker w;
79547   memset(&w, 0, sizeof(w));
79548   w.xExprCallback = analyzeAggregate;
79549   w.xSelectCallback = analyzeAggregatesInSelect;
79550   w.u.pNC = pNC;
79551   assert( pNC->pSrcList!=0 );
79552   sqlite3WalkExpr(&w, pExpr);
79553 }
79554
79555 /*
79556 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
79557 ** expression list.  Return the number of errors.
79558 **
79559 ** If an error is found, the analysis is cut short.
79560 */
79561 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
79562   struct ExprList_item *pItem;
79563   int i;
79564   if( pList ){
79565     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
79566       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
79567     }
79568   }
79569 }
79570
79571 /*
79572 ** Allocate a single new register for use to hold some intermediate result.
79573 */
79574 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
79575   if( pParse->nTempReg==0 ){
79576     return ++pParse->nMem;
79577   }
79578   return pParse->aTempReg[--pParse->nTempReg];
79579 }
79580
79581 /*
79582 ** Deallocate a register, making available for reuse for some other
79583 ** purpose.
79584 **
79585 ** If a register is currently being used by the column cache, then
79586 ** the dallocation is deferred until the column cache line that uses
79587 ** the register becomes stale.
79588 */
79589 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
79590   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
79591     int i;
79592     struct yColCache *p;
79593     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79594       if( p->iReg==iReg ){
79595         p->tempReg = 1;
79596         return;
79597       }
79598     }
79599     pParse->aTempReg[pParse->nTempReg++] = iReg;
79600   }
79601 }
79602
79603 /*
79604 ** Allocate or deallocate a block of nReg consecutive registers
79605 */
79606 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
79607   int i, n;
79608   i = pParse->iRangeReg;
79609   n = pParse->nRangeReg;
79610   if( nReg<=n ){
79611     assert( !usedAsColumnCache(pParse, i, i+n-1) );
79612     pParse->iRangeReg += nReg;
79613     pParse->nRangeReg -= nReg;
79614   }else{
79615     i = pParse->nMem+1;
79616     pParse->nMem += nReg;
79617   }
79618   return i;
79619 }
79620 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
79621   sqlite3ExprCacheRemove(pParse, iReg, nReg);
79622   if( nReg>pParse->nRangeReg ){
79623     pParse->nRangeReg = nReg;
79624     pParse->iRangeReg = iReg;
79625   }
79626 }
79627
79628 /*
79629 ** Mark all temporary registers as being unavailable for reuse.
79630 */
79631 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
79632   pParse->nTempReg = 0;
79633   pParse->nRangeReg = 0;
79634 }
79635
79636 /************** End of expr.c ************************************************/
79637 /************** Begin file alter.c *******************************************/
79638 /*
79639 ** 2005 February 15
79640 **
79641 ** The author disclaims copyright to this source code.  In place of
79642 ** a legal notice, here is a blessing:
79643 **
79644 **    May you do good and not evil.
79645 **    May you find forgiveness for yourself and forgive others.
79646 **    May you share freely, never taking more than you give.
79647 **
79648 *************************************************************************
79649 ** This file contains C code routines that used to generate VDBE code
79650 ** that implements the ALTER TABLE command.
79651 */
79652
79653 /*
79654 ** The code in this file only exists if we are not omitting the
79655 ** ALTER TABLE logic from the build.
79656 */
79657 #ifndef SQLITE_OMIT_ALTERTABLE
79658
79659
79660 /*
79661 ** This function is used by SQL generated to implement the
79662 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
79663 ** CREATE INDEX command. The second is a table name. The table name in
79664 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
79665 ** argument and the result returned. Examples:
79666 **
79667 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
79668 **     -> 'CREATE TABLE def(a, b, c)'
79669 **
79670 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
79671 **     -> 'CREATE INDEX i ON def(a, b, c)'
79672 */
79673 static void renameTableFunc(
79674   sqlite3_context *context,
79675   int NotUsed,
79676   sqlite3_value **argv
79677 ){
79678   unsigned char const *zSql = sqlite3_value_text(argv[0]);
79679   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79680
79681   int token;
79682   Token tname;
79683   unsigned char const *zCsr = zSql;
79684   int len = 0;
79685   char *zRet;
79686
79687   sqlite3 *db = sqlite3_context_db_handle(context);
79688
79689   UNUSED_PARAMETER(NotUsed);
79690
79691   /* The principle used to locate the table name in the CREATE TABLE
79692   ** statement is that the table name is the first non-space token that
79693   ** is immediately followed by a TK_LP or TK_USING token.
79694   */
79695   if( zSql ){
79696     do {
79697       if( !*zCsr ){
79698         /* Ran out of input before finding an opening bracket. Return NULL. */
79699         return;
79700       }
79701
79702       /* Store the token that zCsr points to in tname. */
79703       tname.z = (char*)zCsr;
79704       tname.n = len;
79705
79706       /* Advance zCsr to the next token. Store that token type in 'token',
79707       ** and its length in 'len' (to be used next iteration of this loop).
79708       */
79709       do {
79710         zCsr += len;
79711         len = sqlite3GetToken(zCsr, &token);
79712       } while( token==TK_SPACE );
79713       assert( len>0 );
79714     } while( token!=TK_LP && token!=TK_USING );
79715
79716     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
79717        zTableName, tname.z+tname.n);
79718     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79719   }
79720 }
79721
79722 /*
79723 ** This C function implements an SQL user function that is used by SQL code
79724 ** generated by the ALTER TABLE ... RENAME command to modify the definition
79725 ** of any foreign key constraints that use the table being renamed as the
79726 ** parent table. It is passed three arguments:
79727 **
79728 **   1) The complete text of the CREATE TABLE statement being modified,
79729 **   2) The old name of the table being renamed, and
79730 **   3) The new name of the table being renamed.
79731 **
79732 ** It returns the new CREATE TABLE statement. For example:
79733 **
79734 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
79735 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
79736 */
79737 #ifndef SQLITE_OMIT_FOREIGN_KEY
79738 static void renameParentFunc(
79739   sqlite3_context *context,
79740   int NotUsed,
79741   sqlite3_value **argv
79742 ){
79743   sqlite3 *db = sqlite3_context_db_handle(context);
79744   char *zOutput = 0;
79745   char *zResult;
79746   unsigned char const *zInput = sqlite3_value_text(argv[0]);
79747   unsigned char const *zOld = sqlite3_value_text(argv[1]);
79748   unsigned char const *zNew = sqlite3_value_text(argv[2]);
79749
79750   unsigned const char *z;         /* Pointer to token */
79751   int n;                          /* Length of token z */
79752   int token;                      /* Type of token */
79753
79754   UNUSED_PARAMETER(NotUsed);
79755   for(z=zInput; *z; z=z+n){
79756     n = sqlite3GetToken(z, &token);
79757     if( token==TK_REFERENCES ){
79758       char *zParent;
79759       do {
79760         z += n;
79761         n = sqlite3GetToken(z, &token);
79762       }while( token==TK_SPACE );
79763
79764       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
79765       if( zParent==0 ) break;
79766       sqlite3Dequote(zParent);
79767       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
79768         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
79769             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
79770         );
79771         sqlite3DbFree(db, zOutput);
79772         zOutput = zOut;
79773         zInput = &z[n];
79774       }
79775       sqlite3DbFree(db, zParent);
79776     }
79777   }
79778
79779   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
79780   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
79781   sqlite3DbFree(db, zOutput);
79782 }
79783 #endif
79784
79785 #ifndef SQLITE_OMIT_TRIGGER
79786 /* This function is used by SQL generated to implement the
79787 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
79788 ** statement. The second is a table name. The table name in the CREATE
79789 ** TRIGGER statement is replaced with the third argument and the result
79790 ** returned. This is analagous to renameTableFunc() above, except for CREATE
79791 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
79792 */
79793 static void renameTriggerFunc(
79794   sqlite3_context *context,
79795   int NotUsed,
79796   sqlite3_value **argv
79797 ){
79798   unsigned char const *zSql = sqlite3_value_text(argv[0]);
79799   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79800
79801   int token;
79802   Token tname;
79803   int dist = 3;
79804   unsigned char const *zCsr = zSql;
79805   int len = 0;
79806   char *zRet;
79807   sqlite3 *db = sqlite3_context_db_handle(context);
79808
79809   UNUSED_PARAMETER(NotUsed);
79810
79811   /* The principle used to locate the table name in the CREATE TRIGGER
79812   ** statement is that the table name is the first token that is immediatedly
79813   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
79814   ** of TK_WHEN, TK_BEGIN or TK_FOR.
79815   */
79816   if( zSql ){
79817     do {
79818
79819       if( !*zCsr ){
79820         /* Ran out of input before finding the table name. Return NULL. */
79821         return;
79822       }
79823
79824       /* Store the token that zCsr points to in tname. */
79825       tname.z = (char*)zCsr;
79826       tname.n = len;
79827
79828       /* Advance zCsr to the next token. Store that token type in 'token',
79829       ** and its length in 'len' (to be used next iteration of this loop).
79830       */
79831       do {
79832         zCsr += len;
79833         len = sqlite3GetToken(zCsr, &token);
79834       }while( token==TK_SPACE );
79835       assert( len>0 );
79836
79837       /* Variable 'dist' stores the number of tokens read since the most
79838       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
79839       ** token is read and 'dist' equals 2, the condition stated above
79840       ** to be met.
79841       **
79842       ** Note that ON cannot be a database, table or column name, so
79843       ** there is no need to worry about syntax like
79844       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
79845       */
79846       dist++;
79847       if( token==TK_DOT || token==TK_ON ){
79848         dist = 0;
79849       }
79850     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
79851
79852     /* Variable tname now contains the token that is the old table-name
79853     ** in the CREATE TRIGGER statement.
79854     */
79855     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
79856        zTableName, tname.z+tname.n);
79857     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79858   }
79859 }
79860 #endif   /* !SQLITE_OMIT_TRIGGER */
79861
79862 /*
79863 ** Register built-in functions used to help implement ALTER TABLE
79864 */
79865 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
79866   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
79867     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
79868 #ifndef SQLITE_OMIT_TRIGGER
79869     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
79870 #endif
79871 #ifndef SQLITE_OMIT_FOREIGN_KEY
79872     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
79873 #endif
79874   };
79875   int i;
79876   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79877   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
79878
79879   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
79880     sqlite3FuncDefInsert(pHash, &aFunc[i]);
79881   }
79882 }
79883
79884 /*
79885 ** This function is used to create the text of expressions of the form:
79886 **
79887 **   name=<constant1> OR name=<constant2> OR ...
79888 **
79889 ** If argument zWhere is NULL, then a pointer string containing the text
79890 ** "name=<constant>" is returned, where <constant> is the quoted version
79891 ** of the string passed as argument zConstant. The returned buffer is
79892 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
79893 ** caller to ensure that it is eventually freed.
79894 **
79895 ** If argument zWhere is not NULL, then the string returned is
79896 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
79897 ** In this case zWhere is passed to sqlite3DbFree() before returning.
79898 **
79899 */
79900 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
79901   char *zNew;
79902   if( !zWhere ){
79903     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
79904   }else{
79905     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
79906     sqlite3DbFree(db, zWhere);
79907   }
79908   return zNew;
79909 }
79910
79911 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79912 /*
79913 ** Generate the text of a WHERE expression which can be used to select all
79914 ** tables that have foreign key constraints that refer to table pTab (i.e.
79915 ** constraints for which pTab is the parent table) from the sqlite_master
79916 ** table.
79917 */
79918 static char *whereForeignKeys(Parse *pParse, Table *pTab){
79919   FKey *p;
79920   char *zWhere = 0;
79921   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79922     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
79923   }
79924   return zWhere;
79925 }
79926 #endif
79927
79928 /*
79929 ** Generate the text of a WHERE expression which can be used to select all
79930 ** temporary triggers on table pTab from the sqlite_temp_master table. If
79931 ** table pTab has no temporary triggers, or is itself stored in the
79932 ** temporary database, NULL is returned.
79933 */
79934 static char *whereTempTriggers(Parse *pParse, Table *pTab){
79935   Trigger *pTrig;
79936   char *zWhere = 0;
79937   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
79938
79939   /* If the table is not located in the temp-db (in which case NULL is
79940   ** returned, loop through the tables list of triggers. For each trigger
79941   ** that is not part of the temp-db schema, add a clause to the WHERE
79942   ** expression being built up in zWhere.
79943   */
79944   if( pTab->pSchema!=pTempSchema ){
79945     sqlite3 *db = pParse->db;
79946     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79947       if( pTrig->pSchema==pTempSchema ){
79948         zWhere = whereOrName(db, zWhere, pTrig->zName);
79949       }
79950     }
79951   }
79952   if( zWhere ){
79953     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
79954     sqlite3DbFree(pParse->db, zWhere);
79955     zWhere = zNew;
79956   }
79957   return zWhere;
79958 }
79959
79960 /*
79961 ** Generate code to drop and reload the internal representation of table
79962 ** pTab from the database, including triggers and temporary triggers.
79963 ** Argument zName is the name of the table in the database schema at
79964 ** the time the generated code is executed. This can be different from
79965 ** pTab->zName if this function is being called to code part of an
79966 ** "ALTER TABLE RENAME TO" statement.
79967 */
79968 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
79969   Vdbe *v;
79970   char *zWhere;
79971   int iDb;                   /* Index of database containing pTab */
79972 #ifndef SQLITE_OMIT_TRIGGER
79973   Trigger *pTrig;
79974 #endif
79975
79976   v = sqlite3GetVdbe(pParse);
79977   if( NEVER(v==0) ) return;
79978   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79979   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79980   assert( iDb>=0 );
79981
79982 #ifndef SQLITE_OMIT_TRIGGER
79983   /* Drop any table triggers from the internal schema. */
79984   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79985     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
79986     assert( iTrigDb==iDb || iTrigDb==1 );
79987     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
79988   }
79989 #endif
79990
79991   /* Drop the table and index from the internal schema.  */
79992   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
79993
79994   /* Reload the table, index and permanent trigger schemas. */
79995   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
79996   if( !zWhere ) return;
79997   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
79998
79999 #ifndef SQLITE_OMIT_TRIGGER
80000   /* Now, if the table is not stored in the temp database, reload any temp
80001   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
80002   */
80003   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
80004     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
80005   }
80006 #endif
80007 }
80008
80009 /*
80010 ** Parameter zName is the name of a table that is about to be altered
80011 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
80012 ** If the table is a system table, this function leaves an error message
80013 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
80014 **
80015 ** Or, if zName is not a system table, zero is returned.
80016 */
80017 static int isSystemTable(Parse *pParse, const char *zName){
80018   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
80019     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
80020     return 1;
80021   }
80022   return 0;
80023 }
80024
80025 /*
80026 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
80027 ** command.
80028 */
80029 SQLITE_PRIVATE void sqlite3AlterRenameTable(
80030   Parse *pParse,            /* Parser context. */
80031   SrcList *pSrc,            /* The table to rename. */
80032   Token *pName              /* The new table name. */
80033 ){
80034   int iDb;                  /* Database that contains the table */
80035   char *zDb;                /* Name of database iDb */
80036   Table *pTab;              /* Table being renamed */
80037   char *zName = 0;          /* NULL-terminated version of pName */
80038   sqlite3 *db = pParse->db; /* Database connection */
80039   int nTabName;             /* Number of UTF-8 characters in zTabName */
80040   const char *zTabName;     /* Original name of the table */
80041   Vdbe *v;
80042 #ifndef SQLITE_OMIT_TRIGGER
80043   char *zWhere = 0;         /* Where clause to locate temp triggers */
80044 #endif
80045   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
80046   int savedDbFlags;         /* Saved value of db->flags */
80047
80048   savedDbFlags = db->flags;
80049   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
80050   assert( pSrc->nSrc==1 );
80051   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80052
80053   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
80054   if( !pTab ) goto exit_rename_table;
80055   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80056   zDb = db->aDb[iDb].zName;
80057   db->flags |= SQLITE_PreferBuiltin;
80058
80059   /* Get a NULL terminated version of the new table name. */
80060   zName = sqlite3NameFromToken(db, pName);
80061   if( !zName ) goto exit_rename_table;
80062
80063   /* Check that a table or index named 'zName' does not already exist
80064   ** in database iDb. If so, this is an error.
80065   */
80066   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
80067     sqlite3ErrorMsg(pParse,
80068         "there is already another table or index with this name: %s", zName);
80069     goto exit_rename_table;
80070   }
80071
80072   /* Make sure it is not a system table being altered, or a reserved name
80073   ** that the table is being renamed to.
80074   */
80075   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
80076     goto exit_rename_table;
80077   }
80078   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
80079     exit_rename_table;
80080   }
80081
80082 #ifndef SQLITE_OMIT_VIEW
80083   if( pTab->pSelect ){
80084     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
80085     goto exit_rename_table;
80086   }
80087 #endif
80088
80089 #ifndef SQLITE_OMIT_AUTHORIZATION
80090   /* Invoke the authorization callback. */
80091   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
80092     goto exit_rename_table;
80093   }
80094 #endif
80095
80096 #ifndef SQLITE_OMIT_VIRTUALTABLE
80097   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
80098     goto exit_rename_table;
80099   }
80100   if( IsVirtual(pTab) ){
80101     pVTab = sqlite3GetVTable(db, pTab);
80102     if( pVTab->pVtab->pModule->xRename==0 ){
80103       pVTab = 0;
80104     }
80105   }
80106 #endif
80107
80108   /* Begin a transaction and code the VerifyCookie for database iDb.
80109   ** Then modify the schema cookie (since the ALTER TABLE modifies the
80110   ** schema). Open a statement transaction if the table is a virtual
80111   ** table.
80112   */
80113   v = sqlite3GetVdbe(pParse);
80114   if( v==0 ){
80115     goto exit_rename_table;
80116   }
80117   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
80118   sqlite3ChangeCookie(pParse, iDb);
80119
80120   /* If this is a virtual table, invoke the xRename() function if
80121   ** one is defined. The xRename() callback will modify the names
80122   ** of any resources used by the v-table implementation (including other
80123   ** SQLite tables) that are identified by the name of the virtual table.
80124   */
80125 #ifndef SQLITE_OMIT_VIRTUALTABLE
80126   if( pVTab ){
80127     int i = ++pParse->nMem;
80128     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
80129     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
80130     sqlite3MayAbort(pParse);
80131   }
80132 #endif
80133
80134   /* figure out how many UTF-8 characters are in zName */
80135   zTabName = pTab->zName;
80136   nTabName = sqlite3Utf8CharLen(zTabName, -1);
80137
80138 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
80139   if( db->flags&SQLITE_ForeignKeys ){
80140     /* If foreign-key support is enabled, rewrite the CREATE TABLE
80141     ** statements corresponding to all child tables of foreign key constraints
80142     ** for which the renamed table is the parent table.  */
80143     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
80144       sqlite3NestedParse(pParse,
80145           "UPDATE \"%w\".%s SET "
80146               "sql = sqlite_rename_parent(sql, %Q, %Q) "
80147               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
80148       sqlite3DbFree(db, zWhere);
80149     }
80150   }
80151 #endif
80152
80153   /* Modify the sqlite_master table to use the new table name. */
80154   sqlite3NestedParse(pParse,
80155       "UPDATE %Q.%s SET "
80156 #ifdef SQLITE_OMIT_TRIGGER
80157           "sql = sqlite_rename_table(sql, %Q), "
80158 #else
80159           "sql = CASE "
80160             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
80161             "ELSE sqlite_rename_table(sql, %Q) END, "
80162 #endif
80163           "tbl_name = %Q, "
80164           "name = CASE "
80165             "WHEN type='table' THEN %Q "
80166             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
80167              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
80168             "ELSE name END "
80169       "WHERE tbl_name=%Q COLLATE nocase AND "
80170           "(type='table' OR type='index' OR type='trigger');",
80171       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
80172 #ifndef SQLITE_OMIT_TRIGGER
80173       zName,
80174 #endif
80175       zName, nTabName, zTabName
80176   );
80177
80178 #ifndef SQLITE_OMIT_AUTOINCREMENT
80179   /* If the sqlite_sequence table exists in this database, then update
80180   ** it with the new table name.
80181   */
80182   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
80183     sqlite3NestedParse(pParse,
80184         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
80185         zDb, zName, pTab->zName);
80186   }
80187 #endif
80188
80189 #ifndef SQLITE_OMIT_TRIGGER
80190   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
80191   ** table. Don't do this if the table being ALTERed is itself located in
80192   ** the temp database.
80193   */
80194   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
80195     sqlite3NestedParse(pParse,
80196         "UPDATE sqlite_temp_master SET "
80197             "sql = sqlite_rename_trigger(sql, %Q), "
80198             "tbl_name = %Q "
80199             "WHERE %s;", zName, zName, zWhere);
80200     sqlite3DbFree(db, zWhere);
80201   }
80202 #endif
80203
80204 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
80205   if( db->flags&SQLITE_ForeignKeys ){
80206     FKey *p;
80207     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
80208       Table *pFrom = p->pFrom;
80209       if( pFrom!=pTab ){
80210         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
80211       }
80212     }
80213   }
80214 #endif
80215
80216   /* Drop and reload the internal table schema. */
80217   reloadTableSchema(pParse, pTab, zName);
80218
80219 exit_rename_table:
80220   sqlite3SrcListDelete(db, pSrc);
80221   sqlite3DbFree(db, zName);
80222   db->flags = savedDbFlags;
80223 }
80224
80225
80226 /*
80227 ** Generate code to make sure the file format number is at least minFormat.
80228 ** The generated code will increase the file format number if necessary.
80229 */
80230 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
80231   Vdbe *v;
80232   v = sqlite3GetVdbe(pParse);
80233   /* The VDBE should have been allocated before this routine is called.
80234   ** If that allocation failed, we would have quit before reaching this
80235   ** point */
80236   if( ALWAYS(v) ){
80237     int r1 = sqlite3GetTempReg(pParse);
80238     int r2 = sqlite3GetTempReg(pParse);
80239     int j1;
80240     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
80241     sqlite3VdbeUsesBtree(v, iDb);
80242     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
80243     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
80244     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
80245     sqlite3VdbeJumpHere(v, j1);
80246     sqlite3ReleaseTempReg(pParse, r1);
80247     sqlite3ReleaseTempReg(pParse, r2);
80248   }
80249 }
80250
80251 /*
80252 ** This function is called after an "ALTER TABLE ... ADD" statement
80253 ** has been parsed. Argument pColDef contains the text of the new
80254 ** column definition.
80255 **
80256 ** The Table structure pParse->pNewTable was extended to include
80257 ** the new column during parsing.
80258 */
80259 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
80260   Table *pNew;              /* Copy of pParse->pNewTable */
80261   Table *pTab;              /* Table being altered */
80262   int iDb;                  /* Database number */
80263   const char *zDb;          /* Database name */
80264   const char *zTab;         /* Table name */
80265   char *zCol;               /* Null-terminated column definition */
80266   Column *pCol;             /* The new column */
80267   Expr *pDflt;              /* Default value for the new column */
80268   sqlite3 *db;              /* The database connection; */
80269
80270   db = pParse->db;
80271   if( pParse->nErr || db->mallocFailed ) return;
80272   pNew = pParse->pNewTable;
80273   assert( pNew );
80274
80275   assert( sqlite3BtreeHoldsAllMutexes(db) );
80276   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
80277   zDb = db->aDb[iDb].zName;
80278   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
80279   pCol = &pNew->aCol[pNew->nCol-1];
80280   pDflt = pCol->pDflt;
80281   pTab = sqlite3FindTable(db, zTab, zDb);
80282   assert( pTab );
80283
80284 #ifndef SQLITE_OMIT_AUTHORIZATION
80285   /* Invoke the authorization callback. */
80286   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
80287     return;
80288   }
80289 #endif
80290
80291   /* If the default value for the new column was specified with a
80292   ** literal NULL, then set pDflt to 0. This simplifies checking
80293   ** for an SQL NULL default below.
80294   */
80295   if( pDflt && pDflt->op==TK_NULL ){
80296     pDflt = 0;
80297   }
80298
80299   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
80300   ** If there is a NOT NULL constraint, then the default value for the
80301   ** column must not be NULL.
80302   */
80303   if( pCol->colFlags & COLFLAG_PRIMKEY ){
80304     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
80305     return;
80306   }
80307   if( pNew->pIndex ){
80308     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
80309     return;
80310   }
80311   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
80312     sqlite3ErrorMsg(pParse,
80313         "Cannot add a REFERENCES column with non-NULL default value");
80314     return;
80315   }
80316   if( pCol->notNull && !pDflt ){
80317     sqlite3ErrorMsg(pParse,
80318         "Cannot add a NOT NULL column with default value NULL");
80319     return;
80320   }
80321
80322   /* Ensure the default expression is something that sqlite3ValueFromExpr()
80323   ** can handle (i.e. not CURRENT_TIME etc.)
80324   */
80325   if( pDflt ){
80326     sqlite3_value *pVal;
80327     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
80328       db->mallocFailed = 1;
80329       return;
80330     }
80331     if( !pVal ){
80332       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
80333       return;
80334     }
80335     sqlite3ValueFree(pVal);
80336   }
80337
80338   /* Modify the CREATE TABLE statement. */
80339   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
80340   if( zCol ){
80341     char *zEnd = &zCol[pColDef->n-1];
80342     int savedDbFlags = db->flags;
80343     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
80344       *zEnd-- = '\0';
80345     }
80346     db->flags |= SQLITE_PreferBuiltin;
80347     sqlite3NestedParse(pParse,
80348         "UPDATE \"%w\".%s SET "
80349           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
80350         "WHERE type = 'table' AND name = %Q",
80351       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
80352       zTab
80353     );
80354     sqlite3DbFree(db, zCol);
80355     db->flags = savedDbFlags;
80356   }
80357
80358   /* If the default value of the new column is NULL, then set the file
80359   ** format to 2. If the default value of the new column is not NULL,
80360   ** the file format becomes 3.
80361   */
80362   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
80363
80364   /* Reload the schema of the modified table. */
80365   reloadTableSchema(pParse, pTab, pTab->zName);
80366 }
80367
80368 /*
80369 ** This function is called by the parser after the table-name in
80370 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
80371 ** pSrc is the full-name of the table being altered.
80372 **
80373 ** This routine makes a (partial) copy of the Table structure
80374 ** for the table being altered and sets Parse.pNewTable to point
80375 ** to it. Routines called by the parser as the column definition
80376 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
80377 ** the copy. The copy of the Table structure is deleted by tokenize.c
80378 ** after parsing is finished.
80379 **
80380 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
80381 ** coding the "ALTER TABLE ... ADD" statement.
80382 */
80383 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
80384   Table *pNew;
80385   Table *pTab;
80386   Vdbe *v;
80387   int iDb;
80388   int i;
80389   int nAlloc;
80390   sqlite3 *db = pParse->db;
80391
80392   /* Look up the table being altered. */
80393   assert( pParse->pNewTable==0 );
80394   assert( sqlite3BtreeHoldsAllMutexes(db) );
80395   if( db->mallocFailed ) goto exit_begin_add_column;
80396   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
80397   if( !pTab ) goto exit_begin_add_column;
80398
80399 #ifndef SQLITE_OMIT_VIRTUALTABLE
80400   if( IsVirtual(pTab) ){
80401     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
80402     goto exit_begin_add_column;
80403   }
80404 #endif
80405
80406   /* Make sure this is not an attempt to ALTER a view. */
80407   if( pTab->pSelect ){
80408     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
80409     goto exit_begin_add_column;
80410   }
80411   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
80412     goto exit_begin_add_column;
80413   }
80414
80415   assert( pTab->addColOffset>0 );
80416   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80417
80418   /* Put a copy of the Table struct in Parse.pNewTable for the
80419   ** sqlite3AddColumn() function and friends to modify.  But modify
80420   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
80421   ** prefix, we insure that the name will not collide with an existing
80422   ** table because user table are not allowed to have the "sqlite_"
80423   ** prefix on their name.
80424   */
80425   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
80426   if( !pNew ) goto exit_begin_add_column;
80427   pParse->pNewTable = pNew;
80428   pNew->nRef = 1;
80429   pNew->nCol = pTab->nCol;
80430   assert( pNew->nCol>0 );
80431   nAlloc = (((pNew->nCol-1)/8)*8)+8;
80432   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
80433   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
80434   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
80435   if( !pNew->aCol || !pNew->zName ){
80436     db->mallocFailed = 1;
80437     goto exit_begin_add_column;
80438   }
80439   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
80440   for(i=0; i<pNew->nCol; i++){
80441     Column *pCol = &pNew->aCol[i];
80442     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
80443     pCol->zColl = 0;
80444     pCol->zType = 0;
80445     pCol->pDflt = 0;
80446     pCol->zDflt = 0;
80447   }
80448   pNew->pSchema = db->aDb[iDb].pSchema;
80449   pNew->addColOffset = pTab->addColOffset;
80450   pNew->nRef = 1;
80451
80452   /* Begin a transaction and increment the schema cookie.  */
80453   sqlite3BeginWriteOperation(pParse, 0, iDb);
80454   v = sqlite3GetVdbe(pParse);
80455   if( !v ) goto exit_begin_add_column;
80456   sqlite3ChangeCookie(pParse, iDb);
80457
80458 exit_begin_add_column:
80459   sqlite3SrcListDelete(db, pSrc);
80460   return;
80461 }
80462 #endif  /* SQLITE_ALTER_TABLE */
80463
80464 /************** End of alter.c ***********************************************/
80465 /************** Begin file analyze.c *****************************************/
80466 /*
80467 ** 2005 July 8
80468 **
80469 ** The author disclaims copyright to this source code.  In place of
80470 ** a legal notice, here is a blessing:
80471 **
80472 **    May you do good and not evil.
80473 **    May you find forgiveness for yourself and forgive others.
80474 **    May you share freely, never taking more than you give.
80475 **
80476 *************************************************************************
80477 ** This file contains code associated with the ANALYZE command.
80478 **
80479 ** The ANALYZE command gather statistics about the content of tables
80480 ** and indices.  These statistics are made available to the query planner
80481 ** to help it make better decisions about how to perform queries.
80482 **
80483 ** The following system tables are or have been supported:
80484 **
80485 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
80486 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
80487 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
80488 **
80489 ** Additional tables might be added in future releases of SQLite.
80490 ** The sqlite_stat2 table is not created or used unless the SQLite version
80491 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80492 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
80493 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
80494 ** created and used by SQLite versions 3.7.9 and later and with
80495 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
80496 ** is a superset of sqlite_stat2.
80497 **
80498 ** Format of sqlite_stat1:
80499 **
80500 ** There is normally one row per index, with the index identified by the
80501 ** name in the idx column.  The tbl column is the name of the table to
80502 ** which the index belongs.  In each such row, the stat column will be
80503 ** a string consisting of a list of integers.  The first integer in this
80504 ** list is the number of rows in the index and in the table.  The second
80505 ** integer is the average number of rows in the index that have the same
80506 ** value in the first column of the index.  The third integer is the average
80507 ** number of rows in the index that have the same value for the first two
80508 ** columns.  The N-th integer (for N>1) is the average number of rows in
80509 ** the index which have the same value for the first N-1 columns.  For
80510 ** a K-column index, there will be K+1 integers in the stat column.  If
80511 ** the index is unique, then the last integer will be 1.
80512 **
80513 ** The list of integers in the stat column can optionally be followed
80514 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
80515 ** must be separated from the last integer by a single space.  If the
80516 ** "unordered" keyword is present, then the query planner assumes that
80517 ** the index is unordered and will not use the index for a range query.
80518 **
80519 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
80520 ** column contains a single integer which is the (estimated) number of
80521 ** rows in the table identified by sqlite_stat1.tbl.
80522 **
80523 ** Format of sqlite_stat2:
80524 **
80525 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
80526 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
80527 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
80528 ** about the distribution of keys within an index.  The index is identified by
80529 ** the "idx" column and the "tbl" column is the name of the table to which
80530 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
80531 ** table for each index.
80532 **
80533 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
80534 ** inclusive are samples of the left-most key value in the index taken at
80535 ** evenly spaced points along the index.  Let the number of samples be S
80536 ** (10 in the standard build) and let C be the number of rows in the index.
80537 ** Then the sampled rows are given by:
80538 **
80539 **     rownumber = (i*C*2 + C)/(S*2)
80540 **
80541 ** For i between 0 and S-1.  Conceptually, the index space is divided into
80542 ** S uniform buckets and the samples are the middle row from each bucket.
80543 **
80544 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
80545 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
80546 ** writes the sqlite_stat2 table.  This version of SQLite only supports
80547 ** sqlite_stat3.
80548 **
80549 ** Format for sqlite_stat3:
80550 **
80551 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
80552 ** used to avoid compatibility problems.
80553 **
80554 ** The format of the sqlite_stat3 table is similar to the format of
80555 ** the sqlite_stat2 table.  There are multiple entries for each index.
80556 ** The idx column names the index and the tbl column is the table of the
80557 ** index.  If the idx and tbl columns are the same, then the sample is
80558 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
80559 ** the left-most column of the index.  The nEq column is the approximate
80560 ** number of entires in the index whose left-most column exactly matches
80561 ** the sample.  nLt is the approximate number of entires whose left-most
80562 ** column is less than the sample.  The nDLt column is the approximate
80563 ** number of distinct left-most entries in the index that are less than
80564 ** the sample.
80565 **
80566 ** Future versions of SQLite might change to store a string containing
80567 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
80568 ** integer will be the number of prior index entires that are distinct in
80569 ** the left-most column.  The second integer will be the number of prior index
80570 ** entries that are distinct in the first two columns.  The third integer
80571 ** will be the number of prior index entries that are distinct in the first
80572 ** three columns.  And so forth.  With that extension, the nDLt field is
80573 ** similar in function to the sqlite_stat1.stat field.
80574 **
80575 ** There can be an arbitrary number of sqlite_stat3 entries per index.
80576 ** The ANALYZE command will typically generate sqlite_stat3 tables
80577 ** that contain between 10 and 40 samples which are distributed across
80578 ** the key space, though not uniformly, and which include samples with
80579 ** largest possible nEq values.
80580 */
80581 #ifndef SQLITE_OMIT_ANALYZE
80582
80583 /*
80584 ** This routine generates code that opens the sqlite_stat1 table for
80585 ** writing with cursor iStatCur. If the library was built with the
80586 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
80587 ** opened for writing using cursor (iStatCur+1)
80588 **
80589 ** If the sqlite_stat1 tables does not previously exist, it is created.
80590 ** Similarly, if the sqlite_stat3 table does not exist and the library
80591 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
80592 **
80593 ** Argument zWhere may be a pointer to a buffer containing a table name,
80594 ** or it may be a NULL pointer. If it is not NULL, then all entries in
80595 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
80596 ** with the named table are deleted. If zWhere==0, then code is generated
80597 ** to delete all stat table entries.
80598 */
80599 static void openStatTable(
80600   Parse *pParse,          /* Parsing context */
80601   int iDb,                /* The database we are looking in */
80602   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
80603   const char *zWhere,     /* Delete entries for this table or index */
80604   const char *zWhereType  /* Either "tbl" or "idx" */
80605 ){
80606   static const struct {
80607     const char *zName;
80608     const char *zCols;
80609   } aTable[] = {
80610     { "sqlite_stat1", "tbl,idx,stat" },
80611 #ifdef SQLITE_ENABLE_STAT3
80612     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
80613 #endif
80614   };
80615
80616   int aRoot[] = {0, 0};
80617   u8 aCreateTbl[] = {0, 0};
80618
80619   int i;
80620   sqlite3 *db = pParse->db;
80621   Db *pDb;
80622   Vdbe *v = sqlite3GetVdbe(pParse);
80623   if( v==0 ) return;
80624   assert( sqlite3BtreeHoldsAllMutexes(db) );
80625   assert( sqlite3VdbeDb(v)==db );
80626   pDb = &db->aDb[iDb];
80627
80628   /* Create new statistic tables if they do not exist, or clear them
80629   ** if they do already exist.
80630   */
80631   for(i=0; i<ArraySize(aTable); i++){
80632     const char *zTab = aTable[i].zName;
80633     Table *pStat;
80634     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
80635       /* The sqlite_stat[12] table does not exist. Create it. Note that a
80636       ** side-effect of the CREATE TABLE statement is to leave the rootpage
80637       ** of the new table in register pParse->regRoot. This is important
80638       ** because the OpenWrite opcode below will be needing it. */
80639       sqlite3NestedParse(pParse,
80640           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
80641       );
80642       aRoot[i] = pParse->regRoot;
80643       aCreateTbl[i] = OPFLAG_P2ISREG;
80644     }else{
80645       /* The table already exists. If zWhere is not NULL, delete all entries
80646       ** associated with the table zWhere. If zWhere is NULL, delete the
80647       ** entire contents of the table. */
80648       aRoot[i] = pStat->tnum;
80649       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
80650       if( zWhere ){
80651         sqlite3NestedParse(pParse,
80652            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
80653         );
80654       }else{
80655         /* The sqlite_stat[12] table already exists.  Delete all rows. */
80656         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
80657       }
80658     }
80659   }
80660
80661   /* Open the sqlite_stat[13] tables for writing. */
80662   for(i=0; i<ArraySize(aTable); i++){
80663     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
80664     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
80665     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
80666   }
80667 }
80668
80669 /*
80670 ** Recommended number of samples for sqlite_stat3
80671 */
80672 #ifndef SQLITE_STAT3_SAMPLES
80673 # define SQLITE_STAT3_SAMPLES 24
80674 #endif
80675
80676 /*
80677 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
80678 ** share an instance of the following structure to hold their state
80679 ** information.
80680 */
80681 typedef struct Stat3Accum Stat3Accum;
80682 struct Stat3Accum {
80683   tRowcnt nRow;             /* Number of rows in the entire table */
80684   tRowcnt nPSample;         /* How often to do a periodic sample */
80685   int iMin;                 /* Index of entry with minimum nEq and hash */
80686   int mxSample;             /* Maximum number of samples to accumulate */
80687   int nSample;              /* Current number of samples */
80688   u32 iPrn;                 /* Pseudo-random number used for sampling */
80689   struct Stat3Sample {
80690     i64 iRowid;                /* Rowid in main table of the key */
80691     tRowcnt nEq;               /* sqlite_stat3.nEq */
80692     tRowcnt nLt;               /* sqlite_stat3.nLt */
80693     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
80694     u8 isPSample;              /* True if a periodic sample */
80695     u32 iHash;                 /* Tiebreaker hash */
80696   } *a;                     /* An array of samples */
80697 };
80698
80699 #ifdef SQLITE_ENABLE_STAT3
80700 /*
80701 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
80702 ** are the number of rows in the table or index (C) and the number of samples
80703 ** to accumulate (S).
80704 **
80705 ** This routine allocates the Stat3Accum object.
80706 **
80707 ** The return value is the Stat3Accum object (P).
80708 */
80709 static void stat3Init(
80710   sqlite3_context *context,
80711   int argc,
80712   sqlite3_value **argv
80713 ){
80714   Stat3Accum *p;
80715   tRowcnt nRow;
80716   int mxSample;
80717   int n;
80718
80719   UNUSED_PARAMETER(argc);
80720   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
80721   mxSample = sqlite3_value_int(argv[1]);
80722   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
80723   p = sqlite3MallocZero( n );
80724   if( p==0 ){
80725     sqlite3_result_error_nomem(context);
80726     return;
80727   }
80728   p->a = (struct Stat3Sample*)&p[1];
80729   p->nRow = nRow;
80730   p->mxSample = mxSample;
80731   p->nPSample = p->nRow/(mxSample/3+1) + 1;
80732   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
80733   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
80734 }
80735 static const FuncDef stat3InitFuncdef = {
80736   2,                /* nArg */
80737   SQLITE_UTF8,      /* iPrefEnc */
80738   0,                /* flags */
80739   0,                /* pUserData */
80740   0,                /* pNext */
80741   stat3Init,        /* xFunc */
80742   0,                /* xStep */
80743   0,                /* xFinalize */
80744   "stat3_init",     /* zName */
80745   0,                /* pHash */
80746   0                 /* pDestructor */
80747 };
80748
80749
80750 /*
80751 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
80752 ** arguments describe a single key instance.  This routine makes the
80753 ** decision about whether or not to retain this key for the sqlite_stat3
80754 ** table.
80755 **
80756 ** The return value is NULL.
80757 */
80758 static void stat3Push(
80759   sqlite3_context *context,
80760   int argc,
80761   sqlite3_value **argv
80762 ){
80763   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
80764   tRowcnt nEq = sqlite3_value_int64(argv[0]);
80765   tRowcnt nLt = sqlite3_value_int64(argv[1]);
80766   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
80767   i64 rowid = sqlite3_value_int64(argv[3]);
80768   u8 isPSample = 0;
80769   u8 doInsert = 0;
80770   int iMin = p->iMin;
80771   struct Stat3Sample *pSample;
80772   int i;
80773   u32 h;
80774
80775   UNUSED_PARAMETER(context);
80776   UNUSED_PARAMETER(argc);
80777   if( nEq==0 ) return;
80778   h = p->iPrn = p->iPrn*1103515245 + 12345;
80779   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
80780     doInsert = isPSample = 1;
80781   }else if( p->nSample<p->mxSample ){
80782     doInsert = 1;
80783   }else{
80784     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
80785       doInsert = 1;
80786     }
80787   }
80788   if( !doInsert ) return;
80789   if( p->nSample==p->mxSample ){
80790     assert( p->nSample - iMin - 1 >= 0 );
80791     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
80792     pSample = &p->a[p->nSample-1];
80793   }else{
80794     pSample = &p->a[p->nSample++];
80795   }
80796   pSample->iRowid = rowid;
80797   pSample->nEq = nEq;
80798   pSample->nLt = nLt;
80799   pSample->nDLt = nDLt;
80800   pSample->iHash = h;
80801   pSample->isPSample = isPSample;
80802
80803   /* Find the new minimum */
80804   if( p->nSample==p->mxSample ){
80805     pSample = p->a;
80806     i = 0;
80807     while( pSample->isPSample ){
80808       i++;
80809       pSample++;
80810       assert( i<p->nSample );
80811     }
80812     nEq = pSample->nEq;
80813     h = pSample->iHash;
80814     iMin = i;
80815     for(i++, pSample++; i<p->nSample; i++, pSample++){
80816       if( pSample->isPSample ) continue;
80817       if( pSample->nEq<nEq
80818        || (pSample->nEq==nEq && pSample->iHash<h)
80819       ){
80820         iMin = i;
80821         nEq = pSample->nEq;
80822         h = pSample->iHash;
80823       }
80824     }
80825     p->iMin = iMin;
80826   }
80827 }
80828 static const FuncDef stat3PushFuncdef = {
80829   5,                /* nArg */
80830   SQLITE_UTF8,      /* iPrefEnc */
80831   0,                /* flags */
80832   0,                /* pUserData */
80833   0,                /* pNext */
80834   stat3Push,        /* xFunc */
80835   0,                /* xStep */
80836   0,                /* xFinalize */
80837   "stat3_push",     /* zName */
80838   0,                /* pHash */
80839   0                 /* pDestructor */
80840 };
80841
80842 /*
80843 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
80844 ** used to query the results.  Content is returned for the Nth sqlite_stat3
80845 ** row where N is between 0 and S-1 and S is the number of samples.  The
80846 ** value returned depends on the number of arguments.
80847 **
80848 **   argc==2    result:  rowid
80849 **   argc==3    result:  nEq
80850 **   argc==4    result:  nLt
80851 **   argc==5    result:  nDLt
80852 */
80853 static void stat3Get(
80854   sqlite3_context *context,
80855   int argc,
80856   sqlite3_value **argv
80857 ){
80858   int n = sqlite3_value_int(argv[1]);
80859   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
80860
80861   assert( p!=0 );
80862   if( p->nSample<=n ) return;
80863   switch( argc ){
80864     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
80865     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
80866     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
80867     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
80868   }
80869 }
80870 static const FuncDef stat3GetFuncdef = {
80871   -1,               /* nArg */
80872   SQLITE_UTF8,      /* iPrefEnc */
80873   0,                /* flags */
80874   0,                /* pUserData */
80875   0,                /* pNext */
80876   stat3Get,         /* xFunc */
80877   0,                /* xStep */
80878   0,                /* xFinalize */
80879   "stat3_get",     /* zName */
80880   0,                /* pHash */
80881   0                 /* pDestructor */
80882 };
80883 #endif /* SQLITE_ENABLE_STAT3 */
80884
80885
80886
80887
80888 /*
80889 ** Generate code to do an analysis of all indices associated with
80890 ** a single table.
80891 */
80892 static void analyzeOneTable(
80893   Parse *pParse,   /* Parser context */
80894   Table *pTab,     /* Table whose indices are to be analyzed */
80895   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
80896   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
80897   int iMem         /* Available memory locations begin here */
80898 ){
80899   sqlite3 *db = pParse->db;    /* Database handle */
80900   Index *pIdx;                 /* An index to being analyzed */
80901   int iIdxCur;                 /* Cursor open on index being analyzed */
80902   Vdbe *v;                     /* The virtual machine being built up */
80903   int i;                       /* Loop counter */
80904   int topOfLoop;               /* The top of the loop */
80905   int endOfLoop;               /* The end of the loop */
80906   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
80907   int iDb;                     /* Index of database containing pTab */
80908   int regTabname = iMem++;     /* Register containing table name */
80909   int regIdxname = iMem++;     /* Register containing index name */
80910   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
80911 #ifdef SQLITE_ENABLE_STAT3
80912   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
80913   int regNumLt = iMem++;       /* Number of keys less than regSample */
80914   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
80915   int regSample = iMem++;      /* The next sample value */
80916   int regRowid = regSample;    /* Rowid of a sample */
80917   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
80918   int regLoop = iMem++;        /* Loop counter */
80919   int regCount = iMem++;       /* Number of rows in the table or index */
80920   int regTemp1 = iMem++;       /* Intermediate register */
80921   int regTemp2 = iMem++;       /* Intermediate register */
80922   int once = 1;                /* One-time initialization */
80923   int shortJump = 0;           /* Instruction address */
80924   int iTabCur = pParse->nTab++; /* Table cursor */
80925 #endif
80926   int regCol = iMem++;         /* Content of a column in analyzed table */
80927   int regRec = iMem++;         /* Register holding completed record */
80928   int regTemp = iMem++;        /* Temporary use register */
80929   int regNewRowid = iMem++;    /* Rowid for the inserted record */
80930
80931
80932   v = sqlite3GetVdbe(pParse);
80933   if( v==0 || NEVER(pTab==0) ){
80934     return;
80935   }
80936   if( pTab->tnum==0 ){
80937     /* Do not gather statistics on views or virtual tables */
80938     return;
80939   }
80940   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
80941     /* Do not gather statistics on system tables */
80942     return;
80943   }
80944   assert( sqlite3BtreeHoldsAllMutexes(db) );
80945   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80946   assert( iDb>=0 );
80947   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80948 #ifndef SQLITE_OMIT_AUTHORIZATION
80949   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
80950       db->aDb[iDb].zName ) ){
80951     return;
80952   }
80953 #endif
80954
80955   /* Establish a read-lock on the table at the shared-cache level. */
80956   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
80957
80958   iIdxCur = pParse->nTab++;
80959   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
80960   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
80961     int nCol;
80962     KeyInfo *pKey;
80963     int addrIfNot = 0;           /* address of OP_IfNot */
80964     int *aChngAddr;              /* Array of jump instruction addresses */
80965
80966     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
80967     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
80968     nCol = pIdx->nColumn;
80969     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
80970     if( aChngAddr==0 ) continue;
80971     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
80972     if( iMem+1+(nCol*2)>pParse->nMem ){
80973       pParse->nMem = iMem+1+(nCol*2);
80974     }
80975
80976     /* Open a cursor to the index to be analyzed. */
80977     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
80978     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
80979         (char *)pKey, P4_KEYINFO_HANDOFF);
80980     VdbeComment((v, "%s", pIdx->zName));
80981
80982     /* Populate the register containing the index name. */
80983     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
80984
80985 #ifdef SQLITE_ENABLE_STAT3
80986     if( once ){
80987       once = 0;
80988       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
80989     }
80990     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
80991     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
80992     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
80993     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
80994     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
80995     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
80996     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
80997                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
80998     sqlite3VdbeChangeP5(v, 2);
80999 #endif /* SQLITE_ENABLE_STAT3 */
81000
81001     /* The block of memory cells initialized here is used as follows.
81002     **
81003     **    iMem:
81004     **        The total number of rows in the table.
81005     **
81006     **    iMem+1 .. iMem+nCol:
81007     **        Number of distinct entries in index considering the
81008     **        left-most N columns only, where N is between 1 and nCol,
81009     **        inclusive.
81010     **
81011     **    iMem+nCol+1 .. Mem+2*nCol:
81012     **        Previous value of indexed columns, from left to right.
81013     **
81014     ** Cells iMem through iMem+nCol are initialized to 0. The others are
81015     ** initialized to contain an SQL NULL.
81016     */
81017     for(i=0; i<=nCol; i++){
81018       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
81019     }
81020     for(i=0; i<nCol; i++){
81021       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
81022     }
81023
81024     /* Start the analysis loop. This loop runs through all the entries in
81025     ** the index b-tree.  */
81026     endOfLoop = sqlite3VdbeMakeLabel(v);
81027     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
81028     topOfLoop = sqlite3VdbeCurrentAddr(v);
81029     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
81030
81031     for(i=0; i<nCol; i++){
81032       CollSeq *pColl;
81033       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
81034       if( i==0 ){
81035         /* Always record the very first row */
81036         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
81037       }
81038       assert( pIdx->azColl!=0 );
81039       assert( pIdx->azColl[i]!=0 );
81040       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
81041       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
81042                                       (char*)pColl, P4_COLLSEQ);
81043       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
81044       VdbeComment((v, "jump if column %d changed", i));
81045 #ifdef SQLITE_ENABLE_STAT3
81046       if( i==0 ){
81047         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
81048         VdbeComment((v, "incr repeat count"));
81049       }
81050 #endif
81051     }
81052     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
81053     for(i=0; i<nCol; i++){
81054       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
81055       if( i==0 ){
81056         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
81057 #ifdef SQLITE_ENABLE_STAT3
81058         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
81059                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
81060         sqlite3VdbeChangeP5(v, 5);
81061         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
81062         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
81063         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
81064         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
81065 #endif
81066       }
81067       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
81068       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
81069     }
81070     sqlite3DbFree(db, aChngAddr);
81071
81072     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
81073     sqlite3VdbeResolveLabel(v, endOfLoop);
81074
81075     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
81076     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
81077 #ifdef SQLITE_ENABLE_STAT3
81078     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
81079                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
81080     sqlite3VdbeChangeP5(v, 5);
81081     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
81082     shortJump =
81083     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
81084     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
81085                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
81086     sqlite3VdbeChangeP5(v, 2);
81087     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
81088     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
81089     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
81090     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
81091     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
81092                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
81093     sqlite3VdbeChangeP5(v, 3);
81094     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
81095                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
81096     sqlite3VdbeChangeP5(v, 4);
81097     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
81098                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
81099     sqlite3VdbeChangeP5(v, 5);
81100     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
81101     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
81102     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
81103     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
81104     sqlite3VdbeJumpHere(v, shortJump+2);
81105 #endif
81106
81107     /* Store the results in sqlite_stat1.
81108     **
81109     ** The result is a single row of the sqlite_stat1 table.  The first
81110     ** two columns are the names of the table and index.  The third column
81111     ** is a string composed of a list of integer statistics about the
81112     ** index.  The first integer in the list is the total number of entries
81113     ** in the index.  There is one additional integer in the list for each
81114     ** column of the table.  This additional integer is a guess of how many
81115     ** rows of the table the index will select.  If D is the count of distinct
81116     ** values and K is the total number of rows, then the integer is computed
81117     ** as:
81118     **
81119     **        I = (K+D-1)/D
81120     **
81121     ** If K==0 then no entry is made into the sqlite_stat1 table.
81122     ** If K>0 then it is always the case the D>0 so division by zero
81123     ** is never possible.
81124     */
81125     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
81126     if( jZeroRows<0 ){
81127       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
81128     }
81129     for(i=0; i<nCol; i++){
81130       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
81131       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
81132       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
81133       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
81134       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
81135       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
81136       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
81137     }
81138     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
81139     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
81140     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
81141     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81142   }
81143
81144   /* If the table has no indices, create a single sqlite_stat1 entry
81145   ** containing NULL as the index name and the row count as the content.
81146   */
81147   if( pTab->pIndex==0 ){
81148     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
81149     VdbeComment((v, "%s", pTab->zName));
81150     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
81151     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
81152     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
81153   }else{
81154     sqlite3VdbeJumpHere(v, jZeroRows);
81155     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
81156   }
81157   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
81158   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
81159   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
81160   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
81161   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81162   if( pParse->nMem<regRec ) pParse->nMem = regRec;
81163   sqlite3VdbeJumpHere(v, jZeroRows);
81164 }
81165
81166
81167 /*
81168 ** Generate code that will cause the most recent index analysis to
81169 ** be loaded into internal hash tables where is can be used.
81170 */
81171 static void loadAnalysis(Parse *pParse, int iDb){
81172   Vdbe *v = sqlite3GetVdbe(pParse);
81173   if( v ){
81174     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
81175   }
81176 }
81177
81178 /*
81179 ** Generate code that will do an analysis of an entire database
81180 */
81181 static void analyzeDatabase(Parse *pParse, int iDb){
81182   sqlite3 *db = pParse->db;
81183   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
81184   HashElem *k;
81185   int iStatCur;
81186   int iMem;
81187
81188   sqlite3BeginWriteOperation(pParse, 0, iDb);
81189   iStatCur = pParse->nTab;
81190   pParse->nTab += 3;
81191   openStatTable(pParse, iDb, iStatCur, 0, 0);
81192   iMem = pParse->nMem+1;
81193   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81194   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
81195     Table *pTab = (Table*)sqliteHashData(k);
81196     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
81197   }
81198   loadAnalysis(pParse, iDb);
81199 }
81200
81201 /*
81202 ** Generate code that will do an analysis of a single table in
81203 ** a database.  If pOnlyIdx is not NULL then it is a single index
81204 ** in pTab that should be analyzed.
81205 */
81206 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
81207   int iDb;
81208   int iStatCur;
81209
81210   assert( pTab!=0 );
81211   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81212   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81213   sqlite3BeginWriteOperation(pParse, 0, iDb);
81214   iStatCur = pParse->nTab;
81215   pParse->nTab += 3;
81216   if( pOnlyIdx ){
81217     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
81218   }else{
81219     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
81220   }
81221   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
81222   loadAnalysis(pParse, iDb);
81223 }
81224
81225 /*
81226 ** Generate code for the ANALYZE command.  The parser calls this routine
81227 ** when it recognizes an ANALYZE command.
81228 **
81229 **        ANALYZE                            -- 1
81230 **        ANALYZE  <database>                -- 2
81231 **        ANALYZE  ?<database>.?<tablename>  -- 3
81232 **
81233 ** Form 1 causes all indices in all attached databases to be analyzed.
81234 ** Form 2 analyzes all indices the single database named.
81235 ** Form 3 analyzes all indices associated with the named table.
81236 */
81237 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
81238   sqlite3 *db = pParse->db;
81239   int iDb;
81240   int i;
81241   char *z, *zDb;
81242   Table *pTab;
81243   Index *pIdx;
81244   Token *pTableName;
81245
81246   /* Read the database schema. If an error occurs, leave an error message
81247   ** and code in pParse and return NULL. */
81248   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81249   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81250     return;
81251   }
81252
81253   assert( pName2!=0 || pName1==0 );
81254   if( pName1==0 ){
81255     /* Form 1:  Analyze everything */
81256     for(i=0; i<db->nDb; i++){
81257       if( i==1 ) continue;  /* Do not analyze the TEMP database */
81258       analyzeDatabase(pParse, i);
81259     }
81260   }else if( pName2->n==0 ){
81261     /* Form 2:  Analyze the database or table named */
81262     iDb = sqlite3FindDb(db, pName1);
81263     if( iDb>=0 ){
81264       analyzeDatabase(pParse, iDb);
81265     }else{
81266       z = sqlite3NameFromToken(db, pName1);
81267       if( z ){
81268         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
81269           analyzeTable(pParse, pIdx->pTable, pIdx);
81270         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
81271           analyzeTable(pParse, pTab, 0);
81272         }
81273         sqlite3DbFree(db, z);
81274       }
81275     }
81276   }else{
81277     /* Form 3: Analyze the fully qualified table name */
81278     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
81279     if( iDb>=0 ){
81280       zDb = db->aDb[iDb].zName;
81281       z = sqlite3NameFromToken(db, pTableName);
81282       if( z ){
81283         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
81284           analyzeTable(pParse, pIdx->pTable, pIdx);
81285         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
81286           analyzeTable(pParse, pTab, 0);
81287         }
81288         sqlite3DbFree(db, z);
81289       }
81290     }
81291   }
81292 }
81293
81294 /*
81295 ** Used to pass information from the analyzer reader through to the
81296 ** callback routine.
81297 */
81298 typedef struct analysisInfo analysisInfo;
81299 struct analysisInfo {
81300   sqlite3 *db;
81301   const char *zDatabase;
81302 };
81303
81304 /*
81305 ** This callback is invoked once for each index when reading the
81306 ** sqlite_stat1 table.
81307 **
81308 **     argv[0] = name of the table
81309 **     argv[1] = name of the index (might be NULL)
81310 **     argv[2] = results of analysis - on integer for each column
81311 **
81312 ** Entries for which argv[1]==NULL simply record the number of rows in
81313 ** the table.
81314 */
81315 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
81316   analysisInfo *pInfo = (analysisInfo*)pData;
81317   Index *pIndex;
81318   Table *pTable;
81319   int i, c, n;
81320   tRowcnt v;
81321   const char *z;
81322
81323   assert( argc==3 );
81324   UNUSED_PARAMETER2(NotUsed, argc);
81325
81326   if( argv==0 || argv[0]==0 || argv[2]==0 ){
81327     return 0;
81328   }
81329   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
81330   if( pTable==0 ){
81331     return 0;
81332   }
81333   if( argv[1] ){
81334     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
81335   }else{
81336     pIndex = 0;
81337   }
81338   n = pIndex ? pIndex->nColumn : 0;
81339   z = argv[2];
81340   for(i=0; *z && i<=n; i++){
81341     v = 0;
81342     while( (c=z[0])>='0' && c<='9' ){
81343       v = v*10 + c - '0';
81344       z++;
81345     }
81346     if( i==0 ) pTable->nRowEst = v;
81347     if( pIndex==0 ) break;
81348     pIndex->aiRowEst[i] = v;
81349     if( *z==' ' ) z++;
81350     if( memcmp(z, "unordered", 10)==0 ){
81351       pIndex->bUnordered = 1;
81352       break;
81353     }
81354   }
81355   return 0;
81356 }
81357
81358 /*
81359 ** If the Index.aSample variable is not NULL, delete the aSample[] array
81360 ** and its contents.
81361 */
81362 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
81363 #ifdef SQLITE_ENABLE_STAT3
81364   if( pIdx->aSample ){
81365     int j;
81366     for(j=0; j<pIdx->nSample; j++){
81367       IndexSample *p = &pIdx->aSample[j];
81368       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
81369         sqlite3DbFree(db, p->u.z);
81370       }
81371     }
81372     sqlite3DbFree(db, pIdx->aSample);
81373   }
81374   if( db && db->pnBytesFreed==0 ){
81375     pIdx->nSample = 0;
81376     pIdx->aSample = 0;
81377   }
81378 #else
81379   UNUSED_PARAMETER(db);
81380   UNUSED_PARAMETER(pIdx);
81381 #endif
81382 }
81383
81384 #ifdef SQLITE_ENABLE_STAT3
81385 /*
81386 ** Load content from the sqlite_stat3 table into the Index.aSample[]
81387 ** arrays of all indices.
81388 */
81389 static int loadStat3(sqlite3 *db, const char *zDb){
81390   int rc;                       /* Result codes from subroutines */
81391   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
81392   char *zSql;                   /* Text of the SQL statement */
81393   Index *pPrevIdx = 0;          /* Previous index in the loop */
81394   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
81395   int eType;                    /* Datatype of a sample */
81396   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
81397
81398   assert( db->lookaside.bEnabled==0 );
81399   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
81400     return SQLITE_OK;
81401   }
81402
81403   zSql = sqlite3MPrintf(db,
81404       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
81405       " GROUP BY idx", zDb);
81406   if( !zSql ){
81407     return SQLITE_NOMEM;
81408   }
81409   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81410   sqlite3DbFree(db, zSql);
81411   if( rc ) return rc;
81412
81413   while( sqlite3_step(pStmt)==SQLITE_ROW ){
81414     char *zIndex;   /* Index name */
81415     Index *pIdx;    /* Pointer to the index object */
81416     int nSample;    /* Number of samples */
81417
81418     zIndex = (char *)sqlite3_column_text(pStmt, 0);
81419     if( zIndex==0 ) continue;
81420     nSample = sqlite3_column_int(pStmt, 1);
81421     pIdx = sqlite3FindIndex(db, zIndex, zDb);
81422     if( pIdx==0 ) continue;
81423     assert( pIdx->nSample==0 );
81424     pIdx->nSample = nSample;
81425     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
81426     pIdx->avgEq = pIdx->aiRowEst[1];
81427     if( pIdx->aSample==0 ){
81428       db->mallocFailed = 1;
81429       sqlite3_finalize(pStmt);
81430       return SQLITE_NOMEM;
81431     }
81432   }
81433   rc = sqlite3_finalize(pStmt);
81434   if( rc ) return rc;
81435
81436   zSql = sqlite3MPrintf(db,
81437       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
81438   if( !zSql ){
81439     return SQLITE_NOMEM;
81440   }
81441   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81442   sqlite3DbFree(db, zSql);
81443   if( rc ) return rc;
81444
81445   while( sqlite3_step(pStmt)==SQLITE_ROW ){
81446     char *zIndex;   /* Index name */
81447     Index *pIdx;    /* Pointer to the index object */
81448     int i;          /* Loop counter */
81449     tRowcnt sumEq;  /* Sum of the nEq values */
81450
81451     zIndex = (char *)sqlite3_column_text(pStmt, 0);
81452     if( zIndex==0 ) continue;
81453     pIdx = sqlite3FindIndex(db, zIndex, zDb);
81454     if( pIdx==0 ) continue;
81455     if( pIdx==pPrevIdx ){
81456       idx++;
81457     }else{
81458       pPrevIdx = pIdx;
81459       idx = 0;
81460     }
81461     assert( idx<pIdx->nSample );
81462     pSample = &pIdx->aSample[idx];
81463     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
81464     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
81465     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
81466     if( idx==pIdx->nSample-1 ){
81467       if( pSample->nDLt>0 ){
81468         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
81469         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
81470       }
81471       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
81472     }
81473     eType = sqlite3_column_type(pStmt, 4);
81474     pSample->eType = (u8)eType;
81475     switch( eType ){
81476       case SQLITE_INTEGER: {
81477         pSample->u.i = sqlite3_column_int64(pStmt, 4);
81478         break;
81479       }
81480       case SQLITE_FLOAT: {
81481         pSample->u.r = sqlite3_column_double(pStmt, 4);
81482         break;
81483       }
81484       case SQLITE_NULL: {
81485         break;
81486       }
81487       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
81488         const char *z = (const char *)(
81489               (eType==SQLITE_BLOB) ?
81490               sqlite3_column_blob(pStmt, 4):
81491               sqlite3_column_text(pStmt, 4)
81492            );
81493         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
81494         pSample->nByte = n;
81495         if( n < 1){
81496           pSample->u.z = 0;
81497         }else{
81498           pSample->u.z = sqlite3DbMallocRaw(db, n);
81499           if( pSample->u.z==0 ){
81500             db->mallocFailed = 1;
81501             sqlite3_finalize(pStmt);
81502             return SQLITE_NOMEM;
81503           }
81504           memcpy(pSample->u.z, z, n);
81505         }
81506       }
81507     }
81508   }
81509   return sqlite3_finalize(pStmt);
81510 }
81511 #endif /* SQLITE_ENABLE_STAT3 */
81512
81513 /*
81514 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
81515 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
81516 ** arrays. The contents of sqlite_stat3 are used to populate the
81517 ** Index.aSample[] arrays.
81518 **
81519 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
81520 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
81521 ** during compilation and the sqlite_stat3 table is present, no data is
81522 ** read from it.
81523 **
81524 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the
81525 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
81526 ** returned. However, in this case, data is read from the sqlite_stat1
81527 ** table (if it is present) before returning.
81528 **
81529 ** If an OOM error occurs, this function always sets db->mallocFailed.
81530 ** This means if the caller does not care about other errors, the return
81531 ** code may be ignored.
81532 */
81533 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
81534   analysisInfo sInfo;
81535   HashElem *i;
81536   char *zSql;
81537   int rc;
81538
81539   assert( iDb>=0 && iDb<db->nDb );
81540   assert( db->aDb[iDb].pBt!=0 );
81541
81542   /* Clear any prior statistics */
81543   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81544   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
81545     Index *pIdx = sqliteHashData(i);
81546     sqlite3DefaultRowEst(pIdx);
81547 #ifdef SQLITE_ENABLE_STAT3
81548     sqlite3DeleteIndexSamples(db, pIdx);
81549     pIdx->aSample = 0;
81550 #endif
81551   }
81552
81553   /* Check to make sure the sqlite_stat1 table exists */
81554   sInfo.db = db;
81555   sInfo.zDatabase = db->aDb[iDb].zName;
81556   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
81557     return SQLITE_ERROR;
81558   }
81559
81560   /* Load new statistics out of the sqlite_stat1 table */
81561   zSql = sqlite3MPrintf(db,
81562       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
81563   if( zSql==0 ){
81564     rc = SQLITE_NOMEM;
81565   }else{
81566     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
81567     sqlite3DbFree(db, zSql);
81568   }
81569
81570
81571   /* Load the statistics from the sqlite_stat3 table. */
81572 #ifdef SQLITE_ENABLE_STAT3
81573   if( rc==SQLITE_OK ){
81574     int lookasideEnabled = db->lookaside.bEnabled;
81575     db->lookaside.bEnabled = 0;
81576     rc = loadStat3(db, sInfo.zDatabase);
81577     db->lookaside.bEnabled = lookasideEnabled;
81578   }
81579 #endif
81580
81581   if( rc==SQLITE_NOMEM ){
81582     db->mallocFailed = 1;
81583   }
81584   return rc;
81585 }
81586
81587
81588 #endif /* SQLITE_OMIT_ANALYZE */
81589
81590 /************** End of analyze.c *********************************************/
81591 /************** Begin file attach.c ******************************************/
81592 /*
81593 ** 2003 April 6
81594 **
81595 ** The author disclaims copyright to this source code.  In place of
81596 ** a legal notice, here is a blessing:
81597 **
81598 **    May you do good and not evil.
81599 **    May you find forgiveness for yourself and forgive others.
81600 **    May you share freely, never taking more than you give.
81601 **
81602 *************************************************************************
81603 ** This file contains code used to implement the ATTACH and DETACH commands.
81604 */
81605
81606 #ifndef SQLITE_OMIT_ATTACH
81607 /*
81608 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
81609 ** is slightly different from resolving a normal SQL expression, because simple
81610 ** identifiers are treated as strings, not possible column names or aliases.
81611 **
81612 ** i.e. if the parser sees:
81613 **
81614 **     ATTACH DATABASE abc AS def
81615 **
81616 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
81617 ** looking for columns of the same name.
81618 **
81619 ** This only applies to the root node of pExpr, so the statement:
81620 **
81621 **     ATTACH DATABASE abc||def AS 'db2'
81622 **
81623 ** will fail because neither abc or def can be resolved.
81624 */
81625 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
81626 {
81627   int rc = SQLITE_OK;
81628   if( pExpr ){
81629     if( pExpr->op!=TK_ID ){
81630       rc = sqlite3ResolveExprNames(pName, pExpr);
81631       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
81632         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
81633         return SQLITE_ERROR;
81634       }
81635     }else{
81636       pExpr->op = TK_STRING;
81637     }
81638   }
81639   return rc;
81640 }
81641
81642 /*
81643 ** An SQL user-function registered to do the work of an ATTACH statement. The
81644 ** three arguments to the function come directly from an attach statement:
81645 **
81646 **     ATTACH DATABASE x AS y KEY z
81647 **
81648 **     SELECT sqlite_attach(x, y, z)
81649 **
81650 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
81651 ** third argument.
81652 */
81653 static void attachFunc(
81654   sqlite3_context *context,
81655   int NotUsed,
81656   sqlite3_value **argv
81657 ){
81658   int i;
81659   int rc = 0;
81660   sqlite3 *db = sqlite3_context_db_handle(context);
81661   const char *zName;
81662   const char *zFile;
81663   char *zPath = 0;
81664   char *zErr = 0;
81665   unsigned int flags;
81666   Db *aNew;
81667   char *zErrDyn = 0;
81668   sqlite3_vfs *pVfs;
81669
81670   UNUSED_PARAMETER(NotUsed);
81671
81672   zFile = (const char *)sqlite3_value_text(argv[0]);
81673   zName = (const char *)sqlite3_value_text(argv[1]);
81674   if( zFile==0 ) zFile = "";
81675   if( zName==0 ) zName = "";
81676
81677   /* Check for the following errors:
81678   **
81679   **     * Too many attached databases,
81680   **     * Transaction currently open
81681   **     * Specified database name already being used.
81682   */
81683   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
81684     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
81685       db->aLimit[SQLITE_LIMIT_ATTACHED]
81686     );
81687     goto attach_error;
81688   }
81689   if( !db->autoCommit ){
81690     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
81691     goto attach_error;
81692   }
81693   for(i=0; i<db->nDb; i++){
81694     char *z = db->aDb[i].zName;
81695     assert( z && zName );
81696     if( sqlite3StrICmp(z, zName)==0 ){
81697       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
81698       goto attach_error;
81699     }
81700   }
81701
81702   /* Allocate the new entry in the db->aDb[] array and initialise the schema
81703   ** hash tables.
81704   */
81705   if( db->aDb==db->aDbStatic ){
81706     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
81707     if( aNew==0 ) return;
81708     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
81709   }else{
81710     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
81711     if( aNew==0 ) return;
81712   }
81713   db->aDb = aNew;
81714   aNew = &db->aDb[db->nDb];
81715   memset(aNew, 0, sizeof(*aNew));
81716
81717   /* Open the database file. If the btree is successfully opened, use
81718   ** it to obtain the database schema. At this point the schema may
81719   ** or may not be initialised.
81720   */
81721   flags = db->openFlags;
81722   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
81723   if( rc!=SQLITE_OK ){
81724     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
81725     sqlite3_result_error(context, zErr, -1);
81726     sqlite3_free(zErr);
81727     return;
81728   }
81729   assert( pVfs );
81730   flags |= SQLITE_OPEN_MAIN_DB;
81731   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
81732   sqlite3_free( zPath );
81733   db->nDb++;
81734   if( rc==SQLITE_CONSTRAINT ){
81735     rc = SQLITE_ERROR;
81736     zErrDyn = sqlite3MPrintf(db, "database is already attached");
81737   }else if( rc==SQLITE_OK ){
81738     Pager *pPager;
81739     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
81740     if( !aNew->pSchema ){
81741       rc = SQLITE_NOMEM;
81742     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
81743       zErrDyn = sqlite3MPrintf(db,
81744         "attached databases must use the same text encoding as main database");
81745       rc = SQLITE_ERROR;
81746     }
81747     pPager = sqlite3BtreePager(aNew->pBt);
81748     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
81749     sqlite3BtreeSecureDelete(aNew->pBt,
81750                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
81751   }
81752   aNew->safety_level = 3;
81753   aNew->zName = sqlite3DbStrDup(db, zName);
81754   if( rc==SQLITE_OK && aNew->zName==0 ){
81755     rc = SQLITE_NOMEM;
81756   }
81757
81758
81759 #ifdef SQLITE_HAS_CODEC
81760   if( rc==SQLITE_OK ){
81761     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
81762     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
81763     int nKey;
81764     char *zKey;
81765     int t = sqlite3_value_type(argv[2]);
81766     switch( t ){
81767       case SQLITE_INTEGER:
81768       case SQLITE_FLOAT:
81769         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
81770         rc = SQLITE_ERROR;
81771         break;
81772
81773       case SQLITE_TEXT:
81774       case SQLITE_BLOB:
81775         nKey = sqlite3_value_bytes(argv[2]);
81776         zKey = (char *)sqlite3_value_blob(argv[2]);
81777         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81778         break;
81779
81780       case SQLITE_NULL:
81781         /* No key specified.  Use the key from the main database */
81782         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
81783         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
81784           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81785         }
81786         break;
81787     }
81788   }
81789 #endif
81790
81791   /* If the file was opened successfully, read the schema for the new database.
81792   ** If this fails, or if opening the file failed, then close the file and
81793   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
81794   ** we found it.
81795   */
81796   if( rc==SQLITE_OK ){
81797     sqlite3BtreeEnterAll(db);
81798     rc = sqlite3Init(db, &zErrDyn);
81799     sqlite3BtreeLeaveAll(db);
81800   }
81801   if( rc ){
81802     int iDb = db->nDb - 1;
81803     assert( iDb>=2 );
81804     if( db->aDb[iDb].pBt ){
81805       sqlite3BtreeClose(db->aDb[iDb].pBt);
81806       db->aDb[iDb].pBt = 0;
81807       db->aDb[iDb].pSchema = 0;
81808     }
81809     sqlite3ResetAllSchemasOfConnection(db);
81810     db->nDb = iDb;
81811     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
81812       db->mallocFailed = 1;
81813       sqlite3DbFree(db, zErrDyn);
81814       zErrDyn = sqlite3MPrintf(db, "out of memory");
81815     }else if( zErrDyn==0 ){
81816       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
81817     }
81818     goto attach_error;
81819   }
81820
81821   return;
81822
81823 attach_error:
81824   /* Return an error if we get here */
81825   if( zErrDyn ){
81826     sqlite3_result_error(context, zErrDyn, -1);
81827     sqlite3DbFree(db, zErrDyn);
81828   }
81829   if( rc ) sqlite3_result_error_code(context, rc);
81830 }
81831
81832 /*
81833 ** An SQL user-function registered to do the work of an DETACH statement. The
81834 ** three arguments to the function come directly from a detach statement:
81835 **
81836 **     DETACH DATABASE x
81837 **
81838 **     SELECT sqlite_detach(x)
81839 */
81840 static void detachFunc(
81841   sqlite3_context *context,
81842   int NotUsed,
81843   sqlite3_value **argv
81844 ){
81845   const char *zName = (const char *)sqlite3_value_text(argv[0]);
81846   sqlite3 *db = sqlite3_context_db_handle(context);
81847   int i;
81848   Db *pDb = 0;
81849   char zErr[128];
81850
81851   UNUSED_PARAMETER(NotUsed);
81852
81853   if( zName==0 ) zName = "";
81854   for(i=0; i<db->nDb; i++){
81855     pDb = &db->aDb[i];
81856     if( pDb->pBt==0 ) continue;
81857     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
81858   }
81859
81860   if( i>=db->nDb ){
81861     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
81862     goto detach_error;
81863   }
81864   if( i<2 ){
81865     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
81866     goto detach_error;
81867   }
81868   if( !db->autoCommit ){
81869     sqlite3_snprintf(sizeof(zErr), zErr,
81870                      "cannot DETACH database within transaction");
81871     goto detach_error;
81872   }
81873   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
81874     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
81875     goto detach_error;
81876   }
81877
81878   sqlite3BtreeClose(pDb->pBt);
81879   pDb->pBt = 0;
81880   pDb->pSchema = 0;
81881   sqlite3ResetAllSchemasOfConnection(db);
81882   return;
81883
81884 detach_error:
81885   sqlite3_result_error(context, zErr, -1);
81886 }
81887
81888 /*
81889 ** This procedure generates VDBE code for a single invocation of either the
81890 ** sqlite_detach() or sqlite_attach() SQL user functions.
81891 */
81892 static void codeAttach(
81893   Parse *pParse,       /* The parser context */
81894   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
81895   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
81896   Expr *pAuthArg,      /* Expression to pass to authorization callback */
81897   Expr *pFilename,     /* Name of database file */
81898   Expr *pDbname,       /* Name of the database to use internally */
81899   Expr *pKey           /* Database key for encryption extension */
81900 ){
81901   int rc;
81902   NameContext sName;
81903   Vdbe *v;
81904   sqlite3* db = pParse->db;
81905   int regArgs;
81906
81907   memset(&sName, 0, sizeof(NameContext));
81908   sName.pParse = pParse;
81909
81910   if(
81911       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
81912       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
81913       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
81914   ){
81915     pParse->nErr++;
81916     goto attach_end;
81917   }
81918
81919 #ifndef SQLITE_OMIT_AUTHORIZATION
81920   if( pAuthArg ){
81921     char *zAuthArg;
81922     if( pAuthArg->op==TK_STRING ){
81923       zAuthArg = pAuthArg->u.zToken;
81924     }else{
81925       zAuthArg = 0;
81926     }
81927     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
81928     if(rc!=SQLITE_OK ){
81929       goto attach_end;
81930     }
81931   }
81932 #endif /* SQLITE_OMIT_AUTHORIZATION */
81933
81934
81935   v = sqlite3GetVdbe(pParse);
81936   regArgs = sqlite3GetTempRange(pParse, 4);
81937   sqlite3ExprCode(pParse, pFilename, regArgs);
81938   sqlite3ExprCode(pParse, pDbname, regArgs+1);
81939   sqlite3ExprCode(pParse, pKey, regArgs+2);
81940
81941   assert( v || db->mallocFailed );
81942   if( v ){
81943     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
81944     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
81945     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
81946     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
81947
81948     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
81949     ** statement only). For DETACH, set it to false (expire all existing
81950     ** statements).
81951     */
81952     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
81953   }
81954
81955 attach_end:
81956   sqlite3ExprDelete(db, pFilename);
81957   sqlite3ExprDelete(db, pDbname);
81958   sqlite3ExprDelete(db, pKey);
81959 }
81960
81961 /*
81962 ** Called by the parser to compile a DETACH statement.
81963 **
81964 **     DETACH pDbname
81965 */
81966 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
81967   static const FuncDef detach_func = {
81968     1,                /* nArg */
81969     SQLITE_UTF8,      /* iPrefEnc */
81970     0,                /* flags */
81971     0,                /* pUserData */
81972     0,                /* pNext */
81973     detachFunc,       /* xFunc */
81974     0,                /* xStep */
81975     0,                /* xFinalize */
81976     "sqlite_detach",  /* zName */
81977     0,                /* pHash */
81978     0                 /* pDestructor */
81979   };
81980   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
81981 }
81982
81983 /*
81984 ** Called by the parser to compile an ATTACH statement.
81985 **
81986 **     ATTACH p AS pDbname KEY pKey
81987 */
81988 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
81989   static const FuncDef attach_func = {
81990     3,                /* nArg */
81991     SQLITE_UTF8,      /* iPrefEnc */
81992     0,                /* flags */
81993     0,                /* pUserData */
81994     0,                /* pNext */
81995     attachFunc,       /* xFunc */
81996     0,                /* xStep */
81997     0,                /* xFinalize */
81998     "sqlite_attach",  /* zName */
81999     0,                /* pHash */
82000     0                 /* pDestructor */
82001   };
82002   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
82003 }
82004 #endif /* SQLITE_OMIT_ATTACH */
82005
82006 /*
82007 ** Initialize a DbFixer structure.  This routine must be called prior
82008 ** to passing the structure to one of the sqliteFixAAAA() routines below.
82009 **
82010 ** The return value indicates whether or not fixation is required.  TRUE
82011 ** means we do need to fix the database references, FALSE means we do not.
82012 */
82013 SQLITE_PRIVATE int sqlite3FixInit(
82014   DbFixer *pFix,      /* The fixer to be initialized */
82015   Parse *pParse,      /* Error messages will be written here */
82016   int iDb,            /* This is the database that must be used */
82017   const char *zType,  /* "view", "trigger", or "index" */
82018   const Token *pName  /* Name of the view, trigger, or index */
82019 ){
82020   sqlite3 *db;
82021
82022   if( NEVER(iDb<0) || iDb==1 ) return 0;
82023   db = pParse->db;
82024   assert( db->nDb>iDb );
82025   pFix->pParse = pParse;
82026   pFix->zDb = db->aDb[iDb].zName;
82027   pFix->pSchema = db->aDb[iDb].pSchema;
82028   pFix->zType = zType;
82029   pFix->pName = pName;
82030   return 1;
82031 }
82032
82033 /*
82034 ** The following set of routines walk through the parse tree and assign
82035 ** a specific database to all table references where the database name
82036 ** was left unspecified in the original SQL statement.  The pFix structure
82037 ** must have been initialized by a prior call to sqlite3FixInit().
82038 **
82039 ** These routines are used to make sure that an index, trigger, or
82040 ** view in one database does not refer to objects in a different database.
82041 ** (Exception: indices, triggers, and views in the TEMP database are
82042 ** allowed to refer to anything.)  If a reference is explicitly made
82043 ** to an object in a different database, an error message is added to
82044 ** pParse->zErrMsg and these routines return non-zero.  If everything
82045 ** checks out, these routines return 0.
82046 */
82047 SQLITE_PRIVATE int sqlite3FixSrcList(
82048   DbFixer *pFix,       /* Context of the fixation */
82049   SrcList *pList       /* The Source list to check and modify */
82050 ){
82051   int i;
82052   const char *zDb;
82053   struct SrcList_item *pItem;
82054
82055   if( NEVER(pList==0) ) return 0;
82056   zDb = pFix->zDb;
82057   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
82058     if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
82059       sqlite3ErrorMsg(pFix->pParse,
82060          "%s %T cannot reference objects in database %s",
82061          pFix->zType, pFix->pName, pItem->zDatabase);
82062       return 1;
82063     }
82064     sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
82065     pItem->zDatabase = 0;
82066     pItem->pSchema = pFix->pSchema;
82067 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
82068     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
82069     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
82070 #endif
82071   }
82072   return 0;
82073 }
82074 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
82075 SQLITE_PRIVATE int sqlite3FixSelect(
82076   DbFixer *pFix,       /* Context of the fixation */
82077   Select *pSelect      /* The SELECT statement to be fixed to one database */
82078 ){
82079   while( pSelect ){
82080     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
82081       return 1;
82082     }
82083     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
82084       return 1;
82085     }
82086     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
82087       return 1;
82088     }
82089     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
82090       return 1;
82091     }
82092     pSelect = pSelect->pPrior;
82093   }
82094   return 0;
82095 }
82096 SQLITE_PRIVATE int sqlite3FixExpr(
82097   DbFixer *pFix,     /* Context of the fixation */
82098   Expr *pExpr        /* The expression to be fixed to one database */
82099 ){
82100   while( pExpr ){
82101     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
82102     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82103       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
82104     }else{
82105       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
82106     }
82107     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
82108       return 1;
82109     }
82110     pExpr = pExpr->pLeft;
82111   }
82112   return 0;
82113 }
82114 SQLITE_PRIVATE int sqlite3FixExprList(
82115   DbFixer *pFix,     /* Context of the fixation */
82116   ExprList *pList    /* The expression to be fixed to one database */
82117 ){
82118   int i;
82119   struct ExprList_item *pItem;
82120   if( pList==0 ) return 0;
82121   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
82122     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
82123       return 1;
82124     }
82125   }
82126   return 0;
82127 }
82128 #endif
82129
82130 #ifndef SQLITE_OMIT_TRIGGER
82131 SQLITE_PRIVATE int sqlite3FixTriggerStep(
82132   DbFixer *pFix,     /* Context of the fixation */
82133   TriggerStep *pStep /* The trigger step be fixed to one database */
82134 ){
82135   while( pStep ){
82136     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
82137       return 1;
82138     }
82139     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
82140       return 1;
82141     }
82142     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
82143       return 1;
82144     }
82145     pStep = pStep->pNext;
82146   }
82147   return 0;
82148 }
82149 #endif
82150
82151 /************** End of attach.c **********************************************/
82152 /************** Begin file auth.c ********************************************/
82153 /*
82154 ** 2003 January 11
82155 **
82156 ** The author disclaims copyright to this source code.  In place of
82157 ** a legal notice, here is a blessing:
82158 **
82159 **    May you do good and not evil.
82160 **    May you find forgiveness for yourself and forgive others.
82161 **    May you share freely, never taking more than you give.
82162 **
82163 *************************************************************************
82164 ** This file contains code used to implement the sqlite3_set_authorizer()
82165 ** API.  This facility is an optional feature of the library.  Embedded
82166 ** systems that do not need this facility may omit it by recompiling
82167 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
82168 */
82169
82170 /*
82171 ** All of the code in this file may be omitted by defining a single
82172 ** macro.
82173 */
82174 #ifndef SQLITE_OMIT_AUTHORIZATION
82175
82176 /*
82177 ** Set or clear the access authorization function.
82178 **
82179 ** The access authorization function is be called during the compilation
82180 ** phase to verify that the user has read and/or write access permission on
82181 ** various fields of the database.  The first argument to the auth function
82182 ** is a copy of the 3rd argument to this routine.  The second argument
82183 ** to the auth function is one of these constants:
82184 **
82185 **       SQLITE_CREATE_INDEX
82186 **       SQLITE_CREATE_TABLE
82187 **       SQLITE_CREATE_TEMP_INDEX
82188 **       SQLITE_CREATE_TEMP_TABLE
82189 **       SQLITE_CREATE_TEMP_TRIGGER
82190 **       SQLITE_CREATE_TEMP_VIEW
82191 **       SQLITE_CREATE_TRIGGER
82192 **       SQLITE_CREATE_VIEW
82193 **       SQLITE_DELETE
82194 **       SQLITE_DROP_INDEX
82195 **       SQLITE_DROP_TABLE
82196 **       SQLITE_DROP_TEMP_INDEX
82197 **       SQLITE_DROP_TEMP_TABLE
82198 **       SQLITE_DROP_TEMP_TRIGGER
82199 **       SQLITE_DROP_TEMP_VIEW
82200 **       SQLITE_DROP_TRIGGER
82201 **       SQLITE_DROP_VIEW
82202 **       SQLITE_INSERT
82203 **       SQLITE_PRAGMA
82204 **       SQLITE_READ
82205 **       SQLITE_SELECT
82206 **       SQLITE_TRANSACTION
82207 **       SQLITE_UPDATE
82208 **
82209 ** The third and fourth arguments to the auth function are the name of
82210 ** the table and the column that are being accessed.  The auth function
82211 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
82212 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
82213 ** means that the SQL statement will never-run - the sqlite3_exec() call
82214 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
82215 ** should run but attempts to read the specified column will return NULL
82216 ** and attempts to write the column will be ignored.
82217 **
82218 ** Setting the auth function to NULL disables this hook.  The default
82219 ** setting of the auth function is NULL.
82220 */
82221 SQLITE_API int sqlite3_set_authorizer(
82222   sqlite3 *db,
82223   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
82224   void *pArg
82225 ){
82226   sqlite3_mutex_enter(db->mutex);
82227   db->xAuth = xAuth;
82228   db->pAuthArg = pArg;
82229   sqlite3ExpirePreparedStatements(db);
82230   sqlite3_mutex_leave(db->mutex);
82231   return SQLITE_OK;
82232 }
82233
82234 /*
82235 ** Write an error message into pParse->zErrMsg that explains that the
82236 ** user-supplied authorization function returned an illegal value.
82237 */
82238 static void sqliteAuthBadReturnCode(Parse *pParse){
82239   sqlite3ErrorMsg(pParse, "authorizer malfunction");
82240   pParse->rc = SQLITE_ERROR;
82241 }
82242
82243 /*
82244 ** Invoke the authorization callback for permission to read column zCol from
82245 ** table zTab in database zDb. This function assumes that an authorization
82246 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
82247 **
82248 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
82249 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
82250 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
82251 */
82252 SQLITE_PRIVATE int sqlite3AuthReadCol(
82253   Parse *pParse,                  /* The parser context */
82254   const char *zTab,               /* Table name */
82255   const char *zCol,               /* Column name */
82256   int iDb                         /* Index of containing database. */
82257 ){
82258   sqlite3 *db = pParse->db;       /* Database handle */
82259   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
82260   int rc;                         /* Auth callback return code */
82261
82262   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
82263   if( rc==SQLITE_DENY ){
82264     if( db->nDb>2 || iDb!=0 ){
82265       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
82266     }else{
82267       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
82268     }
82269     pParse->rc = SQLITE_AUTH;
82270   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
82271     sqliteAuthBadReturnCode(pParse);
82272   }
82273   return rc;
82274 }
82275
82276 /*
82277 ** The pExpr should be a TK_COLUMN expression.  The table referred to
82278 ** is in pTabList or else it is the NEW or OLD table of a trigger.
82279 ** Check to see if it is OK to read this particular column.
82280 **
82281 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
82282 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
82283 ** then generate an error.
82284 */
82285 SQLITE_PRIVATE void sqlite3AuthRead(
82286   Parse *pParse,        /* The parser context */
82287   Expr *pExpr,          /* The expression to check authorization on */
82288   Schema *pSchema,      /* The schema of the expression */
82289   SrcList *pTabList     /* All table that pExpr might refer to */
82290 ){
82291   sqlite3 *db = pParse->db;
82292   Table *pTab = 0;      /* The table being read */
82293   const char *zCol;     /* Name of the column of the table */
82294   int iSrc;             /* Index in pTabList->a[] of table being read */
82295   int iDb;              /* The index of the database the expression refers to */
82296   int iCol;             /* Index of column in table */
82297
82298   if( db->xAuth==0 ) return;
82299   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
82300   if( iDb<0 ){
82301     /* An attempt to read a column out of a subquery or other
82302     ** temporary table. */
82303     return;
82304   }
82305
82306   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
82307   if( pExpr->op==TK_TRIGGER ){
82308     pTab = pParse->pTriggerTab;
82309   }else{
82310     assert( pTabList );
82311     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
82312       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
82313         pTab = pTabList->a[iSrc].pTab;
82314         break;
82315       }
82316     }
82317   }
82318   iCol = pExpr->iColumn;
82319   if( NEVER(pTab==0) ) return;
82320
82321   if( iCol>=0 ){
82322     assert( iCol<pTab->nCol );
82323     zCol = pTab->aCol[iCol].zName;
82324   }else if( pTab->iPKey>=0 ){
82325     assert( pTab->iPKey<pTab->nCol );
82326     zCol = pTab->aCol[pTab->iPKey].zName;
82327   }else{
82328     zCol = "ROWID";
82329   }
82330   assert( iDb>=0 && iDb<db->nDb );
82331   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
82332     pExpr->op = TK_NULL;
82333   }
82334 }
82335
82336 /*
82337 ** Do an authorization check using the code and arguments given.  Return
82338 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
82339 ** is returned, then the error count and error message in pParse are
82340 ** modified appropriately.
82341 */
82342 SQLITE_PRIVATE int sqlite3AuthCheck(
82343   Parse *pParse,
82344   int code,
82345   const char *zArg1,
82346   const char *zArg2,
82347   const char *zArg3
82348 ){
82349   sqlite3 *db = pParse->db;
82350   int rc;
82351
82352   /* Don't do any authorization checks if the database is initialising
82353   ** or if the parser is being invoked from within sqlite3_declare_vtab.
82354   */
82355   if( db->init.busy || IN_DECLARE_VTAB ){
82356     return SQLITE_OK;
82357   }
82358
82359   if( db->xAuth==0 ){
82360     return SQLITE_OK;
82361   }
82362   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
82363   if( rc==SQLITE_DENY ){
82364     sqlite3ErrorMsg(pParse, "not authorized");
82365     pParse->rc = SQLITE_AUTH;
82366   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
82367     rc = SQLITE_DENY;
82368     sqliteAuthBadReturnCode(pParse);
82369   }
82370   return rc;
82371 }
82372
82373 /*
82374 ** Push an authorization context.  After this routine is called, the
82375 ** zArg3 argument to authorization callbacks will be zContext until
82376 ** popped.  Or if pParse==0, this routine is a no-op.
82377 */
82378 SQLITE_PRIVATE void sqlite3AuthContextPush(
82379   Parse *pParse,
82380   AuthContext *pContext,
82381   const char *zContext
82382 ){
82383   assert( pParse );
82384   pContext->pParse = pParse;
82385   pContext->zAuthContext = pParse->zAuthContext;
82386   pParse->zAuthContext = zContext;
82387 }
82388
82389 /*
82390 ** Pop an authorization context that was previously pushed
82391 ** by sqlite3AuthContextPush
82392 */
82393 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
82394   if( pContext->pParse ){
82395     pContext->pParse->zAuthContext = pContext->zAuthContext;
82396     pContext->pParse = 0;
82397   }
82398 }
82399
82400 #endif /* SQLITE_OMIT_AUTHORIZATION */
82401
82402 /************** End of auth.c ************************************************/
82403 /************** Begin file build.c *******************************************/
82404 /*
82405 ** 2001 September 15
82406 **
82407 ** The author disclaims copyright to this source code.  In place of
82408 ** a legal notice, here is a blessing:
82409 **
82410 **    May you do good and not evil.
82411 **    May you find forgiveness for yourself and forgive others.
82412 **    May you share freely, never taking more than you give.
82413 **
82414 *************************************************************************
82415 ** This file contains C code routines that are called by the SQLite parser
82416 ** when syntax rules are reduced.  The routines in this file handle the
82417 ** following kinds of SQL syntax:
82418 **
82419 **     CREATE TABLE
82420 **     DROP TABLE
82421 **     CREATE INDEX
82422 **     DROP INDEX
82423 **     creating ID lists
82424 **     BEGIN TRANSACTION
82425 **     COMMIT
82426 **     ROLLBACK
82427 */
82428
82429 /*
82430 ** This routine is called when a new SQL statement is beginning to
82431 ** be parsed.  Initialize the pParse structure as needed.
82432 */
82433 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
82434   pParse->explain = (u8)explainFlag;
82435   pParse->nVar = 0;
82436 }
82437
82438 #ifndef SQLITE_OMIT_SHARED_CACHE
82439 /*
82440 ** The TableLock structure is only used by the sqlite3TableLock() and
82441 ** codeTableLocks() functions.
82442 */
82443 struct TableLock {
82444   int iDb;             /* The database containing the table to be locked */
82445   int iTab;            /* The root page of the table to be locked */
82446   u8 isWriteLock;      /* True for write lock.  False for a read lock */
82447   const char *zName;   /* Name of the table */
82448 };
82449
82450 /*
82451 ** Record the fact that we want to lock a table at run-time.
82452 **
82453 ** The table to be locked has root page iTab and is found in database iDb.
82454 ** A read or a write lock can be taken depending on isWritelock.
82455 **
82456 ** This routine just records the fact that the lock is desired.  The
82457 ** code to make the lock occur is generated by a later call to
82458 ** codeTableLocks() which occurs during sqlite3FinishCoding().
82459 */
82460 SQLITE_PRIVATE void sqlite3TableLock(
82461   Parse *pParse,     /* Parsing context */
82462   int iDb,           /* Index of the database containing the table to lock */
82463   int iTab,          /* Root page number of the table to be locked */
82464   u8 isWriteLock,    /* True for a write lock */
82465   const char *zName  /* Name of the table to be locked */
82466 ){
82467   Parse *pToplevel = sqlite3ParseToplevel(pParse);
82468   int i;
82469   int nBytes;
82470   TableLock *p;
82471   assert( iDb>=0 );
82472
82473   for(i=0; i<pToplevel->nTableLock; i++){
82474     p = &pToplevel->aTableLock[i];
82475     if( p->iDb==iDb && p->iTab==iTab ){
82476       p->isWriteLock = (p->isWriteLock || isWriteLock);
82477       return;
82478     }
82479   }
82480
82481   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
82482   pToplevel->aTableLock =
82483       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82484   if( pToplevel->aTableLock ){
82485     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
82486     p->iDb = iDb;
82487     p->iTab = iTab;
82488     p->isWriteLock = isWriteLock;
82489     p->zName = zName;
82490   }else{
82491     pToplevel->nTableLock = 0;
82492     pToplevel->db->mallocFailed = 1;
82493   }
82494 }
82495
82496 /*
82497 ** Code an OP_TableLock instruction for each table locked by the
82498 ** statement (configured by calls to sqlite3TableLock()).
82499 */
82500 static void codeTableLocks(Parse *pParse){
82501   int i;
82502   Vdbe *pVdbe;
82503
82504   pVdbe = sqlite3GetVdbe(pParse);
82505   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
82506
82507   for(i=0; i<pParse->nTableLock; i++){
82508     TableLock *p = &pParse->aTableLock[i];
82509     int p1 = p->iDb;
82510     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
82511                       p->zName, P4_STATIC);
82512   }
82513 }
82514 #else
82515   #define codeTableLocks(x)
82516 #endif
82517
82518 /*
82519 ** This routine is called after a single SQL statement has been
82520 ** parsed and a VDBE program to execute that statement has been
82521 ** prepared.  This routine puts the finishing touches on the
82522 ** VDBE program and resets the pParse structure for the next
82523 ** parse.
82524 **
82525 ** Note that if an error occurred, it might be the case that
82526 ** no VDBE code was generated.
82527 */
82528 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
82529   sqlite3 *db;
82530   Vdbe *v;
82531
82532   assert( pParse->pToplevel==0 );
82533   db = pParse->db;
82534   if( db->mallocFailed ) return;
82535   if( pParse->nested ) return;
82536   if( pParse->nErr ) return;
82537
82538   /* Begin by generating some termination code at the end of the
82539   ** vdbe program
82540   */
82541   v = sqlite3GetVdbe(pParse);
82542   assert( !pParse->isMultiWrite
82543        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
82544   if( v ){
82545     sqlite3VdbeAddOp0(v, OP_Halt);
82546
82547     /* The cookie mask contains one bit for each database file open.
82548     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
82549     ** set for each database that is used.  Generate code to start a
82550     ** transaction on each used database and to verify the schema cookie
82551     ** on each used database.
82552     */
82553     if( pParse->cookieGoto>0 ){
82554       yDbMask mask;
82555       int iDb;
82556       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
82557       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
82558         if( (mask & pParse->cookieMask)==0 ) continue;
82559         sqlite3VdbeUsesBtree(v, iDb);
82560         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
82561         if( db->init.busy==0 ){
82562           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82563           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
82564                             iDb, pParse->cookieValue[iDb],
82565                             db->aDb[iDb].pSchema->iGeneration);
82566         }
82567       }
82568 #ifndef SQLITE_OMIT_VIRTUALTABLE
82569       {
82570         int i;
82571         for(i=0; i<pParse->nVtabLock; i++){
82572           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
82573           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
82574         }
82575         pParse->nVtabLock = 0;
82576       }
82577 #endif
82578
82579       /* Once all the cookies have been verified and transactions opened,
82580       ** obtain the required table-locks. This is a no-op unless the
82581       ** shared-cache feature is enabled.
82582       */
82583       codeTableLocks(pParse);
82584
82585       /* Initialize any AUTOINCREMENT data structures required.
82586       */
82587       sqlite3AutoincrementBegin(pParse);
82588
82589       /* Finally, jump back to the beginning of the executable code. */
82590       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
82591     }
82592   }
82593
82594
82595   /* Get the VDBE program ready for execution
82596   */
82597   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
82598 #ifdef SQLITE_DEBUG
82599     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
82600     sqlite3VdbeTrace(v, trace);
82601 #endif
82602     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
82603     /* A minimum of one cursor is required if autoincrement is used
82604     *  See ticket [a696379c1f08866] */
82605     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
82606     sqlite3VdbeMakeReady(v, pParse);
82607     pParse->rc = SQLITE_DONE;
82608     pParse->colNamesSet = 0;
82609   }else{
82610     pParse->rc = SQLITE_ERROR;
82611   }
82612   pParse->nTab = 0;
82613   pParse->nMem = 0;
82614   pParse->nSet = 0;
82615   pParse->nVar = 0;
82616   pParse->cookieMask = 0;
82617   pParse->cookieGoto = 0;
82618 }
82619
82620 /*
82621 ** Run the parser and code generator recursively in order to generate
82622 ** code for the SQL statement given onto the end of the pParse context
82623 ** currently under construction.  When the parser is run recursively
82624 ** this way, the final OP_Halt is not appended and other initialization
82625 ** and finalization steps are omitted because those are handling by the
82626 ** outermost parser.
82627 **
82628 ** Not everything is nestable.  This facility is designed to permit
82629 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
82630 ** care if you decide to try to use this routine for some other purposes.
82631 */
82632 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
82633   va_list ap;
82634   char *zSql;
82635   char *zErrMsg = 0;
82636   sqlite3 *db = pParse->db;
82637 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
82638   char saveBuf[SAVE_SZ];
82639
82640   if( pParse->nErr ) return;
82641   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
82642   va_start(ap, zFormat);
82643   zSql = sqlite3VMPrintf(db, zFormat, ap);
82644   va_end(ap);
82645   if( zSql==0 ){
82646     return;   /* A malloc must have failed */
82647   }
82648   pParse->nested++;
82649   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
82650   memset(&pParse->nVar, 0, SAVE_SZ);
82651   sqlite3RunParser(pParse, zSql, &zErrMsg);
82652   sqlite3DbFree(db, zErrMsg);
82653   sqlite3DbFree(db, zSql);
82654   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
82655   pParse->nested--;
82656 }
82657
82658 /*
82659 ** Locate the in-memory structure that describes a particular database
82660 ** table given the name of that table and (optionally) the name of the
82661 ** database containing the table.  Return NULL if not found.
82662 **
82663 ** If zDatabase is 0, all databases are searched for the table and the
82664 ** first matching table is returned.  (No checking for duplicate table
82665 ** names is done.)  The search order is TEMP first, then MAIN, then any
82666 ** auxiliary databases added using the ATTACH command.
82667 **
82668 ** See also sqlite3LocateTable().
82669 */
82670 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
82671   Table *p = 0;
82672   int i;
82673   int nName;
82674   assert( zName!=0 );
82675   nName = sqlite3Strlen30(zName);
82676   /* All mutexes are required for schema access.  Make sure we hold them. */
82677   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82678   for(i=OMIT_TEMPDB; i<db->nDb; i++){
82679     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
82680     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
82681     assert( sqlite3SchemaMutexHeld(db, j, 0) );
82682     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
82683     if( p ) break;
82684   }
82685   return p;
82686 }
82687
82688 /*
82689 ** Locate the in-memory structure that describes a particular database
82690 ** table given the name of that table and (optionally) the name of the
82691 ** database containing the table.  Return NULL if not found.  Also leave an
82692 ** error message in pParse->zErrMsg.
82693 **
82694 ** The difference between this routine and sqlite3FindTable() is that this
82695 ** routine leaves an error message in pParse->zErrMsg where
82696 ** sqlite3FindTable() does not.
82697 */
82698 SQLITE_PRIVATE Table *sqlite3LocateTable(
82699   Parse *pParse,         /* context in which to report errors */
82700   int isView,            /* True if looking for a VIEW rather than a TABLE */
82701   const char *zName,     /* Name of the table we are looking for */
82702   const char *zDbase     /* Name of the database.  Might be NULL */
82703 ){
82704   Table *p;
82705
82706   /* Read the database schema. If an error occurs, leave an error message
82707   ** and code in pParse and return NULL. */
82708   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82709     return 0;
82710   }
82711
82712   p = sqlite3FindTable(pParse->db, zName, zDbase);
82713   if( p==0 ){
82714     const char *zMsg = isView ? "no such view" : "no such table";
82715     if( zDbase ){
82716       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
82717     }else{
82718       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
82719     }
82720     pParse->checkSchema = 1;
82721   }
82722   return p;
82723 }
82724
82725 /*
82726 ** Locate the table identified by *p.
82727 **
82728 ** This is a wrapper around sqlite3LocateTable(). The difference between
82729 ** sqlite3LocateTable() and this function is that this function restricts
82730 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
82731 ** non-NULL if it is part of a view or trigger program definition. See
82732 ** sqlite3FixSrcList() for details.
82733 */
82734 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
82735   Parse *pParse,
82736   int isView,
82737   struct SrcList_item *p
82738 ){
82739   const char *zDb;
82740   assert( p->pSchema==0 || p->zDatabase==0 );
82741   if( p->pSchema ){
82742     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
82743     zDb = pParse->db->aDb[iDb].zName;
82744   }else{
82745     zDb = p->zDatabase;
82746   }
82747   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
82748 }
82749
82750 /*
82751 ** Locate the in-memory structure that describes
82752 ** a particular index given the name of that index
82753 ** and the name of the database that contains the index.
82754 ** Return NULL if not found.
82755 **
82756 ** If zDatabase is 0, all databases are searched for the
82757 ** table and the first matching index is returned.  (No checking
82758 ** for duplicate index names is done.)  The search order is
82759 ** TEMP first, then MAIN, then any auxiliary databases added
82760 ** using the ATTACH command.
82761 */
82762 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
82763   Index *p = 0;
82764   int i;
82765   int nName = sqlite3Strlen30(zName);
82766   /* All mutexes are required for schema access.  Make sure we hold them. */
82767   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82768   for(i=OMIT_TEMPDB; i<db->nDb; i++){
82769     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
82770     Schema *pSchema = db->aDb[j].pSchema;
82771     assert( pSchema );
82772     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
82773     assert( sqlite3SchemaMutexHeld(db, j, 0) );
82774     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
82775     if( p ) break;
82776   }
82777   return p;
82778 }
82779
82780 /*
82781 ** Reclaim the memory used by an index
82782 */
82783 static void freeIndex(sqlite3 *db, Index *p){
82784 #ifndef SQLITE_OMIT_ANALYZE
82785   sqlite3DeleteIndexSamples(db, p);
82786 #endif
82787   sqlite3DbFree(db, p->zColAff);
82788   sqlite3DbFree(db, p);
82789 }
82790
82791 /*
82792 ** For the index called zIdxName which is found in the database iDb,
82793 ** unlike that index from its Table then remove the index from
82794 ** the index hash table and free all memory structures associated
82795 ** with the index.
82796 */
82797 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
82798   Index *pIndex;
82799   int len;
82800   Hash *pHash;
82801
82802   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82803   pHash = &db->aDb[iDb].pSchema->idxHash;
82804   len = sqlite3Strlen30(zIdxName);
82805   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
82806   if( ALWAYS(pIndex) ){
82807     if( pIndex->pTable->pIndex==pIndex ){
82808       pIndex->pTable->pIndex = pIndex->pNext;
82809     }else{
82810       Index *p;
82811       /* Justification of ALWAYS();  The index must be on the list of
82812       ** indices. */
82813       p = pIndex->pTable->pIndex;
82814       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
82815       if( ALWAYS(p && p->pNext==pIndex) ){
82816         p->pNext = pIndex->pNext;
82817       }
82818     }
82819     freeIndex(db, pIndex);
82820   }
82821   db->flags |= SQLITE_InternChanges;
82822 }
82823
82824 /*
82825 ** Look through the list of open database files in db->aDb[] and if
82826 ** any have been closed, remove them from the list.  Reallocate the
82827 ** db->aDb[] structure to a smaller size, if possible.
82828 **
82829 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
82830 ** are never candidates for being collapsed.
82831 */
82832 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
82833   int i, j;
82834   for(i=j=2; i<db->nDb; i++){
82835     struct Db *pDb = &db->aDb[i];
82836     if( pDb->pBt==0 ){
82837       sqlite3DbFree(db, pDb->zName);
82838       pDb->zName = 0;
82839       continue;
82840     }
82841     if( j<i ){
82842       db->aDb[j] = db->aDb[i];
82843     }
82844     j++;
82845   }
82846   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
82847   db->nDb = j;
82848   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
82849     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
82850     sqlite3DbFree(db, db->aDb);
82851     db->aDb = db->aDbStatic;
82852   }
82853 }
82854
82855 /*
82856 ** Reset the schema for the database at index iDb.  Also reset the
82857 ** TEMP schema.
82858 */
82859 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
82860   Db *pDb;
82861   assert( iDb<db->nDb );
82862
82863   /* Case 1:  Reset the single schema identified by iDb */
82864   pDb = &db->aDb[iDb];
82865   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82866   assert( pDb->pSchema!=0 );
82867   sqlite3SchemaClear(pDb->pSchema);
82868
82869   /* If any database other than TEMP is reset, then also reset TEMP
82870   ** since TEMP might be holding triggers that reference tables in the
82871   ** other database.
82872   */
82873   if( iDb!=1 ){
82874     pDb = &db->aDb[1];
82875     assert( pDb->pSchema!=0 );
82876     sqlite3SchemaClear(pDb->pSchema);
82877   }
82878   return;
82879 }
82880
82881 /*
82882 ** Erase all schema information from all attached databases (including
82883 ** "main" and "temp") for a single database connection.
82884 */
82885 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
82886   int i;
82887   sqlite3BtreeEnterAll(db);
82888   for(i=0; i<db->nDb; i++){
82889     Db *pDb = &db->aDb[i];
82890     if( pDb->pSchema ){
82891       sqlite3SchemaClear(pDb->pSchema);
82892     }
82893   }
82894   db->flags &= ~SQLITE_InternChanges;
82895   sqlite3VtabUnlockList(db);
82896   sqlite3BtreeLeaveAll(db);
82897   sqlite3CollapseDatabaseArray(db);
82898 }
82899
82900 /*
82901 ** This routine is called when a commit occurs.
82902 */
82903 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
82904   db->flags &= ~SQLITE_InternChanges;
82905 }
82906
82907 /*
82908 ** Delete memory allocated for the column names of a table or view (the
82909 ** Table.aCol[] array).
82910 */
82911 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
82912   int i;
82913   Column *pCol;
82914   assert( pTable!=0 );
82915   if( (pCol = pTable->aCol)!=0 ){
82916     for(i=0; i<pTable->nCol; i++, pCol++){
82917       sqlite3DbFree(db, pCol->zName);
82918       sqlite3ExprDelete(db, pCol->pDflt);
82919       sqlite3DbFree(db, pCol->zDflt);
82920       sqlite3DbFree(db, pCol->zType);
82921       sqlite3DbFree(db, pCol->zColl);
82922     }
82923     sqlite3DbFree(db, pTable->aCol);
82924   }
82925 }
82926
82927 /*
82928 ** Remove the memory data structures associated with the given
82929 ** Table.  No changes are made to disk by this routine.
82930 **
82931 ** This routine just deletes the data structure.  It does not unlink
82932 ** the table data structure from the hash table.  But it does destroy
82933 ** memory structures of the indices and foreign keys associated with
82934 ** the table.
82935 **
82936 ** The db parameter is optional.  It is needed if the Table object
82937 ** contains lookaside memory.  (Table objects in the schema do not use
82938 ** lookaside memory, but some ephemeral Table objects do.)  Or the
82939 ** db parameter can be used with db->pnBytesFreed to measure the memory
82940 ** used by the Table object.
82941 */
82942 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
82943   Index *pIndex, *pNext;
82944   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
82945
82946   assert( !pTable || pTable->nRef>0 );
82947
82948   /* Do not delete the table until the reference count reaches zero. */
82949   if( !pTable ) return;
82950   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
82951
82952   /* Record the number of outstanding lookaside allocations in schema Tables
82953   ** prior to doing any free() operations.  Since schema Tables do not use
82954   ** lookaside, this number should not change. */
82955   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
82956                          db->lookaside.nOut : 0 );
82957
82958   /* Delete all indices associated with this table. */
82959   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
82960     pNext = pIndex->pNext;
82961     assert( pIndex->pSchema==pTable->pSchema );
82962     if( !db || db->pnBytesFreed==0 ){
82963       char *zName = pIndex->zName;
82964       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
82965          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
82966       );
82967       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
82968       assert( pOld==pIndex || pOld==0 );
82969     }
82970     freeIndex(db, pIndex);
82971   }
82972
82973   /* Delete any foreign keys attached to this table. */
82974   sqlite3FkDelete(db, pTable);
82975
82976   /* Delete the Table structure itself.
82977   */
82978   sqliteDeleteColumnNames(db, pTable);
82979   sqlite3DbFree(db, pTable->zName);
82980   sqlite3DbFree(db, pTable->zColAff);
82981   sqlite3SelectDelete(db, pTable->pSelect);
82982 #ifndef SQLITE_OMIT_CHECK
82983   sqlite3ExprListDelete(db, pTable->pCheck);
82984 #endif
82985 #ifndef SQLITE_OMIT_VIRTUALTABLE
82986   sqlite3VtabClear(db, pTable);
82987 #endif
82988   sqlite3DbFree(db, pTable);
82989
82990   /* Verify that no lookaside memory was used by schema tables */
82991   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
82992 }
82993
82994 /*
82995 ** Unlink the given table from the hash tables and the delete the
82996 ** table structure with all its indices and foreign keys.
82997 */
82998 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
82999   Table *p;
83000   Db *pDb;
83001
83002   assert( db!=0 );
83003   assert( iDb>=0 && iDb<db->nDb );
83004   assert( zTabName );
83005   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83006   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
83007   pDb = &db->aDb[iDb];
83008   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
83009                         sqlite3Strlen30(zTabName),0);
83010   sqlite3DeleteTable(db, p);
83011   db->flags |= SQLITE_InternChanges;
83012 }
83013
83014 /*
83015 ** Given a token, return a string that consists of the text of that
83016 ** token.  Space to hold the returned string
83017 ** is obtained from sqliteMalloc() and must be freed by the calling
83018 ** function.
83019 **
83020 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
83021 ** surround the body of the token are removed.
83022 **
83023 ** Tokens are often just pointers into the original SQL text and so
83024 ** are not \000 terminated and are not persistent.  The returned string
83025 ** is \000 terminated and is persistent.
83026 */
83027 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
83028   char *zName;
83029   if( pName ){
83030     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
83031     sqlite3Dequote(zName);
83032   }else{
83033     zName = 0;
83034   }
83035   return zName;
83036 }
83037
83038 /*
83039 ** Open the sqlite_master table stored in database number iDb for
83040 ** writing. The table is opened using cursor 0.
83041 */
83042 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
83043   Vdbe *v = sqlite3GetVdbe(p);
83044   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
83045   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
83046   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
83047   if( p->nTab==0 ){
83048     p->nTab = 1;
83049   }
83050 }
83051
83052 /*
83053 ** Parameter zName points to a nul-terminated buffer containing the name
83054 ** of a database ("main", "temp" or the name of an attached db). This
83055 ** function returns the index of the named database in db->aDb[], or
83056 ** -1 if the named db cannot be found.
83057 */
83058 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
83059   int i = -1;         /* Database number */
83060   if( zName ){
83061     Db *pDb;
83062     int n = sqlite3Strlen30(zName);
83063     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
83064       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
83065           0==sqlite3StrICmp(pDb->zName, zName) ){
83066         break;
83067       }
83068     }
83069   }
83070   return i;
83071 }
83072
83073 /*
83074 ** The token *pName contains the name of a database (either "main" or
83075 ** "temp" or the name of an attached db). This routine returns the
83076 ** index of the named database in db->aDb[], or -1 if the named db
83077 ** does not exist.
83078 */
83079 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
83080   int i;                               /* Database number */
83081   char *zName;                         /* Name we are searching for */
83082   zName = sqlite3NameFromToken(db, pName);
83083   i = sqlite3FindDbName(db, zName);
83084   sqlite3DbFree(db, zName);
83085   return i;
83086 }
83087
83088 /* The table or view or trigger name is passed to this routine via tokens
83089 ** pName1 and pName2. If the table name was fully qualified, for example:
83090 **
83091 ** CREATE TABLE xxx.yyy (...);
83092 **
83093 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
83094 ** the table name is not fully qualified, i.e.:
83095 **
83096 ** CREATE TABLE yyy(...);
83097 **
83098 ** Then pName1 is set to "yyy" and pName2 is "".
83099 **
83100 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
83101 ** pName2) that stores the unqualified table name.  The index of the
83102 ** database "xxx" is returned.
83103 */
83104 SQLITE_PRIVATE int sqlite3TwoPartName(
83105   Parse *pParse,      /* Parsing and code generating context */
83106   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
83107   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
83108   Token **pUnqual     /* Write the unqualified object name here */
83109 ){
83110   int iDb;                    /* Database holding the object */
83111   sqlite3 *db = pParse->db;
83112
83113   if( ALWAYS(pName2!=0) && pName2->n>0 ){
83114     if( db->init.busy ) {
83115       sqlite3ErrorMsg(pParse, "corrupt database");
83116       pParse->nErr++;
83117       return -1;
83118     }
83119     *pUnqual = pName2;
83120     iDb = sqlite3FindDb(db, pName1);
83121     if( iDb<0 ){
83122       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
83123       pParse->nErr++;
83124       return -1;
83125     }
83126   }else{
83127     assert( db->init.iDb==0 || db->init.busy );
83128     iDb = db->init.iDb;
83129     *pUnqual = pName1;
83130   }
83131   return iDb;
83132 }
83133
83134 /*
83135 ** This routine is used to check if the UTF-8 string zName is a legal
83136 ** unqualified name for a new schema object (table, index, view or
83137 ** trigger). All names are legal except those that begin with the string
83138 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
83139 ** is reserved for internal use.
83140 */
83141 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
83142   if( !pParse->db->init.busy && pParse->nested==0
83143           && (pParse->db->flags & SQLITE_WriteSchema)==0
83144           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
83145     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
83146     return SQLITE_ERROR;
83147   }
83148   return SQLITE_OK;
83149 }
83150
83151 /*
83152 ** Begin constructing a new table representation in memory.  This is
83153 ** the first of several action routines that get called in response
83154 ** to a CREATE TABLE statement.  In particular, this routine is called
83155 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
83156 ** flag is true if the table should be stored in the auxiliary database
83157 ** file instead of in the main database file.  This is normally the case
83158 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
83159 ** CREATE and TABLE.
83160 **
83161 ** The new table record is initialized and put in pParse->pNewTable.
83162 ** As more of the CREATE TABLE statement is parsed, additional action
83163 ** routines will be called to add more information to this record.
83164 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
83165 ** is called to complete the construction of the new table record.
83166 */
83167 SQLITE_PRIVATE void sqlite3StartTable(
83168   Parse *pParse,   /* Parser context */
83169   Token *pName1,   /* First part of the name of the table or view */
83170   Token *pName2,   /* Second part of the name of the table or view */
83171   int isTemp,      /* True if this is a TEMP table */
83172   int isView,      /* True if this is a VIEW */
83173   int isVirtual,   /* True if this is a VIRTUAL table */
83174   int noErr        /* Do nothing if table already exists */
83175 ){
83176   Table *pTable;
83177   char *zName = 0; /* The name of the new table */
83178   sqlite3 *db = pParse->db;
83179   Vdbe *v;
83180   int iDb;         /* Database number to create the table in */
83181   Token *pName;    /* Unqualified name of the table to create */
83182
83183   /* The table or view name to create is passed to this routine via tokens
83184   ** pName1 and pName2. If the table name was fully qualified, for example:
83185   **
83186   ** CREATE TABLE xxx.yyy (...);
83187   **
83188   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
83189   ** the table name is not fully qualified, i.e.:
83190   **
83191   ** CREATE TABLE yyy(...);
83192   **
83193   ** Then pName1 is set to "yyy" and pName2 is "".
83194   **
83195   ** The call below sets the pName pointer to point at the token (pName1 or
83196   ** pName2) that stores the unqualified table name. The variable iDb is
83197   ** set to the index of the database that the table or view is to be
83198   ** created in.
83199   */
83200   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83201   if( iDb<0 ) return;
83202   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
83203     /* If creating a temp table, the name may not be qualified. Unless
83204     ** the database name is "temp" anyway.  */
83205     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
83206     return;
83207   }
83208   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
83209
83210   pParse->sNameToken = *pName;
83211   zName = sqlite3NameFromToken(db, pName);
83212   if( zName==0 ) return;
83213   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83214     goto begin_table_error;
83215   }
83216   if( db->init.iDb==1 ) isTemp = 1;
83217 #ifndef SQLITE_OMIT_AUTHORIZATION
83218   assert( (isTemp & 1)==isTemp );
83219   {
83220     int code;
83221     char *zDb = db->aDb[iDb].zName;
83222     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
83223       goto begin_table_error;
83224     }
83225     if( isView ){
83226       if( !OMIT_TEMPDB && isTemp ){
83227         code = SQLITE_CREATE_TEMP_VIEW;
83228       }else{
83229         code = SQLITE_CREATE_VIEW;
83230       }
83231     }else{
83232       if( !OMIT_TEMPDB && isTemp ){
83233         code = SQLITE_CREATE_TEMP_TABLE;
83234       }else{
83235         code = SQLITE_CREATE_TABLE;
83236       }
83237     }
83238     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
83239       goto begin_table_error;
83240     }
83241   }
83242 #endif
83243
83244   /* Make sure the new table name does not collide with an existing
83245   ** index or table name in the same database.  Issue an error message if
83246   ** it does. The exception is if the statement being parsed was passed
83247   ** to an sqlite3_declare_vtab() call. In that case only the column names
83248   ** and types will be used, so there is no need to test for namespace
83249   ** collisions.
83250   */
83251   if( !IN_DECLARE_VTAB ){
83252     char *zDb = db->aDb[iDb].zName;
83253     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83254       goto begin_table_error;
83255     }
83256     pTable = sqlite3FindTable(db, zName, zDb);
83257     if( pTable ){
83258       if( !noErr ){
83259         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
83260       }else{
83261         assert( !db->init.busy );
83262         sqlite3CodeVerifySchema(pParse, iDb);
83263       }
83264       goto begin_table_error;
83265     }
83266     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
83267       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
83268       goto begin_table_error;
83269     }
83270   }
83271
83272   pTable = sqlite3DbMallocZero(db, sizeof(Table));
83273   if( pTable==0 ){
83274     db->mallocFailed = 1;
83275     pParse->rc = SQLITE_NOMEM;
83276     pParse->nErr++;
83277     goto begin_table_error;
83278   }
83279   pTable->zName = zName;
83280   pTable->iPKey = -1;
83281   pTable->pSchema = db->aDb[iDb].pSchema;
83282   pTable->nRef = 1;
83283   pTable->nRowEst = 1000000;
83284   assert( pParse->pNewTable==0 );
83285   pParse->pNewTable = pTable;
83286
83287   /* If this is the magic sqlite_sequence table used by autoincrement,
83288   ** then record a pointer to this table in the main database structure
83289   ** so that INSERT can find the table easily.
83290   */
83291 #ifndef SQLITE_OMIT_AUTOINCREMENT
83292   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
83293     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83294     pTable->pSchema->pSeqTab = pTable;
83295   }
83296 #endif
83297
83298   /* Begin generating the code that will insert the table record into
83299   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
83300   ** and allocate the record number for the table entry now.  Before any
83301   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
83302   ** indices to be created and the table record must come before the
83303   ** indices.  Hence, the record number for the table must be allocated
83304   ** now.
83305   */
83306   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
83307     int j1;
83308     int fileFormat;
83309     int reg1, reg2, reg3;
83310     sqlite3BeginWriteOperation(pParse, 0, iDb);
83311
83312 #ifndef SQLITE_OMIT_VIRTUALTABLE
83313     if( isVirtual ){
83314       sqlite3VdbeAddOp0(v, OP_VBegin);
83315     }
83316 #endif
83317
83318     /* If the file format and encoding in the database have not been set,
83319     ** set them now.
83320     */
83321     reg1 = pParse->regRowid = ++pParse->nMem;
83322     reg2 = pParse->regRoot = ++pParse->nMem;
83323     reg3 = ++pParse->nMem;
83324     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
83325     sqlite3VdbeUsesBtree(v, iDb);
83326     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
83327     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
83328                   1 : SQLITE_MAX_FILE_FORMAT;
83329     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
83330     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
83331     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
83332     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
83333     sqlite3VdbeJumpHere(v, j1);
83334
83335     /* This just creates a place-holder record in the sqlite_master table.
83336     ** The record created does not contain anything yet.  It will be replaced
83337     ** by the real entry in code generated at sqlite3EndTable().
83338     **
83339     ** The rowid for the new entry is left in register pParse->regRowid.
83340     ** The root page number of the new table is left in reg pParse->regRoot.
83341     ** The rowid and root page number values are needed by the code that
83342     ** sqlite3EndTable will generate.
83343     */
83344 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83345     if( isView || isVirtual ){
83346       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
83347     }else
83348 #endif
83349     {
83350       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
83351     }
83352     sqlite3OpenMasterTable(pParse, iDb);
83353     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
83354     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
83355     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
83356     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
83357     sqlite3VdbeAddOp0(v, OP_Close);
83358   }
83359
83360   /* Normal (non-error) return. */
83361   return;
83362
83363   /* If an error occurs, we jump here */
83364 begin_table_error:
83365   sqlite3DbFree(db, zName);
83366   return;
83367 }
83368
83369 /*
83370 ** This macro is used to compare two strings in a case-insensitive manner.
83371 ** It is slightly faster than calling sqlite3StrICmp() directly, but
83372 ** produces larger code.
83373 **
83374 ** WARNING: This macro is not compatible with the strcmp() family. It
83375 ** returns true if the two strings are equal, otherwise false.
83376 */
83377 #define STRICMP(x, y) (\
83378 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
83379 sqlite3UpperToLower[*(unsigned char *)(y)]     \
83380 && sqlite3StrICmp((x)+1,(y)+1)==0 )
83381
83382 /*
83383 ** Add a new column to the table currently being constructed.
83384 **
83385 ** The parser calls this routine once for each column declaration
83386 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
83387 ** first to get things going.  Then this routine is called for each
83388 ** column.
83389 */
83390 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
83391   Table *p;
83392   int i;
83393   char *z;
83394   Column *pCol;
83395   sqlite3 *db = pParse->db;
83396   if( (p = pParse->pNewTable)==0 ) return;
83397 #if SQLITE_MAX_COLUMN
83398   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
83399     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
83400     return;
83401   }
83402 #endif
83403   z = sqlite3NameFromToken(db, pName);
83404   if( z==0 ) return;
83405   for(i=0; i<p->nCol; i++){
83406     if( STRICMP(z, p->aCol[i].zName) ){
83407       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
83408       sqlite3DbFree(db, z);
83409       return;
83410     }
83411   }
83412   if( (p->nCol & 0x7)==0 ){
83413     Column *aNew;
83414     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
83415     if( aNew==0 ){
83416       sqlite3DbFree(db, z);
83417       return;
83418     }
83419     p->aCol = aNew;
83420   }
83421   pCol = &p->aCol[p->nCol];
83422   memset(pCol, 0, sizeof(p->aCol[0]));
83423   pCol->zName = z;
83424
83425   /* If there is no type specified, columns have the default affinity
83426   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
83427   ** be called next to set pCol->affinity correctly.
83428   */
83429   pCol->affinity = SQLITE_AFF_NONE;
83430   p->nCol++;
83431 }
83432
83433 /*
83434 ** This routine is called by the parser while in the middle of
83435 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
83436 ** been seen on a column.  This routine sets the notNull flag on
83437 ** the column currently under construction.
83438 */
83439 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
83440   Table *p;
83441   p = pParse->pNewTable;
83442   if( p==0 || NEVER(p->nCol<1) ) return;
83443   p->aCol[p->nCol-1].notNull = (u8)onError;
83444 }
83445
83446 /*
83447 ** Scan the column type name zType (length nType) and return the
83448 ** associated affinity type.
83449 **
83450 ** This routine does a case-independent search of zType for the
83451 ** substrings in the following table. If one of the substrings is
83452 ** found, the corresponding affinity is returned. If zType contains
83453 ** more than one of the substrings, entries toward the top of
83454 ** the table take priority. For example, if zType is 'BLOBINT',
83455 ** SQLITE_AFF_INTEGER is returned.
83456 **
83457 ** Substring     | Affinity
83458 ** --------------------------------
83459 ** 'INT'         | SQLITE_AFF_INTEGER
83460 ** 'CHAR'        | SQLITE_AFF_TEXT
83461 ** 'CLOB'        | SQLITE_AFF_TEXT
83462 ** 'TEXT'        | SQLITE_AFF_TEXT
83463 ** 'BLOB'        | SQLITE_AFF_NONE
83464 ** 'REAL'        | SQLITE_AFF_REAL
83465 ** 'FLOA'        | SQLITE_AFF_REAL
83466 ** 'DOUB'        | SQLITE_AFF_REAL
83467 **
83468 ** If none of the substrings in the above table are found,
83469 ** SQLITE_AFF_NUMERIC is returned.
83470 */
83471 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
83472   u32 h = 0;
83473   char aff = SQLITE_AFF_NUMERIC;
83474
83475   if( zIn ) while( zIn[0] ){
83476     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
83477     zIn++;
83478     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
83479       aff = SQLITE_AFF_TEXT;
83480     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
83481       aff = SQLITE_AFF_TEXT;
83482     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
83483       aff = SQLITE_AFF_TEXT;
83484     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
83485         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
83486       aff = SQLITE_AFF_NONE;
83487 #ifndef SQLITE_OMIT_FLOATING_POINT
83488     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
83489         && aff==SQLITE_AFF_NUMERIC ){
83490       aff = SQLITE_AFF_REAL;
83491     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
83492         && aff==SQLITE_AFF_NUMERIC ){
83493       aff = SQLITE_AFF_REAL;
83494     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
83495         && aff==SQLITE_AFF_NUMERIC ){
83496       aff = SQLITE_AFF_REAL;
83497 #endif
83498     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
83499       aff = SQLITE_AFF_INTEGER;
83500       break;
83501     }
83502   }
83503
83504   return aff;
83505 }
83506
83507 /*
83508 ** This routine is called by the parser while in the middle of
83509 ** parsing a CREATE TABLE statement.  The pFirst token is the first
83510 ** token in the sequence of tokens that describe the type of the
83511 ** column currently under construction.   pLast is the last token
83512 ** in the sequence.  Use this information to construct a string
83513 ** that contains the typename of the column and store that string
83514 ** in zType.
83515 */
83516 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
83517   Table *p;
83518   Column *pCol;
83519
83520   p = pParse->pNewTable;
83521   if( p==0 || NEVER(p->nCol<1) ) return;
83522   pCol = &p->aCol[p->nCol-1];
83523   assert( pCol->zType==0 );
83524   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
83525   pCol->affinity = sqlite3AffinityType(pCol->zType);
83526 }
83527
83528 /*
83529 ** The expression is the default value for the most recently added column
83530 ** of the table currently under construction.
83531 **
83532 ** Default value expressions must be constant.  Raise an exception if this
83533 ** is not the case.
83534 **
83535 ** This routine is called by the parser while in the middle of
83536 ** parsing a CREATE TABLE statement.
83537 */
83538 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
83539   Table *p;
83540   Column *pCol;
83541   sqlite3 *db = pParse->db;
83542   p = pParse->pNewTable;
83543   if( p!=0 ){
83544     pCol = &(p->aCol[p->nCol-1]);
83545     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
83546       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
83547           pCol->zName);
83548     }else{
83549       /* A copy of pExpr is used instead of the original, as pExpr contains
83550       ** tokens that point to volatile memory. The 'span' of the expression
83551       ** is required by pragma table_info.
83552       */
83553       sqlite3ExprDelete(db, pCol->pDflt);
83554       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
83555       sqlite3DbFree(db, pCol->zDflt);
83556       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
83557                                      (int)(pSpan->zEnd - pSpan->zStart));
83558     }
83559   }
83560   sqlite3ExprDelete(db, pSpan->pExpr);
83561 }
83562
83563 /*
83564 ** Designate the PRIMARY KEY for the table.  pList is a list of names
83565 ** of columns that form the primary key.  If pList is NULL, then the
83566 ** most recently added column of the table is the primary key.
83567 **
83568 ** A table can have at most one primary key.  If the table already has
83569 ** a primary key (and this is the second primary key) then create an
83570 ** error.
83571 **
83572 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
83573 ** then we will try to use that column as the rowid.  Set the Table.iPKey
83574 ** field of the table under construction to be the index of the
83575 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
83576 ** no INTEGER PRIMARY KEY.
83577 **
83578 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
83579 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
83580 */
83581 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
83582   Parse *pParse,    /* Parsing context */
83583   ExprList *pList,  /* List of field names to be indexed */
83584   int onError,      /* What to do with a uniqueness conflict */
83585   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
83586   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
83587 ){
83588   Table *pTab = pParse->pNewTable;
83589   char *zType = 0;
83590   int iCol = -1, i;
83591   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
83592   if( pTab->tabFlags & TF_HasPrimaryKey ){
83593     sqlite3ErrorMsg(pParse,
83594       "table \"%s\" has more than one primary key", pTab->zName);
83595     goto primary_key_exit;
83596   }
83597   pTab->tabFlags |= TF_HasPrimaryKey;
83598   if( pList==0 ){
83599     iCol = pTab->nCol - 1;
83600     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83601   }else{
83602     for(i=0; i<pList->nExpr; i++){
83603       for(iCol=0; iCol<pTab->nCol; iCol++){
83604         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
83605           break;
83606         }
83607       }
83608       if( iCol<pTab->nCol ){
83609         pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83610       }
83611     }
83612     if( pList->nExpr>1 ) iCol = -1;
83613   }
83614   if( iCol>=0 && iCol<pTab->nCol ){
83615     zType = pTab->aCol[iCol].zType;
83616   }
83617   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
83618         && sortOrder==SQLITE_SO_ASC ){
83619     pTab->iPKey = iCol;
83620     pTab->keyConf = (u8)onError;
83621     assert( autoInc==0 || autoInc==1 );
83622     pTab->tabFlags |= autoInc*TF_Autoincrement;
83623   }else if( autoInc ){
83624 #ifndef SQLITE_OMIT_AUTOINCREMENT
83625     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
83626        "INTEGER PRIMARY KEY");
83627 #endif
83628   }else{
83629     Index *p;
83630     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
83631     if( p ){
83632       p->autoIndex = 2;
83633     }
83634     pList = 0;
83635   }
83636
83637 primary_key_exit:
83638   sqlite3ExprListDelete(pParse->db, pList);
83639   return;
83640 }
83641
83642 /*
83643 ** Add a new CHECK constraint to the table currently under construction.
83644 */
83645 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
83646   Parse *pParse,    /* Parsing context */
83647   Expr *pCheckExpr  /* The check expression */
83648 ){
83649 #ifndef SQLITE_OMIT_CHECK
83650   Table *pTab = pParse->pNewTable;
83651   if( pTab && !IN_DECLARE_VTAB ){
83652     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
83653     if( pParse->constraintName.n ){
83654       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
83655     }
83656   }else
83657 #endif
83658   {
83659     sqlite3ExprDelete(pParse->db, pCheckExpr);
83660   }
83661 }
83662
83663 /*
83664 ** Set the collation function of the most recently parsed table column
83665 ** to the CollSeq given.
83666 */
83667 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
83668   Table *p;
83669   int i;
83670   char *zColl;              /* Dequoted name of collation sequence */
83671   sqlite3 *db;
83672
83673   if( (p = pParse->pNewTable)==0 ) return;
83674   i = p->nCol-1;
83675   db = pParse->db;
83676   zColl = sqlite3NameFromToken(db, pToken);
83677   if( !zColl ) return;
83678
83679   if( sqlite3LocateCollSeq(pParse, zColl) ){
83680     Index *pIdx;
83681     p->aCol[i].zColl = zColl;
83682
83683     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83684     ** then an index may have been created on this column before the
83685     ** collation type was added. Correct this if it is the case.
83686     */
83687     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
83688       assert( pIdx->nColumn==1 );
83689       if( pIdx->aiColumn[0]==i ){
83690         pIdx->azColl[0] = p->aCol[i].zColl;
83691       }
83692     }
83693   }else{
83694     sqlite3DbFree(db, zColl);
83695   }
83696 }
83697
83698 /*
83699 ** This function returns the collation sequence for database native text
83700 ** encoding identified by the string zName, length nName.
83701 **
83702 ** If the requested collation sequence is not available, or not available
83703 ** in the database native encoding, the collation factory is invoked to
83704 ** request it. If the collation factory does not supply such a sequence,
83705 ** and the sequence is available in another text encoding, then that is
83706 ** returned instead.
83707 **
83708 ** If no versions of the requested collations sequence are available, or
83709 ** another error occurs, NULL is returned and an error message written into
83710 ** pParse.
83711 **
83712 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
83713 ** invokes the collation factory if the named collation cannot be found
83714 ** and generates an error message.
83715 **
83716 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
83717 */
83718 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
83719   sqlite3 *db = pParse->db;
83720   u8 enc = ENC(db);
83721   u8 initbusy = db->init.busy;
83722   CollSeq *pColl;
83723
83724   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
83725   if( !initbusy && (!pColl || !pColl->xCmp) ){
83726     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
83727   }
83728
83729   return pColl;
83730 }
83731
83732
83733 /*
83734 ** Generate code that will increment the schema cookie.
83735 **
83736 ** The schema cookie is used to determine when the schema for the
83737 ** database changes.  After each schema change, the cookie value
83738 ** changes.  When a process first reads the schema it records the
83739 ** cookie.  Thereafter, whenever it goes to access the database,
83740 ** it checks the cookie to make sure the schema has not changed
83741 ** since it was last read.
83742 **
83743 ** This plan is not completely bullet-proof.  It is possible for
83744 ** the schema to change multiple times and for the cookie to be
83745 ** set back to prior value.  But schema changes are infrequent
83746 ** and the probability of hitting the same cookie value is only
83747 ** 1 chance in 2^32.  So we're safe enough.
83748 */
83749 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
83750   int r1 = sqlite3GetTempReg(pParse);
83751   sqlite3 *db = pParse->db;
83752   Vdbe *v = pParse->pVdbe;
83753   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83754   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
83755   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
83756   sqlite3ReleaseTempReg(pParse, r1);
83757 }
83758
83759 /*
83760 ** Measure the number of characters needed to output the given
83761 ** identifier.  The number returned includes any quotes used
83762 ** but does not include the null terminator.
83763 **
83764 ** The estimate is conservative.  It might be larger that what is
83765 ** really needed.
83766 */
83767 static int identLength(const char *z){
83768   int n;
83769   for(n=0; *z; n++, z++){
83770     if( *z=='"' ){ n++; }
83771   }
83772   return n + 2;
83773 }
83774
83775 /*
83776 ** The first parameter is a pointer to an output buffer. The second
83777 ** parameter is a pointer to an integer that contains the offset at
83778 ** which to write into the output buffer. This function copies the
83779 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
83780 ** to the specified offset in the buffer and updates *pIdx to refer
83781 ** to the first byte after the last byte written before returning.
83782 **
83783 ** If the string zSignedIdent consists entirely of alpha-numeric
83784 ** characters, does not begin with a digit and is not an SQL keyword,
83785 ** then it is copied to the output buffer exactly as it is. Otherwise,
83786 ** it is quoted using double-quotes.
83787 */
83788 static void identPut(char *z, int *pIdx, char *zSignedIdent){
83789   unsigned char *zIdent = (unsigned char*)zSignedIdent;
83790   int i, j, needQuote;
83791   i = *pIdx;
83792
83793   for(j=0; zIdent[j]; j++){
83794     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
83795   }
83796   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
83797   if( !needQuote ){
83798     needQuote = zIdent[j];
83799   }
83800
83801   if( needQuote ) z[i++] = '"';
83802   for(j=0; zIdent[j]; j++){
83803     z[i++] = zIdent[j];
83804     if( zIdent[j]=='"' ) z[i++] = '"';
83805   }
83806   if( needQuote ) z[i++] = '"';
83807   z[i] = 0;
83808   *pIdx = i;
83809 }
83810
83811 /*
83812 ** Generate a CREATE TABLE statement appropriate for the given
83813 ** table.  Memory to hold the text of the statement is obtained
83814 ** from sqliteMalloc() and must be freed by the calling function.
83815 */
83816 static char *createTableStmt(sqlite3 *db, Table *p){
83817   int i, k, n;
83818   char *zStmt;
83819   char *zSep, *zSep2, *zEnd;
83820   Column *pCol;
83821   n = 0;
83822   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
83823     n += identLength(pCol->zName) + 5;
83824   }
83825   n += identLength(p->zName);
83826   if( n<50 ){
83827     zSep = "";
83828     zSep2 = ",";
83829     zEnd = ")";
83830   }else{
83831     zSep = "\n  ";
83832     zSep2 = ",\n  ";
83833     zEnd = "\n)";
83834   }
83835   n += 35 + 6*p->nCol;
83836   zStmt = sqlite3DbMallocRaw(0, n);
83837   if( zStmt==0 ){
83838     db->mallocFailed = 1;
83839     return 0;
83840   }
83841   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
83842   k = sqlite3Strlen30(zStmt);
83843   identPut(zStmt, &k, p->zName);
83844   zStmt[k++] = '(';
83845   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
83846     static const char * const azType[] = {
83847         /* SQLITE_AFF_TEXT    */ " TEXT",
83848         /* SQLITE_AFF_NONE    */ "",
83849         /* SQLITE_AFF_NUMERIC */ " NUM",
83850         /* SQLITE_AFF_INTEGER */ " INT",
83851         /* SQLITE_AFF_REAL    */ " REAL"
83852     };
83853     int len;
83854     const char *zType;
83855
83856     sqlite3_snprintf(n-k, &zStmt[k], zSep);
83857     k += sqlite3Strlen30(&zStmt[k]);
83858     zSep = zSep2;
83859     identPut(zStmt, &k, pCol->zName);
83860     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
83861     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
83862     testcase( pCol->affinity==SQLITE_AFF_TEXT );
83863     testcase( pCol->affinity==SQLITE_AFF_NONE );
83864     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
83865     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
83866     testcase( pCol->affinity==SQLITE_AFF_REAL );
83867
83868     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
83869     len = sqlite3Strlen30(zType);
83870     assert( pCol->affinity==SQLITE_AFF_NONE
83871             || pCol->affinity==sqlite3AffinityType(zType) );
83872     memcpy(&zStmt[k], zType, len);
83873     k += len;
83874     assert( k<=n );
83875   }
83876   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
83877   return zStmt;
83878 }
83879
83880 /*
83881 ** This routine is called to report the final ")" that terminates
83882 ** a CREATE TABLE statement.
83883 **
83884 ** The table structure that other action routines have been building
83885 ** is added to the internal hash tables, assuming no errors have
83886 ** occurred.
83887 **
83888 ** An entry for the table is made in the master table on disk, unless
83889 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
83890 ** it means we are reading the sqlite_master table because we just
83891 ** connected to the database or because the sqlite_master table has
83892 ** recently changed, so the entry for this table already exists in
83893 ** the sqlite_master table.  We do not want to create it again.
83894 **
83895 ** If the pSelect argument is not NULL, it means that this routine
83896 ** was called to create a table generated from a
83897 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
83898 ** the new table will match the result set of the SELECT.
83899 */
83900 SQLITE_PRIVATE void sqlite3EndTable(
83901   Parse *pParse,          /* Parse context */
83902   Token *pCons,           /* The ',' token after the last column defn. */
83903   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
83904   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
83905 ){
83906   Table *p;
83907   sqlite3 *db = pParse->db;
83908   int iDb;
83909
83910   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
83911     return;
83912   }
83913   p = pParse->pNewTable;
83914   if( p==0 ) return;
83915
83916   assert( !db->init.busy || !pSelect );
83917
83918   iDb = sqlite3SchemaToIndex(db, p->pSchema);
83919
83920 #ifndef SQLITE_OMIT_CHECK
83921   /* Resolve names in all CHECK constraint expressions.
83922   */
83923   if( p->pCheck ){
83924     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
83925     NameContext sNC;                /* Name context for pParse->pNewTable */
83926     ExprList *pList;                /* List of all CHECK constraints */
83927     int i;                          /* Loop counter */
83928
83929     memset(&sNC, 0, sizeof(sNC));
83930     memset(&sSrc, 0, sizeof(sSrc));
83931     sSrc.nSrc = 1;
83932     sSrc.a[0].zName = p->zName;
83933     sSrc.a[0].pTab = p;
83934     sSrc.a[0].iCursor = -1;
83935     sNC.pParse = pParse;
83936     sNC.pSrcList = &sSrc;
83937     sNC.ncFlags = NC_IsCheck;
83938     pList = p->pCheck;
83939     for(i=0; i<pList->nExpr; i++){
83940       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
83941         return;
83942       }
83943     }
83944   }
83945 #endif /* !defined(SQLITE_OMIT_CHECK) */
83946
83947   /* If the db->init.busy is 1 it means we are reading the SQL off the
83948   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
83949   ** So do not write to the disk again.  Extract the root page number
83950   ** for the table from the db->init.newTnum field.  (The page number
83951   ** should have been put there by the sqliteOpenCb routine.)
83952   */
83953   if( db->init.busy ){
83954     p->tnum = db->init.newTnum;
83955   }
83956
83957   /* If not initializing, then create a record for the new table
83958   ** in the SQLITE_MASTER table of the database.
83959   **
83960   ** If this is a TEMPORARY table, write the entry into the auxiliary
83961   ** file instead of into the main database file.
83962   */
83963   if( !db->init.busy ){
83964     int n;
83965     Vdbe *v;
83966     char *zType;    /* "view" or "table" */
83967     char *zType2;   /* "VIEW" or "TABLE" */
83968     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
83969
83970     v = sqlite3GetVdbe(pParse);
83971     if( NEVER(v==0) ) return;
83972
83973     sqlite3VdbeAddOp1(v, OP_Close, 0);
83974
83975     /*
83976     ** Initialize zType for the new view or table.
83977     */
83978     if( p->pSelect==0 ){
83979       /* A regular table */
83980       zType = "table";
83981       zType2 = "TABLE";
83982 #ifndef SQLITE_OMIT_VIEW
83983     }else{
83984       /* A view */
83985       zType = "view";
83986       zType2 = "VIEW";
83987 #endif
83988     }
83989
83990     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
83991     ** statement to populate the new table. The root-page number for the
83992     ** new table is in register pParse->regRoot.
83993     **
83994     ** Once the SELECT has been coded by sqlite3Select(), it is in a
83995     ** suitable state to query for the column names and types to be used
83996     ** by the new table.
83997     **
83998     ** A shared-cache write-lock is not required to write to the new table,
83999     ** as a schema-lock must have already been obtained to create it. Since
84000     ** a schema-lock excludes all other database users, the write-lock would
84001     ** be redundant.
84002     */
84003     if( pSelect ){
84004       SelectDest dest;
84005       Table *pSelTab;
84006
84007       assert(pParse->nTab==1);
84008       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
84009       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
84010       pParse->nTab = 2;
84011       sqlite3SelectDestInit(&dest, SRT_Table, 1);
84012       sqlite3Select(pParse, pSelect, &dest);
84013       sqlite3VdbeAddOp1(v, OP_Close, 1);
84014       if( pParse->nErr==0 ){
84015         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
84016         if( pSelTab==0 ) return;
84017         assert( p->aCol==0 );
84018         p->nCol = pSelTab->nCol;
84019         p->aCol = pSelTab->aCol;
84020         pSelTab->nCol = 0;
84021         pSelTab->aCol = 0;
84022         sqlite3DeleteTable(db, pSelTab);
84023       }
84024     }
84025
84026     /* Compute the complete text of the CREATE statement */
84027     if( pSelect ){
84028       zStmt = createTableStmt(db, p);
84029     }else{
84030       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
84031       zStmt = sqlite3MPrintf(db,
84032           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
84033       );
84034     }
84035
84036     /* A slot for the record has already been allocated in the
84037     ** SQLITE_MASTER table.  We just need to update that slot with all
84038     ** the information we've collected.
84039     */
84040     sqlite3NestedParse(pParse,
84041       "UPDATE %Q.%s "
84042          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
84043        "WHERE rowid=#%d",
84044       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
84045       zType,
84046       p->zName,
84047       p->zName,
84048       pParse->regRoot,
84049       zStmt,
84050       pParse->regRowid
84051     );
84052     sqlite3DbFree(db, zStmt);
84053     sqlite3ChangeCookie(pParse, iDb);
84054
84055 #ifndef SQLITE_OMIT_AUTOINCREMENT
84056     /* Check to see if we need to create an sqlite_sequence table for
84057     ** keeping track of autoincrement keys.
84058     */
84059     if( p->tabFlags & TF_Autoincrement ){
84060       Db *pDb = &db->aDb[iDb];
84061       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84062       if( pDb->pSchema->pSeqTab==0 ){
84063         sqlite3NestedParse(pParse,
84064           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
84065           pDb->zName
84066         );
84067       }
84068     }
84069 #endif
84070
84071     /* Reparse everything to update our internal data structures */
84072     sqlite3VdbeAddParseSchemaOp(v, iDb,
84073                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
84074   }
84075
84076
84077   /* Add the table to the in-memory representation of the database.
84078   */
84079   if( db->init.busy ){
84080     Table *pOld;
84081     Schema *pSchema = p->pSchema;
84082     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84083     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
84084                              sqlite3Strlen30(p->zName),p);
84085     if( pOld ){
84086       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
84087       db->mallocFailed = 1;
84088       return;
84089     }
84090     pParse->pNewTable = 0;
84091     db->flags |= SQLITE_InternChanges;
84092
84093 #ifndef SQLITE_OMIT_ALTERTABLE
84094     if( !p->pSelect ){
84095       const char *zName = (const char *)pParse->sNameToken.z;
84096       int nName;
84097       assert( !pSelect && pCons && pEnd );
84098       if( pCons->z==0 ){
84099         pCons = pEnd;
84100       }
84101       nName = (int)((const char *)pCons->z - zName);
84102       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
84103     }
84104 #endif
84105   }
84106 }
84107
84108 #ifndef SQLITE_OMIT_VIEW
84109 /*
84110 ** The parser calls this routine in order to create a new VIEW
84111 */
84112 SQLITE_PRIVATE void sqlite3CreateView(
84113   Parse *pParse,     /* The parsing context */
84114   Token *pBegin,     /* The CREATE token that begins the statement */
84115   Token *pName1,     /* The token that holds the name of the view */
84116   Token *pName2,     /* The token that holds the name of the view */
84117   Select *pSelect,   /* A SELECT statement that will become the new view */
84118   int isTemp,        /* TRUE for a TEMPORARY view */
84119   int noErr          /* Suppress error messages if VIEW already exists */
84120 ){
84121   Table *p;
84122   int n;
84123   const char *z;
84124   Token sEnd;
84125   DbFixer sFix;
84126   Token *pName = 0;
84127   int iDb;
84128   sqlite3 *db = pParse->db;
84129
84130   if( pParse->nVar>0 ){
84131     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
84132     sqlite3SelectDelete(db, pSelect);
84133     return;
84134   }
84135   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
84136   p = pParse->pNewTable;
84137   if( p==0 || pParse->nErr ){
84138     sqlite3SelectDelete(db, pSelect);
84139     return;
84140   }
84141   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84142   iDb = sqlite3SchemaToIndex(db, p->pSchema);
84143   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
84144     && sqlite3FixSelect(&sFix, pSelect)
84145   ){
84146     sqlite3SelectDelete(db, pSelect);
84147     return;
84148   }
84149
84150   /* Make a copy of the entire SELECT statement that defines the view.
84151   ** This will force all the Expr.token.z values to be dynamically
84152   ** allocated rather than point to the input string - which means that
84153   ** they will persist after the current sqlite3_exec() call returns.
84154   */
84155   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84156   sqlite3SelectDelete(db, pSelect);
84157   if( db->mallocFailed ){
84158     return;
84159   }
84160   if( !db->init.busy ){
84161     sqlite3ViewGetColumnNames(pParse, p);
84162   }
84163
84164   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
84165   ** the end.
84166   */
84167   sEnd = pParse->sLastToken;
84168   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
84169     sEnd.z += sEnd.n;
84170   }
84171   sEnd.n = 0;
84172   n = (int)(sEnd.z - pBegin->z);
84173   z = pBegin->z;
84174   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
84175   sEnd.z = &z[n-1];
84176   sEnd.n = 1;
84177
84178   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
84179   sqlite3EndTable(pParse, 0, &sEnd, 0);
84180   return;
84181 }
84182 #endif /* SQLITE_OMIT_VIEW */
84183
84184 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
84185 /*
84186 ** The Table structure pTable is really a VIEW.  Fill in the names of
84187 ** the columns of the view in the pTable structure.  Return the number
84188 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
84189 */
84190 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
84191   Table *pSelTab;   /* A fake table from which we get the result set */
84192   Select *pSel;     /* Copy of the SELECT that implements the view */
84193   int nErr = 0;     /* Number of errors encountered */
84194   int n;            /* Temporarily holds the number of cursors assigned */
84195   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
84196   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
84197
84198   assert( pTable );
84199
84200 #ifndef SQLITE_OMIT_VIRTUALTABLE
84201   if( sqlite3VtabCallConnect(pParse, pTable) ){
84202     return SQLITE_ERROR;
84203   }
84204   if( IsVirtual(pTable) ) return 0;
84205 #endif
84206
84207 #ifndef SQLITE_OMIT_VIEW
84208   /* A positive nCol means the columns names for this view are
84209   ** already known.
84210   */
84211   if( pTable->nCol>0 ) return 0;
84212
84213   /* A negative nCol is a special marker meaning that we are currently
84214   ** trying to compute the column names.  If we enter this routine with
84215   ** a negative nCol, it means two or more views form a loop, like this:
84216   **
84217   **     CREATE VIEW one AS SELECT * FROM two;
84218   **     CREATE VIEW two AS SELECT * FROM one;
84219   **
84220   ** Actually, the error above is now caught prior to reaching this point.
84221   ** But the following test is still important as it does come up
84222   ** in the following:
84223   **
84224   **     CREATE TABLE main.ex1(a);
84225   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
84226   **     SELECT * FROM temp.ex1;
84227   */
84228   if( pTable->nCol<0 ){
84229     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
84230     return 1;
84231   }
84232   assert( pTable->nCol>=0 );
84233
84234   /* If we get this far, it means we need to compute the table names.
84235   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
84236   ** "*" elements in the results set of the view and will assign cursors
84237   ** to the elements of the FROM clause.  But we do not want these changes
84238   ** to be permanent.  So the computation is done on a copy of the SELECT
84239   ** statement that defines the view.
84240   */
84241   assert( pTable->pSelect );
84242   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
84243   if( pSel ){
84244     u8 enableLookaside = db->lookaside.bEnabled;
84245     n = pParse->nTab;
84246     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
84247     pTable->nCol = -1;
84248     db->lookaside.bEnabled = 0;
84249 #ifndef SQLITE_OMIT_AUTHORIZATION
84250     xAuth = db->xAuth;
84251     db->xAuth = 0;
84252     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84253     db->xAuth = xAuth;
84254 #else
84255     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84256 #endif
84257     db->lookaside.bEnabled = enableLookaside;
84258     pParse->nTab = n;
84259     if( pSelTab ){
84260       assert( pTable->aCol==0 );
84261       pTable->nCol = pSelTab->nCol;
84262       pTable->aCol = pSelTab->aCol;
84263       pSelTab->nCol = 0;
84264       pSelTab->aCol = 0;
84265       sqlite3DeleteTable(db, pSelTab);
84266       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
84267       pTable->pSchema->flags |= DB_UnresetViews;
84268     }else{
84269       pTable->nCol = 0;
84270       nErr++;
84271     }
84272     sqlite3SelectDelete(db, pSel);
84273   } else {
84274     nErr++;
84275   }
84276 #endif /* SQLITE_OMIT_VIEW */
84277   return nErr;
84278 }
84279 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
84280
84281 #ifndef SQLITE_OMIT_VIEW
84282 /*
84283 ** Clear the column names from every VIEW in database idx.
84284 */
84285 static void sqliteViewResetAll(sqlite3 *db, int idx){
84286   HashElem *i;
84287   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
84288   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
84289   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
84290     Table *pTab = sqliteHashData(i);
84291     if( pTab->pSelect ){
84292       sqliteDeleteColumnNames(db, pTab);
84293       pTab->aCol = 0;
84294       pTab->nCol = 0;
84295     }
84296   }
84297   DbClearProperty(db, idx, DB_UnresetViews);
84298 }
84299 #else
84300 # define sqliteViewResetAll(A,B)
84301 #endif /* SQLITE_OMIT_VIEW */
84302
84303 /*
84304 ** This function is called by the VDBE to adjust the internal schema
84305 ** used by SQLite when the btree layer moves a table root page. The
84306 ** root-page of a table or index in database iDb has changed from iFrom
84307 ** to iTo.
84308 **
84309 ** Ticket #1728:  The symbol table might still contain information
84310 ** on tables and/or indices that are the process of being deleted.
84311 ** If you are unlucky, one of those deleted indices or tables might
84312 ** have the same rootpage number as the real table or index that is
84313 ** being moved.  So we cannot stop searching after the first match
84314 ** because the first match might be for one of the deleted indices
84315 ** or tables and not the table/index that is actually being moved.
84316 ** We must continue looping until all tables and indices with
84317 ** rootpage==iFrom have been converted to have a rootpage of iTo
84318 ** in order to be certain that we got the right one.
84319 */
84320 #ifndef SQLITE_OMIT_AUTOVACUUM
84321 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
84322   HashElem *pElem;
84323   Hash *pHash;
84324   Db *pDb;
84325
84326   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84327   pDb = &db->aDb[iDb];
84328   pHash = &pDb->pSchema->tblHash;
84329   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84330     Table *pTab = sqliteHashData(pElem);
84331     if( pTab->tnum==iFrom ){
84332       pTab->tnum = iTo;
84333     }
84334   }
84335   pHash = &pDb->pSchema->idxHash;
84336   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84337     Index *pIdx = sqliteHashData(pElem);
84338     if( pIdx->tnum==iFrom ){
84339       pIdx->tnum = iTo;
84340     }
84341   }
84342 }
84343 #endif
84344
84345 /*
84346 ** Write code to erase the table with root-page iTable from database iDb.
84347 ** Also write code to modify the sqlite_master table and internal schema
84348 ** if a root-page of another table is moved by the btree-layer whilst
84349 ** erasing iTable (this can happen with an auto-vacuum database).
84350 */
84351 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
84352   Vdbe *v = sqlite3GetVdbe(pParse);
84353   int r1 = sqlite3GetTempReg(pParse);
84354   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
84355   sqlite3MayAbort(pParse);
84356 #ifndef SQLITE_OMIT_AUTOVACUUM
84357   /* OP_Destroy stores an in integer r1. If this integer
84358   ** is non-zero, then it is the root page number of a table moved to
84359   ** location iTable. The following code modifies the sqlite_master table to
84360   ** reflect this.
84361   **
84362   ** The "#NNN" in the SQL is a special constant that means whatever value
84363   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
84364   ** token for additional information.
84365   */
84366   sqlite3NestedParse(pParse,
84367      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
84368      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
84369 #endif
84370   sqlite3ReleaseTempReg(pParse, r1);
84371 }
84372
84373 /*
84374 ** Write VDBE code to erase table pTab and all associated indices on disk.
84375 ** Code to update the sqlite_master tables and internal schema definitions
84376 ** in case a root-page belonging to another table is moved by the btree layer
84377 ** is also added (this can happen with an auto-vacuum database).
84378 */
84379 static void destroyTable(Parse *pParse, Table *pTab){
84380 #ifdef SQLITE_OMIT_AUTOVACUUM
84381   Index *pIdx;
84382   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84383   destroyRootPage(pParse, pTab->tnum, iDb);
84384   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84385     destroyRootPage(pParse, pIdx->tnum, iDb);
84386   }
84387 #else
84388   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
84389   ** is not defined), then it is important to call OP_Destroy on the
84390   ** table and index root-pages in order, starting with the numerically
84391   ** largest root-page number. This guarantees that none of the root-pages
84392   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
84393   ** following were coded:
84394   **
84395   ** OP_Destroy 4 0
84396   ** ...
84397   ** OP_Destroy 5 0
84398   **
84399   ** and root page 5 happened to be the largest root-page number in the
84400   ** database, then root page 5 would be moved to page 4 by the
84401   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
84402   ** a free-list page.
84403   */
84404   int iTab = pTab->tnum;
84405   int iDestroyed = 0;
84406
84407   while( 1 ){
84408     Index *pIdx;
84409     int iLargest = 0;
84410
84411     if( iDestroyed==0 || iTab<iDestroyed ){
84412       iLargest = iTab;
84413     }
84414     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84415       int iIdx = pIdx->tnum;
84416       assert( pIdx->pSchema==pTab->pSchema );
84417       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
84418         iLargest = iIdx;
84419       }
84420     }
84421     if( iLargest==0 ){
84422       return;
84423     }else{
84424       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84425       assert( iDb>=0 && iDb<pParse->db->nDb );
84426       destroyRootPage(pParse, iLargest, iDb);
84427       iDestroyed = iLargest;
84428     }
84429   }
84430 #endif
84431 }
84432
84433 /*
84434 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
84435 ** after a DROP INDEX or DROP TABLE command.
84436 */
84437 static void sqlite3ClearStatTables(
84438   Parse *pParse,         /* The parsing context */
84439   int iDb,               /* The database number */
84440   const char *zType,     /* "idx" or "tbl" */
84441   const char *zName      /* Name of index or table */
84442 ){
84443   int i;
84444   const char *zDbName = pParse->db->aDb[iDb].zName;
84445   for(i=1; i<=3; i++){
84446     char zTab[24];
84447     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
84448     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
84449       sqlite3NestedParse(pParse,
84450         "DELETE FROM %Q.%s WHERE %s=%Q",
84451         zDbName, zTab, zType, zName
84452       );
84453     }
84454   }
84455 }
84456
84457 /*
84458 ** Generate code to drop a table.
84459 */
84460 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
84461   Vdbe *v;
84462   sqlite3 *db = pParse->db;
84463   Trigger *pTrigger;
84464   Db *pDb = &db->aDb[iDb];
84465
84466   v = sqlite3GetVdbe(pParse);
84467   assert( v!=0 );
84468   sqlite3BeginWriteOperation(pParse, 1, iDb);
84469
84470 #ifndef SQLITE_OMIT_VIRTUALTABLE
84471   if( IsVirtual(pTab) ){
84472     sqlite3VdbeAddOp0(v, OP_VBegin);
84473   }
84474 #endif
84475
84476   /* Drop all triggers associated with the table being dropped. Code
84477   ** is generated to remove entries from sqlite_master and/or
84478   ** sqlite_temp_master if required.
84479   */
84480   pTrigger = sqlite3TriggerList(pParse, pTab);
84481   while( pTrigger ){
84482     assert( pTrigger->pSchema==pTab->pSchema ||
84483         pTrigger->pSchema==db->aDb[1].pSchema );
84484     sqlite3DropTriggerPtr(pParse, pTrigger);
84485     pTrigger = pTrigger->pNext;
84486   }
84487
84488 #ifndef SQLITE_OMIT_AUTOINCREMENT
84489   /* Remove any entries of the sqlite_sequence table associated with
84490   ** the table being dropped. This is done before the table is dropped
84491   ** at the btree level, in case the sqlite_sequence table needs to
84492   ** move as a result of the drop (can happen in auto-vacuum mode).
84493   */
84494   if( pTab->tabFlags & TF_Autoincrement ){
84495     sqlite3NestedParse(pParse,
84496       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
84497       pDb->zName, pTab->zName
84498     );
84499   }
84500 #endif
84501
84502   /* Drop all SQLITE_MASTER table and index entries that refer to the
84503   ** table. The program name loops through the master table and deletes
84504   ** every row that refers to a table of the same name as the one being
84505   ** dropped. Triggers are handled seperately because a trigger can be
84506   ** created in the temp database that refers to a table in another
84507   ** database.
84508   */
84509   sqlite3NestedParse(pParse,
84510       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
84511       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
84512   if( !isView && !IsVirtual(pTab) ){
84513     destroyTable(pParse, pTab);
84514   }
84515
84516   /* Remove the table entry from SQLite's internal schema and modify
84517   ** the schema cookie.
84518   */
84519   if( IsVirtual(pTab) ){
84520     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
84521   }
84522   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
84523   sqlite3ChangeCookie(pParse, iDb);
84524   sqliteViewResetAll(db, iDb);
84525 }
84526
84527 /*
84528 ** This routine is called to do the work of a DROP TABLE statement.
84529 ** pName is the name of the table to be dropped.
84530 */
84531 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
84532   Table *pTab;
84533   Vdbe *v;
84534   sqlite3 *db = pParse->db;
84535   int iDb;
84536
84537   if( db->mallocFailed ){
84538     goto exit_drop_table;
84539   }
84540   assert( pParse->nErr==0 );
84541   assert( pName->nSrc==1 );
84542   if( noErr ) db->suppressErr++;
84543   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
84544   if( noErr ) db->suppressErr--;
84545
84546   if( pTab==0 ){
84547     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
84548     goto exit_drop_table;
84549   }
84550   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84551   assert( iDb>=0 && iDb<db->nDb );
84552
84553   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
84554   ** it is initialized.
84555   */
84556   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
84557     goto exit_drop_table;
84558   }
84559 #ifndef SQLITE_OMIT_AUTHORIZATION
84560   {
84561     int code;
84562     const char *zTab = SCHEMA_TABLE(iDb);
84563     const char *zDb = db->aDb[iDb].zName;
84564     const char *zArg2 = 0;
84565     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
84566       goto exit_drop_table;
84567     }
84568     if( isView ){
84569       if( !OMIT_TEMPDB && iDb==1 ){
84570         code = SQLITE_DROP_TEMP_VIEW;
84571       }else{
84572         code = SQLITE_DROP_VIEW;
84573       }
84574 #ifndef SQLITE_OMIT_VIRTUALTABLE
84575     }else if( IsVirtual(pTab) ){
84576       code = SQLITE_DROP_VTABLE;
84577       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
84578 #endif
84579     }else{
84580       if( !OMIT_TEMPDB && iDb==1 ){
84581         code = SQLITE_DROP_TEMP_TABLE;
84582       }else{
84583         code = SQLITE_DROP_TABLE;
84584       }
84585     }
84586     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
84587       goto exit_drop_table;
84588     }
84589     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
84590       goto exit_drop_table;
84591     }
84592   }
84593 #endif
84594   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
84595     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
84596     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
84597     goto exit_drop_table;
84598   }
84599
84600 #ifndef SQLITE_OMIT_VIEW
84601   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
84602   ** on a table.
84603   */
84604   if( isView && pTab->pSelect==0 ){
84605     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
84606     goto exit_drop_table;
84607   }
84608   if( !isView && pTab->pSelect ){
84609     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
84610     goto exit_drop_table;
84611   }
84612 #endif
84613
84614   /* Generate code to remove the table from the master table
84615   ** on disk.
84616   */
84617   v = sqlite3GetVdbe(pParse);
84618   if( v ){
84619     sqlite3BeginWriteOperation(pParse, 1, iDb);
84620     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
84621     sqlite3FkDropTable(pParse, pName, pTab);
84622     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
84623   }
84624
84625 exit_drop_table:
84626   sqlite3SrcListDelete(db, pName);
84627 }
84628
84629 /*
84630 ** This routine is called to create a new foreign key on the table
84631 ** currently under construction.  pFromCol determines which columns
84632 ** in the current table point to the foreign key.  If pFromCol==0 then
84633 ** connect the key to the last column inserted.  pTo is the name of
84634 ** the table referred to.  pToCol is a list of tables in the other
84635 ** pTo table that the foreign key points to.  flags contains all
84636 ** information about the conflict resolution algorithms specified
84637 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
84638 **
84639 ** An FKey structure is created and added to the table currently
84640 ** under construction in the pParse->pNewTable field.
84641 **
84642 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
84643 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
84644 */
84645 SQLITE_PRIVATE void sqlite3CreateForeignKey(
84646   Parse *pParse,       /* Parsing context */
84647   ExprList *pFromCol,  /* Columns in this table that point to other table */
84648   Token *pTo,          /* Name of the other table */
84649   ExprList *pToCol,    /* Columns in the other table */
84650   int flags            /* Conflict resolution algorithms. */
84651 ){
84652   sqlite3 *db = pParse->db;
84653 #ifndef SQLITE_OMIT_FOREIGN_KEY
84654   FKey *pFKey = 0;
84655   FKey *pNextTo;
84656   Table *p = pParse->pNewTable;
84657   int nByte;
84658   int i;
84659   int nCol;
84660   char *z;
84661
84662   assert( pTo!=0 );
84663   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
84664   if( pFromCol==0 ){
84665     int iCol = p->nCol-1;
84666     if( NEVER(iCol<0) ) goto fk_end;
84667     if( pToCol && pToCol->nExpr!=1 ){
84668       sqlite3ErrorMsg(pParse, "foreign key on %s"
84669          " should reference only one column of table %T",
84670          p->aCol[iCol].zName, pTo);
84671       goto fk_end;
84672     }
84673     nCol = 1;
84674   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
84675     sqlite3ErrorMsg(pParse,
84676         "number of columns in foreign key does not match the number of "
84677         "columns in the referenced table");
84678     goto fk_end;
84679   }else{
84680     nCol = pFromCol->nExpr;
84681   }
84682   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
84683   if( pToCol ){
84684     for(i=0; i<pToCol->nExpr; i++){
84685       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
84686     }
84687   }
84688   pFKey = sqlite3DbMallocZero(db, nByte );
84689   if( pFKey==0 ){
84690     goto fk_end;
84691   }
84692   pFKey->pFrom = p;
84693   pFKey->pNextFrom = p->pFKey;
84694   z = (char*)&pFKey->aCol[nCol];
84695   pFKey->zTo = z;
84696   memcpy(z, pTo->z, pTo->n);
84697   z[pTo->n] = 0;
84698   sqlite3Dequote(z);
84699   z += pTo->n+1;
84700   pFKey->nCol = nCol;
84701   if( pFromCol==0 ){
84702     pFKey->aCol[0].iFrom = p->nCol-1;
84703   }else{
84704     for(i=0; i<nCol; i++){
84705       int j;
84706       for(j=0; j<p->nCol; j++){
84707         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
84708           pFKey->aCol[i].iFrom = j;
84709           break;
84710         }
84711       }
84712       if( j>=p->nCol ){
84713         sqlite3ErrorMsg(pParse,
84714           "unknown column \"%s\" in foreign key definition",
84715           pFromCol->a[i].zName);
84716         goto fk_end;
84717       }
84718     }
84719   }
84720   if( pToCol ){
84721     for(i=0; i<nCol; i++){
84722       int n = sqlite3Strlen30(pToCol->a[i].zName);
84723       pFKey->aCol[i].zCol = z;
84724       memcpy(z, pToCol->a[i].zName, n);
84725       z[n] = 0;
84726       z += n+1;
84727     }
84728   }
84729   pFKey->isDeferred = 0;
84730   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
84731   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
84732
84733   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
84734   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
84735       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
84736   );
84737   if( pNextTo==pFKey ){
84738     db->mallocFailed = 1;
84739     goto fk_end;
84740   }
84741   if( pNextTo ){
84742     assert( pNextTo->pPrevTo==0 );
84743     pFKey->pNextTo = pNextTo;
84744     pNextTo->pPrevTo = pFKey;
84745   }
84746
84747   /* Link the foreign key to the table as the last step.
84748   */
84749   p->pFKey = pFKey;
84750   pFKey = 0;
84751
84752 fk_end:
84753   sqlite3DbFree(db, pFKey);
84754 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84755   sqlite3ExprListDelete(db, pFromCol);
84756   sqlite3ExprListDelete(db, pToCol);
84757 }
84758
84759 /*
84760 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
84761 ** clause is seen as part of a foreign key definition.  The isDeferred
84762 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
84763 ** The behavior of the most recently created foreign key is adjusted
84764 ** accordingly.
84765 */
84766 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
84767 #ifndef SQLITE_OMIT_FOREIGN_KEY
84768   Table *pTab;
84769   FKey *pFKey;
84770   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
84771   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
84772   pFKey->isDeferred = (u8)isDeferred;
84773 #endif
84774 }
84775
84776 /*
84777 ** Generate code that will erase and refill index *pIdx.  This is
84778 ** used to initialize a newly created index or to recompute the
84779 ** content of an index in response to a REINDEX command.
84780 **
84781 ** if memRootPage is not negative, it means that the index is newly
84782 ** created.  The register specified by memRootPage contains the
84783 ** root page number of the index.  If memRootPage is negative, then
84784 ** the index already exists and must be cleared before being refilled and
84785 ** the root page number of the index is taken from pIndex->tnum.
84786 */
84787 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
84788   Table *pTab = pIndex->pTable;  /* The table that is indexed */
84789   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
84790   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
84791   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
84792   int addr1;                     /* Address of top of loop */
84793   int addr2;                     /* Address to jump to for next iteration */
84794   int tnum;                      /* Root page of index */
84795   Vdbe *v;                       /* Generate code into this virtual machine */
84796   KeyInfo *pKey;                 /* KeyInfo for index */
84797 #ifdef SQLITE_OMIT_MERGE_SORT
84798   int regIdxKey;                 /* Registers containing the index key */
84799 #endif
84800   int regRecord;                 /* Register holding assemblied index record */
84801   sqlite3 *db = pParse->db;      /* The database connection */
84802   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
84803
84804 #ifndef SQLITE_OMIT_AUTHORIZATION
84805   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
84806       db->aDb[iDb].zName ) ){
84807     return;
84808   }
84809 #endif
84810
84811   /* Require a write-lock on the table to perform this operation */
84812   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
84813
84814   v = sqlite3GetVdbe(pParse);
84815   if( v==0 ) return;
84816   if( memRootPage>=0 ){
84817     tnum = memRootPage;
84818   }else{
84819     tnum = pIndex->tnum;
84820     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
84821   }
84822   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
84823   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
84824                     (char *)pKey, P4_KEYINFO_HANDOFF);
84825   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
84826
84827 #ifndef SQLITE_OMIT_MERGE_SORT
84828   /* Open the sorter cursor if we are to use one. */
84829   iSorter = pParse->nTab++;
84830   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
84831 #else
84832   iSorter = iTab;
84833 #endif
84834
84835   /* Open the table. Loop through all rows of the table, inserting index
84836   ** records into the sorter. */
84837   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
84838   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
84839   regRecord = sqlite3GetTempReg(pParse);
84840
84841 #ifndef SQLITE_OMIT_MERGE_SORT
84842   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
84843   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
84844   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
84845   sqlite3VdbeJumpHere(v, addr1);
84846   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
84847   if( pIndex->onError!=OE_None ){
84848     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
84849     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
84850     addr2 = sqlite3VdbeCurrentAddr(v);
84851     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
84852     sqlite3HaltConstraint(
84853         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
84854     );
84855   }else{
84856     addr2 = sqlite3VdbeCurrentAddr(v);
84857   }
84858   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
84859   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
84860   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84861 #else
84862   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
84863   addr2 = addr1 + 1;
84864   if( pIndex->onError!=OE_None ){
84865     const int regRowid = regIdxKey + pIndex->nColumn;
84866     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
84867     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
84868
84869     /* The registers accessed by the OP_IsUnique opcode were allocated
84870     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
84871     ** call above. Just before that function was freed they were released
84872     ** (made available to the compiler for reuse) using
84873     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
84874     ** opcode use the values stored within seems dangerous. However, since
84875     ** we can be sure that no other temp registers have been allocated
84876     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
84877     */
84878     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
84879     sqlite3HaltConstraint(
84880         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
84881   }
84882   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
84883   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84884 #endif
84885   sqlite3ReleaseTempReg(pParse, regRecord);
84886   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
84887   sqlite3VdbeJumpHere(v, addr1);
84888
84889   sqlite3VdbeAddOp1(v, OP_Close, iTab);
84890   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
84891   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
84892 }
84893
84894 /*
84895 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
84896 ** and pTblList is the name of the table that is to be indexed.  Both will
84897 ** be NULL for a primary key or an index that is created to satisfy a
84898 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
84899 ** as the table to be indexed.  pParse->pNewTable is a table that is
84900 ** currently being constructed by a CREATE TABLE statement.
84901 **
84902 ** pList is a list of columns to be indexed.  pList will be NULL if this
84903 ** is a primary key or unique-constraint on the most recent column added
84904 ** to the table currently under construction.
84905 **
84906 ** If the index is created successfully, return a pointer to the new Index
84907 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
84908 ** as the tables primary key (Index.autoIndex==2).
84909 */
84910 SQLITE_PRIVATE Index *sqlite3CreateIndex(
84911   Parse *pParse,     /* All information about this parse */
84912   Token *pName1,     /* First part of index name. May be NULL */
84913   Token *pName2,     /* Second part of index name. May be NULL */
84914   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
84915   ExprList *pList,   /* A list of columns to be indexed */
84916   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
84917   Token *pStart,     /* The CREATE token that begins this statement */
84918   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
84919   int sortOrder,     /* Sort order of primary key when pList==NULL */
84920   int ifNotExist     /* Omit error if index already exists */
84921 ){
84922   Index *pRet = 0;     /* Pointer to return */
84923   Table *pTab = 0;     /* Table to be indexed */
84924   Index *pIndex = 0;   /* The index to be created */
84925   char *zName = 0;     /* Name of the index */
84926   int nName;           /* Number of characters in zName */
84927   int i, j;
84928   Token nullId;        /* Fake token for an empty ID list */
84929   DbFixer sFix;        /* For assigning database names to pTable */
84930   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
84931   sqlite3 *db = pParse->db;
84932   Db *pDb;             /* The specific table containing the indexed database */
84933   int iDb;             /* Index of the database that is being written */
84934   Token *pName = 0;    /* Unqualified name of the index to create */
84935   struct ExprList_item *pListItem; /* For looping over pList */
84936   int nCol;
84937   int nExtra = 0;
84938   char *zExtra;
84939
84940   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
84941   assert( pParse->nErr==0 );      /* Never called with prior errors */
84942   if( db->mallocFailed || IN_DECLARE_VTAB ){
84943     goto exit_create_index;
84944   }
84945   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84946     goto exit_create_index;
84947   }
84948
84949   /*
84950   ** Find the table that is to be indexed.  Return early if not found.
84951   */
84952   if( pTblName!=0 ){
84953
84954     /* Use the two-part index name to determine the database
84955     ** to search for the table. 'Fix' the table name to this db
84956     ** before looking up the table.
84957     */
84958     assert( pName1 && pName2 );
84959     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84960     if( iDb<0 ) goto exit_create_index;
84961     assert( pName && pName->z );
84962
84963 #ifndef SQLITE_OMIT_TEMPDB
84964     /* If the index name was unqualified, check if the table
84965     ** is a temp table. If so, set the database to 1. Do not do this
84966     ** if initialising a database schema.
84967     */
84968     if( !db->init.busy ){
84969       pTab = sqlite3SrcListLookup(pParse, pTblName);
84970       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
84971         iDb = 1;
84972       }
84973     }
84974 #endif
84975
84976     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
84977         sqlite3FixSrcList(&sFix, pTblName)
84978     ){
84979       /* Because the parser constructs pTblName from a single identifier,
84980       ** sqlite3FixSrcList can never fail. */
84981       assert(0);
84982     }
84983     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
84984     assert( db->mallocFailed==0 || pTab==0 );
84985     if( pTab==0 ) goto exit_create_index;
84986     assert( db->aDb[iDb].pSchema==pTab->pSchema );
84987   }else{
84988     assert( pName==0 );
84989     assert( pStart==0 );
84990     pTab = pParse->pNewTable;
84991     if( !pTab ) goto exit_create_index;
84992     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84993   }
84994   pDb = &db->aDb[iDb];
84995
84996   assert( pTab!=0 );
84997   assert( pParse->nErr==0 );
84998   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
84999        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
85000     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
85001     goto exit_create_index;
85002   }
85003 #ifndef SQLITE_OMIT_VIEW
85004   if( pTab->pSelect ){
85005     sqlite3ErrorMsg(pParse, "views may not be indexed");
85006     goto exit_create_index;
85007   }
85008 #endif
85009 #ifndef SQLITE_OMIT_VIRTUALTABLE
85010   if( IsVirtual(pTab) ){
85011     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
85012     goto exit_create_index;
85013   }
85014 #endif
85015
85016   /*
85017   ** Find the name of the index.  Make sure there is not already another
85018   ** index or table with the same name.
85019   **
85020   ** Exception:  If we are reading the names of permanent indices from the
85021   ** sqlite_master table (because some other process changed the schema) and
85022   ** one of the index names collides with the name of a temporary table or
85023   ** index, then we will continue to process this index.
85024   **
85025   ** If pName==0 it means that we are
85026   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
85027   ** own name.
85028   */
85029   if( pName ){
85030     zName = sqlite3NameFromToken(db, pName);
85031     if( zName==0 ) goto exit_create_index;
85032     assert( pName->z!=0 );
85033     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
85034       goto exit_create_index;
85035     }
85036     if( !db->init.busy ){
85037       if( sqlite3FindTable(db, zName, 0)!=0 ){
85038         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
85039         goto exit_create_index;
85040       }
85041     }
85042     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
85043       if( !ifNotExist ){
85044         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
85045       }else{
85046         assert( !db->init.busy );
85047         sqlite3CodeVerifySchema(pParse, iDb);
85048       }
85049       goto exit_create_index;
85050     }
85051   }else{
85052     int n;
85053     Index *pLoop;
85054     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
85055     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
85056     if( zName==0 ){
85057       goto exit_create_index;
85058     }
85059   }
85060
85061   /* Check for authorization to create an index.
85062   */
85063 #ifndef SQLITE_OMIT_AUTHORIZATION
85064   {
85065     const char *zDb = pDb->zName;
85066     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
85067       goto exit_create_index;
85068     }
85069     i = SQLITE_CREATE_INDEX;
85070     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
85071     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
85072       goto exit_create_index;
85073     }
85074   }
85075 #endif
85076
85077   /* If pList==0, it means this routine was called to make a primary
85078   ** key out of the last column added to the table under construction.
85079   ** So create a fake list to simulate this.
85080   */
85081   if( pList==0 ){
85082     nullId.z = pTab->aCol[pTab->nCol-1].zName;
85083     nullId.n = sqlite3Strlen30((char*)nullId.z);
85084     pList = sqlite3ExprListAppend(pParse, 0, 0);
85085     if( pList==0 ) goto exit_create_index;
85086     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
85087     pList->a[0].sortOrder = (u8)sortOrder;
85088   }
85089
85090   /* Figure out how many bytes of space are required to store explicitly
85091   ** specified collation sequence names.
85092   */
85093   for(i=0; i<pList->nExpr; i++){
85094     Expr *pExpr = pList->a[i].pExpr;
85095     if( pExpr ){
85096       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
85097       if( pColl ){
85098         nExtra += (1 + sqlite3Strlen30(pColl->zName));
85099       }
85100     }
85101   }
85102
85103   /*
85104   ** Allocate the index structure.
85105   */
85106   nName = sqlite3Strlen30(zName);
85107   nCol = pList->nExpr;
85108   pIndex = sqlite3DbMallocZero(db,
85109       ROUND8(sizeof(Index)) +              /* Index structure  */
85110       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
85111       sizeof(char *)*nCol +                /* Index.azColl     */
85112       sizeof(int)*nCol +                   /* Index.aiColumn   */
85113       sizeof(u8)*nCol +                    /* Index.aSortOrder */
85114       nName + 1 +                          /* Index.zName      */
85115       nExtra                               /* Collation sequence names */
85116   );
85117   if( db->mallocFailed ){
85118     goto exit_create_index;
85119   }
85120   zExtra = (char*)pIndex;
85121   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
85122   pIndex->azColl = (char**)
85123      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
85124   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
85125   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
85126   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
85127   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
85128   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
85129   zExtra = (char *)(&pIndex->zName[nName+1]);
85130   memcpy(pIndex->zName, zName, nName+1);
85131   pIndex->pTable = pTab;
85132   pIndex->nColumn = pList->nExpr;
85133   pIndex->onError = (u8)onError;
85134   pIndex->autoIndex = (u8)(pName==0);
85135   pIndex->pSchema = db->aDb[iDb].pSchema;
85136   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85137
85138   /* Check to see if we should honor DESC requests on index columns
85139   */
85140   if( pDb->pSchema->file_format>=4 ){
85141     sortOrderMask = -1;   /* Honor DESC */
85142   }else{
85143     sortOrderMask = 0;    /* Ignore DESC */
85144   }
85145
85146   /* Scan the names of the columns of the table to be indexed and
85147   ** load the column indices into the Index structure.  Report an error
85148   ** if any column is not found.
85149   **
85150   ** TODO:  Add a test to make sure that the same column is not named
85151   ** more than once within the same index.  Only the first instance of
85152   ** the column will ever be used by the optimizer.  Note that using the
85153   ** same column more than once cannot be an error because that would
85154   ** break backwards compatibility - it needs to be a warning.
85155   */
85156   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
85157     const char *zColName = pListItem->zName;
85158     Column *pTabCol;
85159     int requestedSortOrder;
85160     CollSeq *pColl;                /* Collating sequence */
85161     char *zColl;                   /* Collation sequence name */
85162
85163     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
85164       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
85165     }
85166     if( j>=pTab->nCol ){
85167       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
85168         pTab->zName, zColName);
85169       pParse->checkSchema = 1;
85170       goto exit_create_index;
85171     }
85172     pIndex->aiColumn[i] = j;
85173     if( pListItem->pExpr
85174      && (pColl = sqlite3ExprCollSeq(pParse, pListItem->pExpr))!=0
85175     ){
85176       int nColl;
85177       zColl = pColl->zName;
85178       nColl = sqlite3Strlen30(zColl) + 1;
85179       assert( nExtra>=nColl );
85180       memcpy(zExtra, zColl, nColl);
85181       zColl = zExtra;
85182       zExtra += nColl;
85183       nExtra -= nColl;
85184     }else{
85185       zColl = pTab->aCol[j].zColl;
85186       if( !zColl ){
85187         zColl = "BINARY";
85188       }
85189     }
85190     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
85191       goto exit_create_index;
85192     }
85193     pIndex->azColl[i] = zColl;
85194     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
85195     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
85196   }
85197   sqlite3DefaultRowEst(pIndex);
85198
85199   if( pTab==pParse->pNewTable ){
85200     /* This routine has been called to create an automatic index as a
85201     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
85202     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
85203     ** i.e. one of:
85204     **
85205     ** CREATE TABLE t(x PRIMARY KEY, y);
85206     ** CREATE TABLE t(x, y, UNIQUE(x, y));
85207     **
85208     ** Either way, check to see if the table already has such an index. If
85209     ** so, don't bother creating this one. This only applies to
85210     ** automatically created indices. Users can do as they wish with
85211     ** explicit indices.
85212     **
85213     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
85214     ** (and thus suppressing the second one) even if they have different
85215     ** sort orders.
85216     **
85217     ** If there are different collating sequences or if the columns of
85218     ** the constraint occur in different orders, then the constraints are
85219     ** considered distinct and both result in separate indices.
85220     */
85221     Index *pIdx;
85222     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85223       int k;
85224       assert( pIdx->onError!=OE_None );
85225       assert( pIdx->autoIndex );
85226       assert( pIndex->onError!=OE_None );
85227
85228       if( pIdx->nColumn!=pIndex->nColumn ) continue;
85229       for(k=0; k<pIdx->nColumn; k++){
85230         const char *z1;
85231         const char *z2;
85232         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
85233         z1 = pIdx->azColl[k];
85234         z2 = pIndex->azColl[k];
85235         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
85236       }
85237       if( k==pIdx->nColumn ){
85238         if( pIdx->onError!=pIndex->onError ){
85239           /* This constraint creates the same index as a previous
85240           ** constraint specified somewhere in the CREATE TABLE statement.
85241           ** However the ON CONFLICT clauses are different. If both this
85242           ** constraint and the previous equivalent constraint have explicit
85243           ** ON CONFLICT clauses this is an error. Otherwise, use the
85244           ** explicitly specified behaviour for the index.
85245           */
85246           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
85247             sqlite3ErrorMsg(pParse,
85248                 "conflicting ON CONFLICT clauses specified", 0);
85249           }
85250           if( pIdx->onError==OE_Default ){
85251             pIdx->onError = pIndex->onError;
85252           }
85253         }
85254         goto exit_create_index;
85255       }
85256     }
85257   }
85258
85259   /* Link the new Index structure to its table and to the other
85260   ** in-memory database structures.
85261   */
85262   if( db->init.busy ){
85263     Index *p;
85264     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
85265     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
85266                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
85267                           pIndex);
85268     if( p ){
85269       assert( p==pIndex );  /* Malloc must have failed */
85270       db->mallocFailed = 1;
85271       goto exit_create_index;
85272     }
85273     db->flags |= SQLITE_InternChanges;
85274     if( pTblName!=0 ){
85275       pIndex->tnum = db->init.newTnum;
85276     }
85277   }
85278
85279   /* If the db->init.busy is 0 then create the index on disk.  This
85280   ** involves writing the index into the master table and filling in the
85281   ** index with the current table contents.
85282   **
85283   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
85284   ** command.  db->init.busy is 1 when a database is opened and
85285   ** CREATE INDEX statements are read out of the master table.  In
85286   ** the latter case the index already exists on disk, which is why
85287   ** we don't want to recreate it.
85288   **
85289   ** If pTblName==0 it means this index is generated as a primary key
85290   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
85291   ** has just been created, it contains no data and the index initialization
85292   ** step can be skipped.
85293   */
85294   else{ /* if( db->init.busy==0 ) */
85295     Vdbe *v;
85296     char *zStmt;
85297     int iMem = ++pParse->nMem;
85298
85299     v = sqlite3GetVdbe(pParse);
85300     if( v==0 ) goto exit_create_index;
85301
85302
85303     /* Create the rootpage for the index
85304     */
85305     sqlite3BeginWriteOperation(pParse, 1, iDb);
85306     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
85307
85308     /* Gather the complete text of the CREATE INDEX statement into
85309     ** the zStmt variable
85310     */
85311     if( pStart ){
85312       assert( pEnd!=0 );
85313       /* A named index with an explicit CREATE INDEX statement */
85314       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
85315         onError==OE_None ? "" : " UNIQUE",
85316         (int)(pEnd->z - pName->z) + 1,
85317         pName->z);
85318     }else{
85319       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
85320       /* zStmt = sqlite3MPrintf(""); */
85321       zStmt = 0;
85322     }
85323
85324     /* Add an entry in sqlite_master for this index
85325     */
85326     sqlite3NestedParse(pParse,
85327         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
85328         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85329         pIndex->zName,
85330         pTab->zName,
85331         iMem,
85332         zStmt
85333     );
85334     sqlite3DbFree(db, zStmt);
85335
85336     /* Fill the index with data and reparse the schema. Code an OP_Expire
85337     ** to invalidate all pre-compiled statements.
85338     */
85339     if( pTblName ){
85340       sqlite3RefillIndex(pParse, pIndex, iMem);
85341       sqlite3ChangeCookie(pParse, iDb);
85342       sqlite3VdbeAddParseSchemaOp(v, iDb,
85343          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
85344       sqlite3VdbeAddOp1(v, OP_Expire, 0);
85345     }
85346   }
85347
85348   /* When adding an index to the list of indices for a table, make
85349   ** sure all indices labeled OE_Replace come after all those labeled
85350   ** OE_Ignore.  This is necessary for the correct constraint check
85351   ** processing (in sqlite3GenerateConstraintChecks()) as part of
85352   ** UPDATE and INSERT statements.
85353   */
85354   if( db->init.busy || pTblName==0 ){
85355     if( onError!=OE_Replace || pTab->pIndex==0
85356          || pTab->pIndex->onError==OE_Replace){
85357       pIndex->pNext = pTab->pIndex;
85358       pTab->pIndex = pIndex;
85359     }else{
85360       Index *pOther = pTab->pIndex;
85361       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
85362         pOther = pOther->pNext;
85363       }
85364       pIndex->pNext = pOther->pNext;
85365       pOther->pNext = pIndex;
85366     }
85367     pRet = pIndex;
85368     pIndex = 0;
85369   }
85370
85371   /* Clean up before exiting */
85372 exit_create_index:
85373   if( pIndex ){
85374     sqlite3DbFree(db, pIndex->zColAff);
85375     sqlite3DbFree(db, pIndex);
85376   }
85377   sqlite3ExprListDelete(db, pList);
85378   sqlite3SrcListDelete(db, pTblName);
85379   sqlite3DbFree(db, zName);
85380   return pRet;
85381 }
85382
85383 /*
85384 ** Fill the Index.aiRowEst[] array with default information - information
85385 ** to be used when we have not run the ANALYZE command.
85386 **
85387 ** aiRowEst[0] is suppose to contain the number of elements in the index.
85388 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
85389 ** number of rows in the table that match any particular value of the
85390 ** first column of the index.  aiRowEst[2] is an estimate of the number
85391 ** of rows that match any particular combiniation of the first 2 columns
85392 ** of the index.  And so forth.  It must always be the case that
85393 *
85394 **           aiRowEst[N]<=aiRowEst[N-1]
85395 **           aiRowEst[N]>=1
85396 **
85397 ** Apart from that, we have little to go on besides intuition as to
85398 ** how aiRowEst[] should be initialized.  The numbers generated here
85399 ** are based on typical values found in actual indices.
85400 */
85401 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
85402   tRowcnt *a = pIdx->aiRowEst;
85403   int i;
85404   tRowcnt n;
85405   assert( a!=0 );
85406   a[0] = pIdx->pTable->nRowEst;
85407   if( a[0]<10 ) a[0] = 10;
85408   n = 10;
85409   for(i=1; i<=pIdx->nColumn; i++){
85410     a[i] = n;
85411     if( n>5 ) n--;
85412   }
85413   if( pIdx->onError!=OE_None ){
85414     a[pIdx->nColumn] = 1;
85415   }
85416 }
85417
85418 /*
85419 ** This routine will drop an existing named index.  This routine
85420 ** implements the DROP INDEX statement.
85421 */
85422 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
85423   Index *pIndex;
85424   Vdbe *v;
85425   sqlite3 *db = pParse->db;
85426   int iDb;
85427
85428   assert( pParse->nErr==0 );   /* Never called with prior errors */
85429   if( db->mallocFailed ){
85430     goto exit_drop_index;
85431   }
85432   assert( pName->nSrc==1 );
85433   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85434     goto exit_drop_index;
85435   }
85436   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
85437   if( pIndex==0 ){
85438     if( !ifExists ){
85439       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
85440     }else{
85441       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
85442     }
85443     pParse->checkSchema = 1;
85444     goto exit_drop_index;
85445   }
85446   if( pIndex->autoIndex ){
85447     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
85448       "or PRIMARY KEY constraint cannot be dropped", 0);
85449     goto exit_drop_index;
85450   }
85451   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
85452 #ifndef SQLITE_OMIT_AUTHORIZATION
85453   {
85454     int code = SQLITE_DROP_INDEX;
85455     Table *pTab = pIndex->pTable;
85456     const char *zDb = db->aDb[iDb].zName;
85457     const char *zTab = SCHEMA_TABLE(iDb);
85458     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
85459       goto exit_drop_index;
85460     }
85461     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
85462     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
85463       goto exit_drop_index;
85464     }
85465   }
85466 #endif
85467
85468   /* Generate code to remove the index and from the master table */
85469   v = sqlite3GetVdbe(pParse);
85470   if( v ){
85471     sqlite3BeginWriteOperation(pParse, 1, iDb);
85472     sqlite3NestedParse(pParse,
85473        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
85474        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
85475     );
85476     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
85477     sqlite3ChangeCookie(pParse, iDb);
85478     destroyRootPage(pParse, pIndex->tnum, iDb);
85479     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
85480   }
85481
85482 exit_drop_index:
85483   sqlite3SrcListDelete(db, pName);
85484 }
85485
85486 /*
85487 ** pArray is a pointer to an array of objects. Each object in the
85488 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
85489 ** to extend the array so that there is space for a new object at the end.
85490 **
85491 ** When this function is called, *pnEntry contains the current size of
85492 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
85493 ** in total).
85494 **
85495 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
85496 ** space allocated for the new object is zeroed, *pnEntry updated to
85497 ** reflect the new size of the array and a pointer to the new allocation
85498 ** returned. *pIdx is set to the index of the new array entry in this case.
85499 **
85500 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
85501 ** unchanged and a copy of pArray returned.
85502 */
85503 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
85504   sqlite3 *db,      /* Connection to notify of malloc failures */
85505   void *pArray,     /* Array of objects.  Might be reallocated */
85506   int szEntry,      /* Size of each object in the array */
85507   int *pnEntry,     /* Number of objects currently in use */
85508   int *pIdx         /* Write the index of a new slot here */
85509 ){
85510   char *z;
85511   int n = *pnEntry;
85512   if( (n & (n-1))==0 ){
85513     int sz = (n==0) ? 1 : 2*n;
85514     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
85515     if( pNew==0 ){
85516       *pIdx = -1;
85517       return pArray;
85518     }
85519     pArray = pNew;
85520   }
85521   z = (char*)pArray;
85522   memset(&z[n * szEntry], 0, szEntry);
85523   *pIdx = n;
85524   ++*pnEntry;
85525   return pArray;
85526 }
85527
85528 /*
85529 ** Append a new element to the given IdList.  Create a new IdList if
85530 ** need be.
85531 **
85532 ** A new IdList is returned, or NULL if malloc() fails.
85533 */
85534 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
85535   int i;
85536   if( pList==0 ){
85537     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
85538     if( pList==0 ) return 0;
85539   }
85540   pList->a = sqlite3ArrayAllocate(
85541       db,
85542       pList->a,
85543       sizeof(pList->a[0]),
85544       &pList->nId,
85545       &i
85546   );
85547   if( i<0 ){
85548     sqlite3IdListDelete(db, pList);
85549     return 0;
85550   }
85551   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
85552   return pList;
85553 }
85554
85555 /*
85556 ** Delete an IdList.
85557 */
85558 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
85559   int i;
85560   if( pList==0 ) return;
85561   for(i=0; i<pList->nId; i++){
85562     sqlite3DbFree(db, pList->a[i].zName);
85563   }
85564   sqlite3DbFree(db, pList->a);
85565   sqlite3DbFree(db, pList);
85566 }
85567
85568 /*
85569 ** Return the index in pList of the identifier named zId.  Return -1
85570 ** if not found.
85571 */
85572 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
85573   int i;
85574   if( pList==0 ) return -1;
85575   for(i=0; i<pList->nId; i++){
85576     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
85577   }
85578   return -1;
85579 }
85580
85581 /*
85582 ** Expand the space allocated for the given SrcList object by
85583 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
85584 ** New slots are zeroed.
85585 **
85586 ** For example, suppose a SrcList initially contains two entries: A,B.
85587 ** To append 3 new entries onto the end, do this:
85588 **
85589 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
85590 **
85591 ** After the call above it would contain:  A, B, nil, nil, nil.
85592 ** If the iStart argument had been 1 instead of 2, then the result
85593 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
85594 ** the iStart value would be 0.  The result then would
85595 ** be: nil, nil, nil, A, B.
85596 **
85597 ** If a memory allocation fails the SrcList is unchanged.  The
85598 ** db->mallocFailed flag will be set to true.
85599 */
85600 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
85601   sqlite3 *db,       /* Database connection to notify of OOM errors */
85602   SrcList *pSrc,     /* The SrcList to be enlarged */
85603   int nExtra,        /* Number of new slots to add to pSrc->a[] */
85604   int iStart         /* Index in pSrc->a[] of first new slot */
85605 ){
85606   int i;
85607
85608   /* Sanity checking on calling parameters */
85609   assert( iStart>=0 );
85610   assert( nExtra>=1 );
85611   assert( pSrc!=0 );
85612   assert( iStart<=pSrc->nSrc );
85613
85614   /* Allocate additional space if needed */
85615   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
85616     SrcList *pNew;
85617     int nAlloc = pSrc->nSrc+nExtra;
85618     int nGot;
85619     pNew = sqlite3DbRealloc(db, pSrc,
85620                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
85621     if( pNew==0 ){
85622       assert( db->mallocFailed );
85623       return pSrc;
85624     }
85625     pSrc = pNew;
85626     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85627     pSrc->nAlloc = (u16)nGot;
85628   }
85629
85630   /* Move existing slots that come after the newly inserted slots
85631   ** out of the way */
85632   for(i=pSrc->nSrc-1; i>=iStart; i--){
85633     pSrc->a[i+nExtra] = pSrc->a[i];
85634   }
85635   pSrc->nSrc += (i16)nExtra;
85636
85637   /* Zero the newly allocated slots */
85638   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85639   for(i=iStart; i<iStart+nExtra; i++){
85640     pSrc->a[i].iCursor = -1;
85641   }
85642
85643   /* Return a pointer to the enlarged SrcList */
85644   return pSrc;
85645 }
85646
85647
85648 /*
85649 ** Append a new table name to the given SrcList.  Create a new SrcList if
85650 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
85651 **
85652 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
85653 ** SrcList might be the same as the SrcList that was input or it might be
85654 ** a new one.  If an OOM error does occurs, then the prior value of pList
85655 ** that is input to this routine is automatically freed.
85656 **
85657 ** If pDatabase is not null, it means that the table has an optional
85658 ** database name prefix.  Like this:  "database.table".  The pDatabase
85659 ** points to the table name and the pTable points to the database name.
85660 ** The SrcList.a[].zName field is filled with the table name which might
85661 ** come from pTable (if pDatabase is NULL) or from pDatabase.
85662 ** SrcList.a[].zDatabase is filled with the database name from pTable,
85663 ** or with NULL if no database is specified.
85664 **
85665 ** In other words, if call like this:
85666 **
85667 **         sqlite3SrcListAppend(D,A,B,0);
85668 **
85669 ** Then B is a table name and the database name is unspecified.  If called
85670 ** like this:
85671 **
85672 **         sqlite3SrcListAppend(D,A,B,C);
85673 **
85674 ** Then C is the table name and B is the database name.  If C is defined
85675 ** then so is B.  In other words, we never have a case where:
85676 **
85677 **         sqlite3SrcListAppend(D,A,0,C);
85678 **
85679 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
85680 ** before being added to the SrcList.
85681 */
85682 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
85683   sqlite3 *db,        /* Connection to notify of malloc failures */
85684   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
85685   Token *pTable,      /* Table to append */
85686   Token *pDatabase    /* Database of the table */
85687 ){
85688   struct SrcList_item *pItem;
85689   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
85690   if( pList==0 ){
85691     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
85692     if( pList==0 ) return 0;
85693     pList->nAlloc = 1;
85694   }
85695   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
85696   if( db->mallocFailed ){
85697     sqlite3SrcListDelete(db, pList);
85698     return 0;
85699   }
85700   pItem = &pList->a[pList->nSrc-1];
85701   if( pDatabase && pDatabase->z==0 ){
85702     pDatabase = 0;
85703   }
85704   if( pDatabase ){
85705     Token *pTemp = pDatabase;
85706     pDatabase = pTable;
85707     pTable = pTemp;
85708   }
85709   pItem->zName = sqlite3NameFromToken(db, pTable);
85710   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
85711   return pList;
85712 }
85713
85714 /*
85715 ** Assign VdbeCursor index numbers to all tables in a SrcList
85716 */
85717 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
85718   int i;
85719   struct SrcList_item *pItem;
85720   assert(pList || pParse->db->mallocFailed );
85721   if( pList ){
85722     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
85723       if( pItem->iCursor>=0 ) break;
85724       pItem->iCursor = pParse->nTab++;
85725       if( pItem->pSelect ){
85726         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
85727       }
85728     }
85729   }
85730 }
85731
85732 /*
85733 ** Delete an entire SrcList including all its substructure.
85734 */
85735 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
85736   int i;
85737   struct SrcList_item *pItem;
85738   if( pList==0 ) return;
85739   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
85740     sqlite3DbFree(db, pItem->zDatabase);
85741     sqlite3DbFree(db, pItem->zName);
85742     sqlite3DbFree(db, pItem->zAlias);
85743     sqlite3DbFree(db, pItem->zIndex);
85744     sqlite3DeleteTable(db, pItem->pTab);
85745     sqlite3SelectDelete(db, pItem->pSelect);
85746     sqlite3ExprDelete(db, pItem->pOn);
85747     sqlite3IdListDelete(db, pItem->pUsing);
85748   }
85749   sqlite3DbFree(db, pList);
85750 }
85751
85752 /*
85753 ** This routine is called by the parser to add a new term to the
85754 ** end of a growing FROM clause.  The "p" parameter is the part of
85755 ** the FROM clause that has already been constructed.  "p" is NULL
85756 ** if this is the first term of the FROM clause.  pTable and pDatabase
85757 ** are the name of the table and database named in the FROM clause term.
85758 ** pDatabase is NULL if the database name qualifier is missing - the
85759 ** usual case.  If the term has a alias, then pAlias points to the
85760 ** alias token.  If the term is a subquery, then pSubquery is the
85761 ** SELECT statement that the subquery encodes.  The pTable and
85762 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
85763 ** parameters are the content of the ON and USING clauses.
85764 **
85765 ** Return a new SrcList which encodes is the FROM with the new
85766 ** term added.
85767 */
85768 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
85769   Parse *pParse,          /* Parsing context */
85770   SrcList *p,             /* The left part of the FROM clause already seen */
85771   Token *pTable,          /* Name of the table to add to the FROM clause */
85772   Token *pDatabase,       /* Name of the database containing pTable */
85773   Token *pAlias,          /* The right-hand side of the AS subexpression */
85774   Select *pSubquery,      /* A subquery used in place of a table name */
85775   Expr *pOn,              /* The ON clause of a join */
85776   IdList *pUsing          /* The USING clause of a join */
85777 ){
85778   struct SrcList_item *pItem;
85779   sqlite3 *db = pParse->db;
85780   if( !p && (pOn || pUsing) ){
85781     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
85782       (pOn ? "ON" : "USING")
85783     );
85784     goto append_from_error;
85785   }
85786   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
85787   if( p==0 || NEVER(p->nSrc==0) ){
85788     goto append_from_error;
85789   }
85790   pItem = &p->a[p->nSrc-1];
85791   assert( pAlias!=0 );
85792   if( pAlias->n ){
85793     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
85794   }
85795   pItem->pSelect = pSubquery;
85796   pItem->pOn = pOn;
85797   pItem->pUsing = pUsing;
85798   return p;
85799
85800  append_from_error:
85801   assert( p==0 );
85802   sqlite3ExprDelete(db, pOn);
85803   sqlite3IdListDelete(db, pUsing);
85804   sqlite3SelectDelete(db, pSubquery);
85805   return 0;
85806 }
85807
85808 /*
85809 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
85810 ** element of the source-list passed as the second argument.
85811 */
85812 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
85813   assert( pIndexedBy!=0 );
85814   if( p && ALWAYS(p->nSrc>0) ){
85815     struct SrcList_item *pItem = &p->a[p->nSrc-1];
85816     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
85817     if( pIndexedBy->n==1 && !pIndexedBy->z ){
85818       /* A "NOT INDEXED" clause was supplied. See parse.y
85819       ** construct "indexed_opt" for details. */
85820       pItem->notIndexed = 1;
85821     }else{
85822       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
85823     }
85824   }
85825 }
85826
85827 /*
85828 ** When building up a FROM clause in the parser, the join operator
85829 ** is initially attached to the left operand.  But the code generator
85830 ** expects the join operator to be on the right operand.  This routine
85831 ** Shifts all join operators from left to right for an entire FROM
85832 ** clause.
85833 **
85834 ** Example: Suppose the join is like this:
85835 **
85836 **           A natural cross join B
85837 **
85838 ** The operator is "natural cross join".  The A and B operands are stored
85839 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
85840 ** operator with A.  This routine shifts that operator over to B.
85841 */
85842 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
85843   if( p ){
85844     int i;
85845     assert( p->a || p->nSrc==0 );
85846     for(i=p->nSrc-1; i>0; i--){
85847       p->a[i].jointype = p->a[i-1].jointype;
85848     }
85849     p->a[0].jointype = 0;
85850   }
85851 }
85852
85853 /*
85854 ** Begin a transaction
85855 */
85856 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
85857   sqlite3 *db;
85858   Vdbe *v;
85859   int i;
85860
85861   assert( pParse!=0 );
85862   db = pParse->db;
85863   assert( db!=0 );
85864 /*  if( db->aDb[0].pBt==0 ) return; */
85865   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
85866     return;
85867   }
85868   v = sqlite3GetVdbe(pParse);
85869   if( !v ) return;
85870   if( type!=TK_DEFERRED ){
85871     for(i=0; i<db->nDb; i++){
85872       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
85873       sqlite3VdbeUsesBtree(v, i);
85874     }
85875   }
85876   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
85877 }
85878
85879 /*
85880 ** Commit a transaction
85881 */
85882 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
85883   Vdbe *v;
85884
85885   assert( pParse!=0 );
85886   assert( pParse->db!=0 );
85887   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
85888     return;
85889   }
85890   v = sqlite3GetVdbe(pParse);
85891   if( v ){
85892     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
85893   }
85894 }
85895
85896 /*
85897 ** Rollback a transaction
85898 */
85899 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
85900   Vdbe *v;
85901
85902   assert( pParse!=0 );
85903   assert( pParse->db!=0 );
85904   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
85905     return;
85906   }
85907   v = sqlite3GetVdbe(pParse);
85908   if( v ){
85909     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
85910   }
85911 }
85912
85913 /*
85914 ** This function is called by the parser when it parses a command to create,
85915 ** release or rollback an SQL savepoint.
85916 */
85917 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
85918   char *zName = sqlite3NameFromToken(pParse->db, pName);
85919   if( zName ){
85920     Vdbe *v = sqlite3GetVdbe(pParse);
85921 #ifndef SQLITE_OMIT_AUTHORIZATION
85922     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
85923     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
85924 #endif
85925     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
85926       sqlite3DbFree(pParse->db, zName);
85927       return;
85928     }
85929     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
85930   }
85931 }
85932
85933 /*
85934 ** Make sure the TEMP database is open and available for use.  Return
85935 ** the number of errors.  Leave any error messages in the pParse structure.
85936 */
85937 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
85938   sqlite3 *db = pParse->db;
85939   if( db->aDb[1].pBt==0 && !pParse->explain ){
85940     int rc;
85941     Btree *pBt;
85942     static const int flags =
85943           SQLITE_OPEN_READWRITE |
85944           SQLITE_OPEN_CREATE |
85945           SQLITE_OPEN_EXCLUSIVE |
85946           SQLITE_OPEN_DELETEONCLOSE |
85947           SQLITE_OPEN_TEMP_DB;
85948
85949     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
85950     if( rc!=SQLITE_OK ){
85951       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
85952         "file for storing temporary tables");
85953       pParse->rc = rc;
85954       return 1;
85955     }
85956     db->aDb[1].pBt = pBt;
85957     assert( db->aDb[1].pSchema );
85958     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
85959       db->mallocFailed = 1;
85960       return 1;
85961     }
85962   }
85963   return 0;
85964 }
85965
85966 /*
85967 ** Generate VDBE code that will verify the schema cookie and start
85968 ** a read-transaction for all named database files.
85969 **
85970 ** It is important that all schema cookies be verified and all
85971 ** read transactions be started before anything else happens in
85972 ** the VDBE program.  But this routine can be called after much other
85973 ** code has been generated.  So here is what we do:
85974 **
85975 ** The first time this routine is called, we code an OP_Goto that
85976 ** will jump to a subroutine at the end of the program.  Then we
85977 ** record every database that needs its schema verified in the
85978 ** pParse->cookieMask field.  Later, after all other code has been
85979 ** generated, the subroutine that does the cookie verifications and
85980 ** starts the transactions will be coded and the OP_Goto P2 value
85981 ** will be made to point to that subroutine.  The generation of the
85982 ** cookie verification subroutine code happens in sqlite3FinishCoding().
85983 **
85984 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
85985 ** schema on any databases.  This can be used to position the OP_Goto
85986 ** early in the code, before we know if any database tables will be used.
85987 */
85988 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
85989   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85990
85991 #ifndef SQLITE_OMIT_TRIGGER
85992   if( pToplevel!=pParse ){
85993     /* This branch is taken if a trigger is currently being coded. In this
85994     ** case, set cookieGoto to a non-zero value to show that this function
85995     ** has been called. This is used by the sqlite3ExprCodeConstants()
85996     ** function. */
85997     pParse->cookieGoto = -1;
85998   }
85999 #endif
86000   if( pToplevel->cookieGoto==0 ){
86001     Vdbe *v = sqlite3GetVdbe(pToplevel);
86002     if( v==0 ) return;  /* This only happens if there was a prior error */
86003     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
86004   }
86005   if( iDb>=0 ){
86006     sqlite3 *db = pToplevel->db;
86007     yDbMask mask;
86008
86009     assert( iDb<db->nDb );
86010     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
86011     assert( iDb<SQLITE_MAX_ATTACHED+2 );
86012     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86013     mask = ((yDbMask)1)<<iDb;
86014     if( (pToplevel->cookieMask & mask)==0 ){
86015       pToplevel->cookieMask |= mask;
86016       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
86017       if( !OMIT_TEMPDB && iDb==1 ){
86018         sqlite3OpenTempDatabase(pToplevel);
86019       }
86020     }
86021   }
86022 }
86023
86024 /*
86025 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
86026 ** attached database. Otherwise, invoke it for the database named zDb only.
86027 */
86028 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
86029   sqlite3 *db = pParse->db;
86030   int i;
86031   for(i=0; i<db->nDb; i++){
86032     Db *pDb = &db->aDb[i];
86033     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
86034       sqlite3CodeVerifySchema(pParse, i);
86035     }
86036   }
86037 }
86038
86039 /*
86040 ** Generate VDBE code that prepares for doing an operation that
86041 ** might change the database.
86042 **
86043 ** This routine starts a new transaction if we are not already within
86044 ** a transaction.  If we are already within a transaction, then a checkpoint
86045 ** is set if the setStatement parameter is true.  A checkpoint should
86046 ** be set for operations that might fail (due to a constraint) part of
86047 ** the way through and which will need to undo some writes without having to
86048 ** rollback the whole transaction.  For operations where all constraints
86049 ** can be checked before any changes are made to the database, it is never
86050 ** necessary to undo a write and the checkpoint should not be set.
86051 */
86052 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
86053   Parse *pToplevel = sqlite3ParseToplevel(pParse);
86054   sqlite3CodeVerifySchema(pParse, iDb);
86055   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
86056   pToplevel->isMultiWrite |= setStatement;
86057 }
86058
86059 /*
86060 ** Indicate that the statement currently under construction might write
86061 ** more than one entry (example: deleting one row then inserting another,
86062 ** inserting multiple rows in a table, or inserting a row and index entries.)
86063 ** If an abort occurs after some of these writes have completed, then it will
86064 ** be necessary to undo the completed writes.
86065 */
86066 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
86067   Parse *pToplevel = sqlite3ParseToplevel(pParse);
86068   pToplevel->isMultiWrite = 1;
86069 }
86070
86071 /*
86072 ** The code generator calls this routine if is discovers that it is
86073 ** possible to abort a statement prior to completion.  In order to
86074 ** perform this abort without corrupting the database, we need to make
86075 ** sure that the statement is protected by a statement transaction.
86076 **
86077 ** Technically, we only need to set the mayAbort flag if the
86078 ** isMultiWrite flag was previously set.  There is a time dependency
86079 ** such that the abort must occur after the multiwrite.  This makes
86080 ** some statements involving the REPLACE conflict resolution algorithm
86081 ** go a little faster.  But taking advantage of this time dependency
86082 ** makes it more difficult to prove that the code is correct (in
86083 ** particular, it prevents us from writing an effective
86084 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
86085 ** to take the safe route and skip the optimization.
86086 */
86087 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
86088   Parse *pToplevel = sqlite3ParseToplevel(pParse);
86089   pToplevel->mayAbort = 1;
86090 }
86091
86092 /*
86093 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
86094 ** error. The onError parameter determines which (if any) of the statement
86095 ** and/or current transaction is rolled back.
86096 */
86097 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
86098   Vdbe *v = sqlite3GetVdbe(pParse);
86099   if( onError==OE_Abort ){
86100     sqlite3MayAbort(pParse);
86101   }
86102   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
86103 }
86104
86105 /*
86106 ** Check to see if pIndex uses the collating sequence pColl.  Return
86107 ** true if it does and false if it does not.
86108 */
86109 #ifndef SQLITE_OMIT_REINDEX
86110 static int collationMatch(const char *zColl, Index *pIndex){
86111   int i;
86112   assert( zColl!=0 );
86113   for(i=0; i<pIndex->nColumn; i++){
86114     const char *z = pIndex->azColl[i];
86115     assert( z!=0 );
86116     if( 0==sqlite3StrICmp(z, zColl) ){
86117       return 1;
86118     }
86119   }
86120   return 0;
86121 }
86122 #endif
86123
86124 /*
86125 ** Recompute all indices of pTab that use the collating sequence pColl.
86126 ** If pColl==0 then recompute all indices of pTab.
86127 */
86128 #ifndef SQLITE_OMIT_REINDEX
86129 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
86130   Index *pIndex;              /* An index associated with pTab */
86131
86132   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
86133     if( zColl==0 || collationMatch(zColl, pIndex) ){
86134       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
86135       sqlite3BeginWriteOperation(pParse, 0, iDb);
86136       sqlite3RefillIndex(pParse, pIndex, -1);
86137     }
86138   }
86139 }
86140 #endif
86141
86142 /*
86143 ** Recompute all indices of all tables in all databases where the
86144 ** indices use the collating sequence pColl.  If pColl==0 then recompute
86145 ** all indices everywhere.
86146 */
86147 #ifndef SQLITE_OMIT_REINDEX
86148 static void reindexDatabases(Parse *pParse, char const *zColl){
86149   Db *pDb;                    /* A single database */
86150   int iDb;                    /* The database index number */
86151   sqlite3 *db = pParse->db;   /* The database connection */
86152   HashElem *k;                /* For looping over tables in pDb */
86153   Table *pTab;                /* A table in the database */
86154
86155   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
86156   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
86157     assert( pDb!=0 );
86158     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
86159       pTab = (Table*)sqliteHashData(k);
86160       reindexTable(pParse, pTab, zColl);
86161     }
86162   }
86163 }
86164 #endif
86165
86166 /*
86167 ** Generate code for the REINDEX command.
86168 **
86169 **        REINDEX                            -- 1
86170 **        REINDEX  <collation>               -- 2
86171 **        REINDEX  ?<database>.?<tablename>  -- 3
86172 **        REINDEX  ?<database>.?<indexname>  -- 4
86173 **
86174 ** Form 1 causes all indices in all attached databases to be rebuilt.
86175 ** Form 2 rebuilds all indices in all databases that use the named
86176 ** collating function.  Forms 3 and 4 rebuild the named index or all
86177 ** indices associated with the named table.
86178 */
86179 #ifndef SQLITE_OMIT_REINDEX
86180 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
86181   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
86182   char *z;                    /* Name of a table or index */
86183   const char *zDb;            /* Name of the database */
86184   Table *pTab;                /* A table in the database */
86185   Index *pIndex;              /* An index associated with pTab */
86186   int iDb;                    /* The database index number */
86187   sqlite3 *db = pParse->db;   /* The database connection */
86188   Token *pObjName;            /* Name of the table or index to be reindexed */
86189
86190   /* Read the database schema. If an error occurs, leave an error message
86191   ** and code in pParse and return NULL. */
86192   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
86193     return;
86194   }
86195
86196   if( pName1==0 ){
86197     reindexDatabases(pParse, 0);
86198     return;
86199   }else if( NEVER(pName2==0) || pName2->z==0 ){
86200     char *zColl;
86201     assert( pName1->z );
86202     zColl = sqlite3NameFromToken(pParse->db, pName1);
86203     if( !zColl ) return;
86204     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
86205     if( pColl ){
86206       reindexDatabases(pParse, zColl);
86207       sqlite3DbFree(db, zColl);
86208       return;
86209     }
86210     sqlite3DbFree(db, zColl);
86211   }
86212   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
86213   if( iDb<0 ) return;
86214   z = sqlite3NameFromToken(db, pObjName);
86215   if( z==0 ) return;
86216   zDb = db->aDb[iDb].zName;
86217   pTab = sqlite3FindTable(db, z, zDb);
86218   if( pTab ){
86219     reindexTable(pParse, pTab, 0);
86220     sqlite3DbFree(db, z);
86221     return;
86222   }
86223   pIndex = sqlite3FindIndex(db, z, zDb);
86224   sqlite3DbFree(db, z);
86225   if( pIndex ){
86226     sqlite3BeginWriteOperation(pParse, 0, iDb);
86227     sqlite3RefillIndex(pParse, pIndex, -1);
86228     return;
86229   }
86230   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
86231 }
86232 #endif
86233
86234 /*
86235 ** Return a dynamicly allocated KeyInfo structure that can be used
86236 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
86237 **
86238 ** If successful, a pointer to the new structure is returned. In this case
86239 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
86240 ** pointer. If an error occurs (out of memory or missing collation
86241 ** sequence), NULL is returned and the state of pParse updated to reflect
86242 ** the error.
86243 */
86244 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
86245   int i;
86246   int nCol = pIdx->nColumn;
86247   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
86248   sqlite3 *db = pParse->db;
86249   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
86250
86251   if( pKey ){
86252     pKey->db = pParse->db;
86253     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
86254     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
86255     for(i=0; i<nCol; i++){
86256       char *zColl = pIdx->azColl[i];
86257       assert( zColl );
86258       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
86259       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
86260     }
86261     pKey->nField = (u16)nCol;
86262   }
86263
86264   if( pParse->nErr ){
86265     sqlite3DbFree(db, pKey);
86266     pKey = 0;
86267   }
86268   return pKey;
86269 }
86270
86271 /************** End of build.c ***********************************************/
86272 /************** Begin file callback.c ****************************************/
86273 /*
86274 ** 2005 May 23
86275 **
86276 ** The author disclaims copyright to this source code.  In place of
86277 ** a legal notice, here is a blessing:
86278 **
86279 **    May you do good and not evil.
86280 **    May you find forgiveness for yourself and forgive others.
86281 **    May you share freely, never taking more than you give.
86282 **
86283 *************************************************************************
86284 **
86285 ** This file contains functions used to access the internal hash tables
86286 ** of user defined functions and collation sequences.
86287 */
86288
86289
86290 /*
86291 ** Invoke the 'collation needed' callback to request a collation sequence
86292 ** in the encoding enc of name zName, length nName.
86293 */
86294 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
86295   assert( !db->xCollNeeded || !db->xCollNeeded16 );
86296   if( db->xCollNeeded ){
86297     char *zExternal = sqlite3DbStrDup(db, zName);
86298     if( !zExternal ) return;
86299     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
86300     sqlite3DbFree(db, zExternal);
86301   }
86302 #ifndef SQLITE_OMIT_UTF16
86303   if( db->xCollNeeded16 ){
86304     char const *zExternal;
86305     sqlite3_value *pTmp = sqlite3ValueNew(db);
86306     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
86307     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
86308     if( zExternal ){
86309       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
86310     }
86311     sqlite3ValueFree(pTmp);
86312   }
86313 #endif
86314 }
86315
86316 /*
86317 ** This routine is called if the collation factory fails to deliver a
86318 ** collation function in the best encoding but there may be other versions
86319 ** of this collation function (for other text encodings) available. Use one
86320 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
86321 ** possible.
86322 */
86323 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
86324   CollSeq *pColl2;
86325   char *z = pColl->zName;
86326   int i;
86327   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
86328   for(i=0; i<3; i++){
86329     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
86330     if( pColl2->xCmp!=0 ){
86331       memcpy(pColl, pColl2, sizeof(CollSeq));
86332       pColl->xDel = 0;         /* Do not copy the destructor */
86333       return SQLITE_OK;
86334     }
86335   }
86336   return SQLITE_ERROR;
86337 }
86338
86339 /*
86340 ** This function is responsible for invoking the collation factory callback
86341 ** or substituting a collation sequence of a different encoding when the
86342 ** requested collation sequence is not available in the desired encoding.
86343 **
86344 ** If it is not NULL, then pColl must point to the database native encoding
86345 ** collation sequence with name zName, length nName.
86346 **
86347 ** The return value is either the collation sequence to be used in database
86348 ** db for collation type name zName, length nName, or NULL, if no collation
86349 ** sequence can be found.  If no collation is found, leave an error message.
86350 **
86351 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
86352 */
86353 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
86354   Parse *pParse,        /* Parsing context */
86355   u8 enc,               /* The desired encoding for the collating sequence */
86356   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
86357   const char *zName     /* Collating sequence name */
86358 ){
86359   CollSeq *p;
86360   sqlite3 *db = pParse->db;
86361
86362   p = pColl;
86363   if( !p ){
86364     p = sqlite3FindCollSeq(db, enc, zName, 0);
86365   }
86366   if( !p || !p->xCmp ){
86367     /* No collation sequence of this type for this encoding is registered.
86368     ** Call the collation factory to see if it can supply us with one.
86369     */
86370     callCollNeeded(db, enc, zName);
86371     p = sqlite3FindCollSeq(db, enc, zName, 0);
86372   }
86373   if( p && !p->xCmp && synthCollSeq(db, p) ){
86374     p = 0;
86375   }
86376   assert( !p || p->xCmp );
86377   if( p==0 ){
86378     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
86379   }
86380   return p;
86381 }
86382
86383 /*
86384 ** This routine is called on a collation sequence before it is used to
86385 ** check that it is defined. An undefined collation sequence exists when
86386 ** a database is loaded that contains references to collation sequences
86387 ** that have not been defined by sqlite3_create_collation() etc.
86388 **
86389 ** If required, this routine calls the 'collation needed' callback to
86390 ** request a definition of the collating sequence. If this doesn't work,
86391 ** an equivalent collating sequence that uses a text encoding different
86392 ** from the main database is substituted, if one is available.
86393 */
86394 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
86395   if( pColl ){
86396     const char *zName = pColl->zName;
86397     sqlite3 *db = pParse->db;
86398     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
86399     if( !p ){
86400       return SQLITE_ERROR;
86401     }
86402     assert( p==pColl );
86403   }
86404   return SQLITE_OK;
86405 }
86406
86407
86408
86409 /*
86410 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
86411 ** specified by zName and nName is not found and parameter 'create' is
86412 ** true, then create a new entry. Otherwise return NULL.
86413 **
86414 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
86415 ** array of three CollSeq structures. The first is the collation sequence
86416 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
86417 **
86418 ** Stored immediately after the three collation sequences is a copy of
86419 ** the collation sequence name. A pointer to this string is stored in
86420 ** each collation sequence structure.
86421 */
86422 static CollSeq *findCollSeqEntry(
86423   sqlite3 *db,          /* Database connection */
86424   const char *zName,    /* Name of the collating sequence */
86425   int create            /* Create a new entry if true */
86426 ){
86427   CollSeq *pColl;
86428   int nName = sqlite3Strlen30(zName);
86429   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
86430
86431   if( 0==pColl && create ){
86432     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
86433     if( pColl ){
86434       CollSeq *pDel = 0;
86435       pColl[0].zName = (char*)&pColl[3];
86436       pColl[0].enc = SQLITE_UTF8;
86437       pColl[1].zName = (char*)&pColl[3];
86438       pColl[1].enc = SQLITE_UTF16LE;
86439       pColl[2].zName = (char*)&pColl[3];
86440       pColl[2].enc = SQLITE_UTF16BE;
86441       memcpy(pColl[0].zName, zName, nName);
86442       pColl[0].zName[nName] = 0;
86443       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
86444
86445       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
86446       ** return the pColl pointer to be deleted (because it wasn't added
86447       ** to the hash table).
86448       */
86449       assert( pDel==0 || pDel==pColl );
86450       if( pDel!=0 ){
86451         db->mallocFailed = 1;
86452         sqlite3DbFree(db, pDel);
86453         pColl = 0;
86454       }
86455     }
86456   }
86457   return pColl;
86458 }
86459
86460 /*
86461 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
86462 ** Return the CollSeq* pointer for the collation sequence named zName
86463 ** for the encoding 'enc' from the database 'db'.
86464 **
86465 ** If the entry specified is not found and 'create' is true, then create a
86466 ** new entry.  Otherwise return NULL.
86467 **
86468 ** A separate function sqlite3LocateCollSeq() is a wrapper around
86469 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
86470 ** if necessary and generates an error message if the collating sequence
86471 ** cannot be found.
86472 **
86473 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
86474 */
86475 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
86476   sqlite3 *db,
86477   u8 enc,
86478   const char *zName,
86479   int create
86480 ){
86481   CollSeq *pColl;
86482   if( zName ){
86483     pColl = findCollSeqEntry(db, zName, create);
86484   }else{
86485     pColl = db->pDfltColl;
86486   }
86487   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
86488   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
86489   if( pColl ) pColl += enc-1;
86490   return pColl;
86491 }
86492
86493 /* During the search for the best function definition, this procedure
86494 ** is called to test how well the function passed as the first argument
86495 ** matches the request for a function with nArg arguments in a system
86496 ** that uses encoding enc. The value returned indicates how well the
86497 ** request is matched. A higher value indicates a better match.
86498 **
86499 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
86500 ** is also -1.  In other words, we are searching for a function that
86501 ** takes a variable number of arguments.
86502 **
86503 ** If nArg is -2 that means that we are searching for any function
86504 ** regardless of the number of arguments it uses, so return a positive
86505 ** match score for any
86506 **
86507 ** The returned value is always between 0 and 6, as follows:
86508 **
86509 ** 0: Not a match.
86510 ** 1: UTF8/16 conversion required and function takes any number of arguments.
86511 ** 2: UTF16 byte order change required and function takes any number of args.
86512 ** 3: encoding matches and function takes any number of arguments
86513 ** 4: UTF8/16 conversion required - argument count matches exactly
86514 ** 5: UTF16 byte order conversion required - argument count matches exactly
86515 ** 6: Perfect match:  encoding and argument count match exactly.
86516 **
86517 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
86518 ** a perfect match and any function with both xStep and xFunc NULL is
86519 ** a non-match.
86520 */
86521 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
86522 static int matchQuality(
86523   FuncDef *p,     /* The function we are evaluating for match quality */
86524   int nArg,       /* Desired number of arguments.  (-1)==any */
86525   u8 enc          /* Desired text encoding */
86526 ){
86527   int match;
86528
86529   /* nArg of -2 is a special case */
86530   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
86531
86532   /* Wrong number of arguments means "no match" */
86533   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
86534
86535   /* Give a better score to a function with a specific number of arguments
86536   ** than to function that accepts any number of arguments. */
86537   if( p->nArg==nArg ){
86538     match = 4;
86539   }else{
86540     match = 1;
86541   }
86542
86543   /* Bonus points if the text encoding matches */
86544   if( enc==p->iPrefEnc ){
86545     match += 2;  /* Exact encoding match */
86546   }else if( (enc & p->iPrefEnc & 2)!=0 ){
86547     match += 1;  /* Both are UTF16, but with different byte orders */
86548   }
86549
86550   return match;
86551 }
86552
86553 /*
86554 ** Search a FuncDefHash for a function with the given name.  Return
86555 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
86556 */
86557 static FuncDef *functionSearch(
86558   FuncDefHash *pHash,  /* Hash table to search */
86559   int h,               /* Hash of the name */
86560   const char *zFunc,   /* Name of function */
86561   int nFunc            /* Number of bytes in zFunc */
86562 ){
86563   FuncDef *p;
86564   for(p=pHash->a[h]; p; p=p->pHash){
86565     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
86566       return p;
86567     }
86568   }
86569   return 0;
86570 }
86571
86572 /*
86573 ** Insert a new FuncDef into a FuncDefHash hash table.
86574 */
86575 SQLITE_PRIVATE void sqlite3FuncDefInsert(
86576   FuncDefHash *pHash,  /* The hash table into which to insert */
86577   FuncDef *pDef        /* The function definition to insert */
86578 ){
86579   FuncDef *pOther;
86580   int nName = sqlite3Strlen30(pDef->zName);
86581   u8 c1 = (u8)pDef->zName[0];
86582   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
86583   pOther = functionSearch(pHash, h, pDef->zName, nName);
86584   if( pOther ){
86585     assert( pOther!=pDef && pOther->pNext!=pDef );
86586     pDef->pNext = pOther->pNext;
86587     pOther->pNext = pDef;
86588   }else{
86589     pDef->pNext = 0;
86590     pDef->pHash = pHash->a[h];
86591     pHash->a[h] = pDef;
86592   }
86593 }
86594
86595
86596
86597 /*
86598 ** Locate a user function given a name, a number of arguments and a flag
86599 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
86600 ** pointer to the FuncDef structure that defines that function, or return
86601 ** NULL if the function does not exist.
86602 **
86603 ** If the createFlag argument is true, then a new (blank) FuncDef
86604 ** structure is created and liked into the "db" structure if a
86605 ** no matching function previously existed.
86606 **
86607 ** If nArg is -2, then the first valid function found is returned.  A
86608 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
86609 ** case is used to see if zName is a valid function name for some number
86610 ** of arguments.  If nArg is -2, then createFlag must be 0.
86611 **
86612 ** If createFlag is false, then a function with the required name and
86613 ** number of arguments may be returned even if the eTextRep flag does not
86614 ** match that requested.
86615 */
86616 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
86617   sqlite3 *db,       /* An open database */
86618   const char *zName, /* Name of the function.  Not null-terminated */
86619   int nName,         /* Number of characters in the name */
86620   int nArg,          /* Number of arguments.  -1 means any number */
86621   u8 enc,            /* Preferred text encoding */
86622   u8 createFlag      /* Create new entry if true and does not otherwise exist */
86623 ){
86624   FuncDef *p;         /* Iterator variable */
86625   FuncDef *pBest = 0; /* Best match found so far */
86626   int bestScore = 0;  /* Score of best match */
86627   int h;              /* Hash value */
86628
86629   assert( nArg>=(-2) );
86630   assert( nArg>=(-1) || createFlag==0 );
86631   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
86632   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
86633
86634   /* First search for a match amongst the application-defined functions.
86635   */
86636   p = functionSearch(&db->aFunc, h, zName, nName);
86637   while( p ){
86638     int score = matchQuality(p, nArg, enc);
86639     if( score>bestScore ){
86640       pBest = p;
86641       bestScore = score;
86642     }
86643     p = p->pNext;
86644   }
86645
86646   /* If no match is found, search the built-in functions.
86647   **
86648   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
86649   ** functions even if a prior app-defined function was found.  And give
86650   ** priority to built-in functions.
86651   **
86652   ** Except, if createFlag is true, that means that we are trying to
86653   ** install a new function.  Whatever FuncDef structure is returned it will
86654   ** have fields overwritten with new information appropriate for the
86655   ** new function.  But the FuncDefs for built-in functions are read-only.
86656   ** So we must not search for built-ins when creating a new function.
86657   */
86658   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
86659     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
86660     bestScore = 0;
86661     p = functionSearch(pHash, h, zName, nName);
86662     while( p ){
86663       int score = matchQuality(p, nArg, enc);
86664       if( score>bestScore ){
86665         pBest = p;
86666         bestScore = score;
86667       }
86668       p = p->pNext;
86669     }
86670   }
86671
86672   /* If the createFlag parameter is true and the search did not reveal an
86673   ** exact match for the name, number of arguments and encoding, then add a
86674   ** new entry to the hash table and return it.
86675   */
86676   if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
86677       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
86678     pBest->zName = (char *)&pBest[1];
86679     pBest->nArg = (u16)nArg;
86680     pBest->iPrefEnc = enc;
86681     memcpy(pBest->zName, zName, nName);
86682     pBest->zName[nName] = 0;
86683     sqlite3FuncDefInsert(&db->aFunc, pBest);
86684   }
86685
86686   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
86687     return pBest;
86688   }
86689   return 0;
86690 }
86691
86692 /*
86693 ** Free all resources held by the schema structure. The void* argument points
86694 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
86695 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
86696 ** of the schema hash tables).
86697 **
86698 ** The Schema.cache_size variable is not cleared.
86699 */
86700 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
86701   Hash temp1;
86702   Hash temp2;
86703   HashElem *pElem;
86704   Schema *pSchema = (Schema *)p;
86705
86706   temp1 = pSchema->tblHash;
86707   temp2 = pSchema->trigHash;
86708   sqlite3HashInit(&pSchema->trigHash);
86709   sqlite3HashClear(&pSchema->idxHash);
86710   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
86711     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
86712   }
86713   sqlite3HashClear(&temp2);
86714   sqlite3HashInit(&pSchema->tblHash);
86715   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
86716     Table *pTab = sqliteHashData(pElem);
86717     sqlite3DeleteTable(0, pTab);
86718   }
86719   sqlite3HashClear(&temp1);
86720   sqlite3HashClear(&pSchema->fkeyHash);
86721   pSchema->pSeqTab = 0;
86722   if( pSchema->flags & DB_SchemaLoaded ){
86723     pSchema->iGeneration++;
86724     pSchema->flags &= ~DB_SchemaLoaded;
86725   }
86726 }
86727
86728 /*
86729 ** Find and return the schema associated with a BTree.  Create
86730 ** a new one if necessary.
86731 */
86732 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
86733   Schema * p;
86734   if( pBt ){
86735     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
86736   }else{
86737     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
86738   }
86739   if( !p ){
86740     db->mallocFailed = 1;
86741   }else if ( 0==p->file_format ){
86742     sqlite3HashInit(&p->tblHash);
86743     sqlite3HashInit(&p->idxHash);
86744     sqlite3HashInit(&p->trigHash);
86745     sqlite3HashInit(&p->fkeyHash);
86746     p->enc = SQLITE_UTF8;
86747   }
86748   return p;
86749 }
86750
86751 /************** End of callback.c ********************************************/
86752 /************** Begin file delete.c ******************************************/
86753 /*
86754 ** 2001 September 15
86755 **
86756 ** The author disclaims copyright to this source code.  In place of
86757 ** a legal notice, here is a blessing:
86758 **
86759 **    May you do good and not evil.
86760 **    May you find forgiveness for yourself and forgive others.
86761 **    May you share freely, never taking more than you give.
86762 **
86763 *************************************************************************
86764 ** This file contains C code routines that are called by the parser
86765 ** in order to generate code for DELETE FROM statements.
86766 */
86767
86768 /*
86769 ** While a SrcList can in general represent multiple tables and subqueries
86770 ** (as in the FROM clause of a SELECT statement) in this case it contains
86771 ** the name of a single table, as one might find in an INSERT, DELETE,
86772 ** or UPDATE statement.  Look up that table in the symbol table and
86773 ** return a pointer.  Set an error message and return NULL if the table
86774 ** name is not found or if any other error occurs.
86775 **
86776 ** The following fields are initialized appropriate in pSrc:
86777 **
86778 **    pSrc->a[0].pTab       Pointer to the Table object
86779 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
86780 **
86781 */
86782 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
86783   struct SrcList_item *pItem = pSrc->a;
86784   Table *pTab;
86785   assert( pItem && pSrc->nSrc==1 );
86786   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
86787   sqlite3DeleteTable(pParse->db, pItem->pTab);
86788   pItem->pTab = pTab;
86789   if( pTab ){
86790     pTab->nRef++;
86791   }
86792   if( sqlite3IndexedByLookup(pParse, pItem) ){
86793     pTab = 0;
86794   }
86795   return pTab;
86796 }
86797
86798 /*
86799 ** Check to make sure the given table is writable.  If it is not
86800 ** writable, generate an error message and return 1.  If it is
86801 ** writable return 0;
86802 */
86803 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
86804   /* A table is not writable under the following circumstances:
86805   **
86806   **   1) It is a virtual table and no implementation of the xUpdate method
86807   **      has been provided, or
86808   **   2) It is a system table (i.e. sqlite_master), this call is not
86809   **      part of a nested parse and writable_schema pragma has not
86810   **      been specified.
86811   **
86812   ** In either case leave an error message in pParse and return non-zero.
86813   */
86814   if( ( IsVirtual(pTab)
86815      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
86816    || ( (pTab->tabFlags & TF_Readonly)!=0
86817      && (pParse->db->flags & SQLITE_WriteSchema)==0
86818      && pParse->nested==0 )
86819   ){
86820     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
86821     return 1;
86822   }
86823
86824 #ifndef SQLITE_OMIT_VIEW
86825   if( !viewOk && pTab->pSelect ){
86826     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
86827     return 1;
86828   }
86829 #endif
86830   return 0;
86831 }
86832
86833
86834 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86835 /*
86836 ** Evaluate a view and store its result in an ephemeral table.  The
86837 ** pWhere argument is an optional WHERE clause that restricts the
86838 ** set of rows in the view that are to be added to the ephemeral table.
86839 */
86840 SQLITE_PRIVATE void sqlite3MaterializeView(
86841   Parse *pParse,       /* Parsing context */
86842   Table *pView,        /* View definition */
86843   Expr *pWhere,        /* Optional WHERE clause to be added */
86844   int iCur             /* Cursor number for ephemerial table */
86845 ){
86846   SelectDest dest;
86847   Select *pDup;
86848   sqlite3 *db = pParse->db;
86849
86850   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
86851   if( pWhere ){
86852     SrcList *pFrom;
86853
86854     pWhere = sqlite3ExprDup(db, pWhere, 0);
86855     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
86856     if( pFrom ){
86857       assert( pFrom->nSrc==1 );
86858       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
86859       pFrom->a[0].pSelect = pDup;
86860       assert( pFrom->a[0].pOn==0 );
86861       assert( pFrom->a[0].pUsing==0 );
86862     }else{
86863       sqlite3SelectDelete(db, pDup);
86864     }
86865     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
86866     if( pDup ) pDup->selFlags |= SF_Materialize;
86867   }
86868   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
86869   sqlite3Select(pParse, pDup, &dest);
86870   sqlite3SelectDelete(db, pDup);
86871 }
86872 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
86873
86874 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
86875 /*
86876 ** Generate an expression tree to implement the WHERE, ORDER BY,
86877 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
86878 **
86879 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
86880 **                            \__________________________/
86881 **                               pLimitWhere (pInClause)
86882 */
86883 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
86884   Parse *pParse,               /* The parser context */
86885   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
86886   Expr *pWhere,                /* The WHERE clause.  May be null */
86887   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
86888   Expr *pLimit,                /* The LIMIT clause.  May be null */
86889   Expr *pOffset,               /* The OFFSET clause.  May be null */
86890   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
86891 ){
86892   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
86893   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
86894   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
86895   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
86896   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
86897   Select *pSelect = NULL;      /* Complete SELECT tree */
86898
86899   /* Check that there isn't an ORDER BY without a LIMIT clause.
86900   */
86901   if( pOrderBy && (pLimit == 0) ) {
86902     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
86903     goto limit_where_cleanup_2;
86904   }
86905
86906   /* We only need to generate a select expression if there
86907   ** is a limit/offset term to enforce.
86908   */
86909   if( pLimit == 0 ) {
86910     /* if pLimit is null, pOffset will always be null as well. */
86911     assert( pOffset == 0 );
86912     return pWhere;
86913   }
86914
86915   /* Generate a select expression tree to enforce the limit/offset
86916   ** term for the DELETE or UPDATE statement.  For example:
86917   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86918   ** becomes:
86919   **   DELETE FROM table_a WHERE rowid IN (
86920   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86921   **   );
86922   */
86923
86924   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86925   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
86926   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
86927   if( pEList == 0 ) goto limit_where_cleanup_2;
86928
86929   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
86930   ** and the SELECT subtree. */
86931   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
86932   if( pSelectSrc == 0 ) {
86933     sqlite3ExprListDelete(pParse->db, pEList);
86934     goto limit_where_cleanup_2;
86935   }
86936
86937   /* generate the SELECT expression tree. */
86938   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
86939                              pOrderBy,0,pLimit,pOffset);
86940   if( pSelect == 0 ) return 0;
86941
86942   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
86943   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86944   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
86945   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
86946   if( pInClause == 0 ) goto limit_where_cleanup_1;
86947
86948   pInClause->x.pSelect = pSelect;
86949   pInClause->flags |= EP_xIsSelect;
86950   sqlite3ExprSetHeight(pParse, pInClause);
86951   return pInClause;
86952
86953   /* something went wrong. clean up anything allocated. */
86954 limit_where_cleanup_1:
86955   sqlite3SelectDelete(pParse->db, pSelect);
86956   return 0;
86957
86958 limit_where_cleanup_2:
86959   sqlite3ExprDelete(pParse->db, pWhere);
86960   sqlite3ExprListDelete(pParse->db, pOrderBy);
86961   sqlite3ExprDelete(pParse->db, pLimit);
86962   sqlite3ExprDelete(pParse->db, pOffset);
86963   return 0;
86964 }
86965 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
86966
86967 /*
86968 ** Generate code for a DELETE FROM statement.
86969 **
86970 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
86971 **                 \________/       \________________/
86972 **                  pTabList              pWhere
86973 */
86974 SQLITE_PRIVATE void sqlite3DeleteFrom(
86975   Parse *pParse,         /* The parser context */
86976   SrcList *pTabList,     /* The table from which we should delete things */
86977   Expr *pWhere           /* The WHERE clause.  May be null */
86978 ){
86979   Vdbe *v;               /* The virtual database engine */
86980   Table *pTab;           /* The table from which records will be deleted */
86981   const char *zDb;       /* Name of database holding pTab */
86982   int end, addr = 0;     /* A couple addresses of generated code */
86983   int i;                 /* Loop counter */
86984   WhereInfo *pWInfo;     /* Information about the WHERE clause */
86985   Index *pIdx;           /* For looping over indices of the table */
86986   int iCur;              /* VDBE Cursor number for pTab */
86987   sqlite3 *db;           /* Main database structure */
86988   AuthContext sContext;  /* Authorization context */
86989   NameContext sNC;       /* Name context to resolve expressions in */
86990   int iDb;               /* Database number */
86991   int memCnt = -1;       /* Memory cell used for change counting */
86992   int rcauth;            /* Value returned by authorization callback */
86993
86994 #ifndef SQLITE_OMIT_TRIGGER
86995   int isView;                  /* True if attempting to delete from a view */
86996   Trigger *pTrigger;           /* List of table triggers, if required */
86997 #endif
86998
86999   memset(&sContext, 0, sizeof(sContext));
87000   db = pParse->db;
87001   if( pParse->nErr || db->mallocFailed ){
87002     goto delete_from_cleanup;
87003   }
87004   assert( pTabList->nSrc==1 );
87005
87006   /* Locate the table which we want to delete.  This table has to be
87007   ** put in an SrcList structure because some of the subroutines we
87008   ** will be calling are designed to work with multiple tables and expect
87009   ** an SrcList* parameter instead of just a Table* parameter.
87010   */
87011   pTab = sqlite3SrcListLookup(pParse, pTabList);
87012   if( pTab==0 )  goto delete_from_cleanup;
87013
87014   /* Figure out if we have any triggers and if the table being
87015   ** deleted from is a view
87016   */
87017 #ifndef SQLITE_OMIT_TRIGGER
87018   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
87019   isView = pTab->pSelect!=0;
87020 #else
87021 # define pTrigger 0
87022 # define isView 0
87023 #endif
87024 #ifdef SQLITE_OMIT_VIEW
87025 # undef isView
87026 # define isView 0
87027 #endif
87028
87029   /* If pTab is really a view, make sure it has been initialized.
87030   */
87031   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
87032     goto delete_from_cleanup;
87033   }
87034
87035   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
87036     goto delete_from_cleanup;
87037   }
87038   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87039   assert( iDb<db->nDb );
87040   zDb = db->aDb[iDb].zName;
87041   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
87042   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
87043   if( rcauth==SQLITE_DENY ){
87044     goto delete_from_cleanup;
87045   }
87046   assert(!isView || pTrigger);
87047
87048   /* Assign  cursor number to the table and all its indices.
87049   */
87050   assert( pTabList->nSrc==1 );
87051   iCur = pTabList->a[0].iCursor = pParse->nTab++;
87052   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87053     pParse->nTab++;
87054   }
87055
87056   /* Start the view context
87057   */
87058   if( isView ){
87059     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
87060   }
87061
87062   /* Begin generating code.
87063   */
87064   v = sqlite3GetVdbe(pParse);
87065   if( v==0 ){
87066     goto delete_from_cleanup;
87067   }
87068   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
87069   sqlite3BeginWriteOperation(pParse, 1, iDb);
87070
87071   /* If we are trying to delete from a view, realize that view into
87072   ** a ephemeral table.
87073   */
87074 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
87075   if( isView ){
87076     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
87077   }
87078 #endif
87079
87080   /* Resolve the column names in the WHERE clause.
87081   */
87082   memset(&sNC, 0, sizeof(sNC));
87083   sNC.pParse = pParse;
87084   sNC.pSrcList = pTabList;
87085   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
87086     goto delete_from_cleanup;
87087   }
87088
87089   /* Initialize the counter of the number of rows deleted, if
87090   ** we are counting rows.
87091   */
87092   if( db->flags & SQLITE_CountRows ){
87093     memCnt = ++pParse->nMem;
87094     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
87095   }
87096
87097 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
87098   /* Special case: A DELETE without a WHERE clause deletes everything.
87099   ** It is easier just to erase the whole table. Prior to version 3.6.5,
87100   ** this optimization caused the row change count (the value returned by
87101   ** API function sqlite3_count_changes) to be set incorrectly.  */
87102   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
87103    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
87104   ){
87105     assert( !isView );
87106     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
87107                       pTab->zName, P4_STATIC);
87108     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87109       assert( pIdx->pSchema==pTab->pSchema );
87110       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
87111     }
87112   }else
87113 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
87114   /* The usual case: There is a WHERE clause so we have to scan through
87115   ** the table and pick which records to delete.
87116   */
87117   {
87118     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
87119     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
87120     int regRowid;                   /* Actual register containing rowids */
87121
87122     /* Collect rowids of every row to be deleted.
87123     */
87124     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
87125     pWInfo = sqlite3WhereBegin(
87126         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
87127     );
87128     if( pWInfo==0 ) goto delete_from_cleanup;
87129     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
87130     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
87131     if( db->flags & SQLITE_CountRows ){
87132       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
87133     }
87134     sqlite3WhereEnd(pWInfo);
87135
87136     /* Delete every item whose key was written to the list during the
87137     ** database scan.  We have to delete items after the scan is complete
87138     ** because deleting an item can change the scan order.  */
87139     end = sqlite3VdbeMakeLabel(v);
87140
87141     /* Unless this is a view, open cursors for the table we are
87142     ** deleting from and all its indices. If this is a view, then the
87143     ** only effect this statement has is to fire the INSTEAD OF
87144     ** triggers.  */
87145     if( !isView ){
87146       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
87147     }
87148
87149     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
87150
87151     /* Delete the row */
87152 #ifndef SQLITE_OMIT_VIRTUALTABLE
87153     if( IsVirtual(pTab) ){
87154       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
87155       sqlite3VtabMakeWritable(pParse, pTab);
87156       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
87157       sqlite3VdbeChangeP5(v, OE_Abort);
87158       sqlite3MayAbort(pParse);
87159     }else
87160 #endif
87161     {
87162       int count = (pParse->nested==0);    /* True to count changes */
87163       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
87164     }
87165
87166     /* End of the delete loop */
87167     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
87168     sqlite3VdbeResolveLabel(v, end);
87169
87170     /* Close the cursors open on the table and its indexes. */
87171     if( !isView && !IsVirtual(pTab) ){
87172       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
87173         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
87174       }
87175       sqlite3VdbeAddOp1(v, OP_Close, iCur);
87176     }
87177   }
87178
87179   /* Update the sqlite_sequence table by storing the content of the
87180   ** maximum rowid counter values recorded while inserting into
87181   ** autoincrement tables.
87182   */
87183   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
87184     sqlite3AutoincrementEnd(pParse);
87185   }
87186
87187   /* Return the number of rows that were deleted. If this routine is
87188   ** generating code because of a call to sqlite3NestedParse(), do not
87189   ** invoke the callback function.
87190   */
87191   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
87192     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
87193     sqlite3VdbeSetNumCols(v, 1);
87194     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
87195   }
87196
87197 delete_from_cleanup:
87198   sqlite3AuthContextPop(&sContext);
87199   sqlite3SrcListDelete(db, pTabList);
87200   sqlite3ExprDelete(db, pWhere);
87201   return;
87202 }
87203 /* Make sure "isView" and other macros defined above are undefined. Otherwise
87204 ** thely may interfere with compilation of other functions in this file
87205 ** (or in another file, if this file becomes part of the amalgamation).  */
87206 #ifdef isView
87207  #undef isView
87208 #endif
87209 #ifdef pTrigger
87210  #undef pTrigger
87211 #endif
87212
87213 /*
87214 ** This routine generates VDBE code that causes a single row of a
87215 ** single table to be deleted.
87216 **
87217 ** The VDBE must be in a particular state when this routine is called.
87218 ** These are the requirements:
87219 **
87220 **   1.  A read/write cursor pointing to pTab, the table containing the row
87221 **       to be deleted, must be opened as cursor number $iCur.
87222 **
87223 **   2.  Read/write cursors for all indices of pTab must be open as
87224 **       cursor number base+i for the i-th index.
87225 **
87226 **   3.  The record number of the row to be deleted must be stored in
87227 **       memory cell iRowid.
87228 **
87229 ** This routine generates code to remove both the table record and all
87230 ** index entries that point to that record.
87231 */
87232 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
87233   Parse *pParse,     /* Parsing context */
87234   Table *pTab,       /* Table containing the row to be deleted */
87235   int iCur,          /* Cursor number for the table */
87236   int iRowid,        /* Memory cell that contains the rowid to delete */
87237   int count,         /* If non-zero, increment the row change counter */
87238   Trigger *pTrigger, /* List of triggers to (potentially) fire */
87239   int onconf         /* Default ON CONFLICT policy for triggers */
87240 ){
87241   Vdbe *v = pParse->pVdbe;        /* Vdbe */
87242   int iOld = 0;                   /* First register in OLD.* array */
87243   int iLabel;                     /* Label resolved to end of generated code */
87244
87245   /* Vdbe is guaranteed to have been allocated by this stage. */
87246   assert( v );
87247
87248   /* Seek cursor iCur to the row to delete. If this row no longer exists
87249   ** (this can happen if a trigger program has already deleted it), do
87250   ** not attempt to delete it or fire any DELETE triggers.  */
87251   iLabel = sqlite3VdbeMakeLabel(v);
87252   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87253
87254   /* If there are any triggers to fire, allocate a range of registers to
87255   ** use for the old.* references in the triggers.  */
87256   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
87257     u32 mask;                     /* Mask of OLD.* columns in use */
87258     int iCol;                     /* Iterator used while populating OLD.* */
87259
87260     /* TODO: Could use temporary registers here. Also could attempt to
87261     ** avoid copying the contents of the rowid register.  */
87262     mask = sqlite3TriggerColmask(
87263         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
87264     );
87265     mask |= sqlite3FkOldmask(pParse, pTab);
87266     iOld = pParse->nMem+1;
87267     pParse->nMem += (1 + pTab->nCol);
87268
87269     /* Populate the OLD.* pseudo-table register array. These values will be
87270     ** used by any BEFORE and AFTER triggers that exist.  */
87271     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
87272     for(iCol=0; iCol<pTab->nCol; iCol++){
87273       if( mask==0xffffffff || mask&(1<<iCol) ){
87274         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
87275       }
87276     }
87277
87278     /* Invoke BEFORE DELETE trigger programs. */
87279     sqlite3CodeRowTrigger(pParse, pTrigger,
87280         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
87281     );
87282
87283     /* Seek the cursor to the row to be deleted again. It may be that
87284     ** the BEFORE triggers coded above have already removed the row
87285     ** being deleted. Do not attempt to delete the row a second time, and
87286     ** do not fire AFTER triggers.  */
87287     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87288
87289     /* Do FK processing. This call checks that any FK constraints that
87290     ** refer to this table (i.e. constraints attached to other tables)
87291     ** are not violated by deleting this row.  */
87292     sqlite3FkCheck(pParse, pTab, iOld, 0);
87293   }
87294
87295   /* Delete the index and table entries. Skip this step if pTab is really
87296   ** a view (in which case the only effect of the DELETE statement is to
87297   ** fire the INSTEAD OF triggers).  */
87298   if( pTab->pSelect==0 ){
87299     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
87300     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
87301     if( count ){
87302       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
87303     }
87304   }
87305
87306   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
87307   ** handle rows (possibly in other tables) that refer via a foreign key
87308   ** to the row just deleted. */
87309   sqlite3FkActions(pParse, pTab, 0, iOld);
87310
87311   /* Invoke AFTER DELETE trigger programs. */
87312   sqlite3CodeRowTrigger(pParse, pTrigger,
87313       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
87314   );
87315
87316   /* Jump here if the row had already been deleted before any BEFORE
87317   ** trigger programs were invoked. Or if a trigger program throws a
87318   ** RAISE(IGNORE) exception.  */
87319   sqlite3VdbeResolveLabel(v, iLabel);
87320 }
87321
87322 /*
87323 ** This routine generates VDBE code that causes the deletion of all
87324 ** index entries associated with a single row of a single table.
87325 **
87326 ** The VDBE must be in a particular state when this routine is called.
87327 ** These are the requirements:
87328 **
87329 **   1.  A read/write cursor pointing to pTab, the table containing the row
87330 **       to be deleted, must be opened as cursor number "iCur".
87331 **
87332 **   2.  Read/write cursors for all indices of pTab must be open as
87333 **       cursor number iCur+i for the i-th index.
87334 **
87335 **   3.  The "iCur" cursor must be pointing to the row that is to be
87336 **       deleted.
87337 */
87338 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
87339   Parse *pParse,     /* Parsing and code generating context */
87340   Table *pTab,       /* Table containing the row to be deleted */
87341   int iCur,          /* Cursor number for the table */
87342   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
87343 ){
87344   int i;
87345   Index *pIdx;
87346   int r1;
87347
87348   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
87349     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
87350     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
87351     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
87352   }
87353 }
87354
87355 /*
87356 ** Generate code that will assemble an index key and put it in register
87357 ** regOut.  The key with be for index pIdx which is an index on pTab.
87358 ** iCur is the index of a cursor open on the pTab table and pointing to
87359 ** the entry that needs indexing.
87360 **
87361 ** Return a register number which is the first in a block of
87362 ** registers that holds the elements of the index key.  The
87363 ** block of registers has already been deallocated by the time
87364 ** this routine returns.
87365 */
87366 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
87367   Parse *pParse,     /* Parsing context */
87368   Index *pIdx,       /* The index for which to generate a key */
87369   int iCur,          /* Cursor number for the pIdx->pTable table */
87370   int regOut,        /* Write the new index key to this register */
87371   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
87372 ){
87373   Vdbe *v = pParse->pVdbe;
87374   int j;
87375   Table *pTab = pIdx->pTable;
87376   int regBase;
87377   int nCol;
87378
87379   nCol = pIdx->nColumn;
87380   regBase = sqlite3GetTempRange(pParse, nCol+1);
87381   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
87382   for(j=0; j<nCol; j++){
87383     int idx = pIdx->aiColumn[j];
87384     if( idx==pTab->iPKey ){
87385       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
87386     }else{
87387       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
87388       sqlite3ColumnDefault(v, pTab, idx, -1);
87389     }
87390   }
87391   if( doMakeRec ){
87392     const char *zAff;
87393     if( pTab->pSelect
87394      || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
87395     ){
87396       zAff = 0;
87397     }else{
87398       zAff = sqlite3IndexAffinityStr(v, pIdx);
87399     }
87400     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
87401     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
87402   }
87403   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
87404   return regBase;
87405 }
87406
87407 /************** End of delete.c **********************************************/
87408 /************** Begin file func.c ********************************************/
87409 /*
87410 ** 2002 February 23
87411 **
87412 ** The author disclaims copyright to this source code.  In place of
87413 ** a legal notice, here is a blessing:
87414 **
87415 **    May you do good and not evil.
87416 **    May you find forgiveness for yourself and forgive others.
87417 **    May you share freely, never taking more than you give.
87418 **
87419 *************************************************************************
87420 ** This file contains the C functions that implement various SQL
87421 ** functions of SQLite.
87422 **
87423 ** There is only one exported symbol in this file - the function
87424 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
87425 ** All other code has file scope.
87426 */
87427 /* #include <stdlib.h> */
87428 /* #include <assert.h> */
87429
87430 /*
87431 ** Return the collating function associated with a function.
87432 */
87433 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
87434   return context->pColl;
87435 }
87436
87437 /*
87438 ** Indicate that the accumulator load should be skipped on this
87439 ** iteration of the aggregate loop.
87440 */
87441 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
87442   context->skipFlag = 1;
87443 }
87444
87445 /*
87446 ** Implementation of the non-aggregate min() and max() functions
87447 */
87448 static void minmaxFunc(
87449   sqlite3_context *context,
87450   int argc,
87451   sqlite3_value **argv
87452 ){
87453   int i;
87454   int mask;    /* 0 for min() or 0xffffffff for max() */
87455   int iBest;
87456   CollSeq *pColl;
87457
87458   assert( argc>1 );
87459   mask = sqlite3_user_data(context)==0 ? 0 : -1;
87460   pColl = sqlite3GetFuncCollSeq(context);
87461   assert( pColl );
87462   assert( mask==-1 || mask==0 );
87463   iBest = 0;
87464   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87465   for(i=1; i<argc; i++){
87466     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
87467     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
87468       testcase( mask==0 );
87469       iBest = i;
87470     }
87471   }
87472   sqlite3_result_value(context, argv[iBest]);
87473 }
87474
87475 /*
87476 ** Return the type of the argument.
87477 */
87478 static void typeofFunc(
87479   sqlite3_context *context,
87480   int NotUsed,
87481   sqlite3_value **argv
87482 ){
87483   const char *z = 0;
87484   UNUSED_PARAMETER(NotUsed);
87485   switch( sqlite3_value_type(argv[0]) ){
87486     case SQLITE_INTEGER: z = "integer"; break;
87487     case SQLITE_TEXT:    z = "text";    break;
87488     case SQLITE_FLOAT:   z = "real";    break;
87489     case SQLITE_BLOB:    z = "blob";    break;
87490     default:             z = "null";    break;
87491   }
87492   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
87493 }
87494
87495
87496 /*
87497 ** Implementation of the length() function
87498 */
87499 static void lengthFunc(
87500   sqlite3_context *context,
87501   int argc,
87502   sqlite3_value **argv
87503 ){
87504   int len;
87505
87506   assert( argc==1 );
87507   UNUSED_PARAMETER(argc);
87508   switch( sqlite3_value_type(argv[0]) ){
87509     case SQLITE_BLOB:
87510     case SQLITE_INTEGER:
87511     case SQLITE_FLOAT: {
87512       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
87513       break;
87514     }
87515     case SQLITE_TEXT: {
87516       const unsigned char *z = sqlite3_value_text(argv[0]);
87517       if( z==0 ) return;
87518       len = 0;
87519       while( *z ){
87520         len++;
87521         SQLITE_SKIP_UTF8(z);
87522       }
87523       sqlite3_result_int(context, len);
87524       break;
87525     }
87526     default: {
87527       sqlite3_result_null(context);
87528       break;
87529     }
87530   }
87531 }
87532
87533 /*
87534 ** Implementation of the abs() function.
87535 **
87536 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
87537 ** the numeric argument X.
87538 */
87539 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87540   assert( argc==1 );
87541   UNUSED_PARAMETER(argc);
87542   switch( sqlite3_value_type(argv[0]) ){
87543     case SQLITE_INTEGER: {
87544       i64 iVal = sqlite3_value_int64(argv[0]);
87545       if( iVal<0 ){
87546         if( (iVal<<1)==0 ){
87547           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
87548           ** abs(X) throws an integer overflow error since there is no
87549           ** equivalent positive 64-bit two complement value. */
87550           sqlite3_result_error(context, "integer overflow", -1);
87551           return;
87552         }
87553         iVal = -iVal;
87554       }
87555       sqlite3_result_int64(context, iVal);
87556       break;
87557     }
87558     case SQLITE_NULL: {
87559       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
87560       sqlite3_result_null(context);
87561       break;
87562     }
87563     default: {
87564       /* Because sqlite3_value_double() returns 0.0 if the argument is not
87565       ** something that can be converted into a number, we have:
87566       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
87567       ** cannot be converted to a numeric value.
87568       */
87569       double rVal = sqlite3_value_double(argv[0]);
87570       if( rVal<0 ) rVal = -rVal;
87571       sqlite3_result_double(context, rVal);
87572       break;
87573     }
87574   }
87575 }
87576
87577 /*
87578 ** Implementation of the instr() function.
87579 **
87580 ** instr(haystack,needle) finds the first occurrence of needle
87581 ** in haystack and returns the number of previous characters plus 1,
87582 ** or 0 if needle does not occur within haystack.
87583 **
87584 ** If both haystack and needle are BLOBs, then the result is one more than
87585 ** the number of bytes in haystack prior to the first occurrence of needle,
87586 ** or 0 if needle never occurs in haystack.
87587 */
87588 static void instrFunc(
87589   sqlite3_context *context,
87590   int argc,
87591   sqlite3_value **argv
87592 ){
87593   const unsigned char *zHaystack;
87594   const unsigned char *zNeedle;
87595   int nHaystack;
87596   int nNeedle;
87597   int typeHaystack, typeNeedle;
87598   int N = 1;
87599   int isText;
87600
87601   UNUSED_PARAMETER(argc);
87602   typeHaystack = sqlite3_value_type(argv[0]);
87603   typeNeedle = sqlite3_value_type(argv[1]);
87604   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
87605   nHaystack = sqlite3_value_bytes(argv[0]);
87606   nNeedle = sqlite3_value_bytes(argv[1]);
87607   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
87608     zHaystack = sqlite3_value_blob(argv[0]);
87609     zNeedle = sqlite3_value_blob(argv[1]);
87610     isText = 0;
87611   }else{
87612     zHaystack = sqlite3_value_text(argv[0]);
87613     zNeedle = sqlite3_value_text(argv[1]);
87614     isText = 1;
87615   }
87616   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
87617     N++;
87618     do{
87619       nHaystack--;
87620       zHaystack++;
87621     }while( isText && (zHaystack[0]&0xc0)==0x80 );
87622   }
87623   if( nNeedle>nHaystack ) N = 0;
87624   sqlite3_result_int(context, N);
87625 }
87626
87627 /*
87628 ** Implementation of the substr() function.
87629 **
87630 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
87631 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
87632 ** of x.  If x is text, then we actually count UTF-8 characters.
87633 ** If x is a blob, then we count bytes.
87634 **
87635 ** If p1 is negative, then we begin abs(p1) from the end of x[].
87636 **
87637 ** If p2 is negative, return the p2 characters preceeding p1.
87638 */
87639 static void substrFunc(
87640   sqlite3_context *context,
87641   int argc,
87642   sqlite3_value **argv
87643 ){
87644   const unsigned char *z;
87645   const unsigned char *z2;
87646   int len;
87647   int p0type;
87648   i64 p1, p2;
87649   int negP2 = 0;
87650
87651   assert( argc==3 || argc==2 );
87652   if( sqlite3_value_type(argv[1])==SQLITE_NULL
87653    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
87654   ){
87655     return;
87656   }
87657   p0type = sqlite3_value_type(argv[0]);
87658   p1 = sqlite3_value_int(argv[1]);
87659   if( p0type==SQLITE_BLOB ){
87660     len = sqlite3_value_bytes(argv[0]);
87661     z = sqlite3_value_blob(argv[0]);
87662     if( z==0 ) return;
87663     assert( len==sqlite3_value_bytes(argv[0]) );
87664   }else{
87665     z = sqlite3_value_text(argv[0]);
87666     if( z==0 ) return;
87667     len = 0;
87668     if( p1<0 ){
87669       for(z2=z; *z2; len++){
87670         SQLITE_SKIP_UTF8(z2);
87671       }
87672     }
87673   }
87674   if( argc==3 ){
87675     p2 = sqlite3_value_int(argv[2]);
87676     if( p2<0 ){
87677       p2 = -p2;
87678       negP2 = 1;
87679     }
87680   }else{
87681     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
87682   }
87683   if( p1<0 ){
87684     p1 += len;
87685     if( p1<0 ){
87686       p2 += p1;
87687       if( p2<0 ) p2 = 0;
87688       p1 = 0;
87689     }
87690   }else if( p1>0 ){
87691     p1--;
87692   }else if( p2>0 ){
87693     p2--;
87694   }
87695   if( negP2 ){
87696     p1 -= p2;
87697     if( p1<0 ){
87698       p2 += p1;
87699       p1 = 0;
87700     }
87701   }
87702   assert( p1>=0 && p2>=0 );
87703   if( p0type!=SQLITE_BLOB ){
87704     while( *z && p1 ){
87705       SQLITE_SKIP_UTF8(z);
87706       p1--;
87707     }
87708     for(z2=z; *z2 && p2; p2--){
87709       SQLITE_SKIP_UTF8(z2);
87710     }
87711     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
87712   }else{
87713     if( p1+p2>len ){
87714       p2 = len-p1;
87715       if( p2<0 ) p2 = 0;
87716     }
87717     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
87718   }
87719 }
87720
87721 /*
87722 ** Implementation of the round() function
87723 */
87724 #ifndef SQLITE_OMIT_FLOATING_POINT
87725 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87726   int n = 0;
87727   double r;
87728   char *zBuf;
87729   assert( argc==1 || argc==2 );
87730   if( argc==2 ){
87731     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
87732     n = sqlite3_value_int(argv[1]);
87733     if( n>30 ) n = 30;
87734     if( n<0 ) n = 0;
87735   }
87736   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87737   r = sqlite3_value_double(argv[0]);
87738   /* If Y==0 and X will fit in a 64-bit int,
87739   ** handle the rounding directly,
87740   ** otherwise use printf.
87741   */
87742   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
87743     r = (double)((sqlite_int64)(r+0.5));
87744   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
87745     r = -(double)((sqlite_int64)((-r)+0.5));
87746   }else{
87747     zBuf = sqlite3_mprintf("%.*f",n,r);
87748     if( zBuf==0 ){
87749       sqlite3_result_error_nomem(context);
87750       return;
87751     }
87752     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
87753     sqlite3_free(zBuf);
87754   }
87755   sqlite3_result_double(context, r);
87756 }
87757 #endif
87758
87759 /*
87760 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
87761 ** allocation fails, call sqlite3_result_error_nomem() to notify
87762 ** the database handle that malloc() has failed and return NULL.
87763 ** If nByte is larger than the maximum string or blob length, then
87764 ** raise an SQLITE_TOOBIG exception and return NULL.
87765 */
87766 static void *contextMalloc(sqlite3_context *context, i64 nByte){
87767   char *z;
87768   sqlite3 *db = sqlite3_context_db_handle(context);
87769   assert( nByte>0 );
87770   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
87771   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
87772   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87773     sqlite3_result_error_toobig(context);
87774     z = 0;
87775   }else{
87776     z = sqlite3Malloc((int)nByte);
87777     if( !z ){
87778       sqlite3_result_error_nomem(context);
87779     }
87780   }
87781   return z;
87782 }
87783
87784 /*
87785 ** Implementation of the upper() and lower() SQL functions.
87786 */
87787 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87788   char *z1;
87789   const char *z2;
87790   int i, n;
87791   UNUSED_PARAMETER(argc);
87792   z2 = (char*)sqlite3_value_text(argv[0]);
87793   n = sqlite3_value_bytes(argv[0]);
87794   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87795   assert( z2==(char*)sqlite3_value_text(argv[0]) );
87796   if( z2 ){
87797     z1 = contextMalloc(context, ((i64)n)+1);
87798     if( z1 ){
87799       for(i=0; i<n; i++){
87800         z1[i] = (char)sqlite3Toupper(z2[i]);
87801       }
87802       sqlite3_result_text(context, z1, n, sqlite3_free);
87803     }
87804   }
87805 }
87806 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87807   char *z1;
87808   const char *z2;
87809   int i, n;
87810   UNUSED_PARAMETER(argc);
87811   z2 = (char*)sqlite3_value_text(argv[0]);
87812   n = sqlite3_value_bytes(argv[0]);
87813   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87814   assert( z2==(char*)sqlite3_value_text(argv[0]) );
87815   if( z2 ){
87816     z1 = contextMalloc(context, ((i64)n)+1);
87817     if( z1 ){
87818       for(i=0; i<n; i++){
87819         z1[i] = sqlite3Tolower(z2[i]);
87820       }
87821       sqlite3_result_text(context, z1, n, sqlite3_free);
87822     }
87823   }
87824 }
87825
87826 /*
87827 ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
87828 ** that unused argument values do not have to be computed.  However, we
87829 ** still need some kind of function implementation for this routines in
87830 ** the function table.  That function implementation will never be called
87831 ** so it doesn't matter what the implementation is.  We might as well use
87832 ** the "version()" function as a substitute.
87833 */
87834 #define ifnullFunc versionFunc   /* Substitute function - never called */
87835
87836 /*
87837 ** Implementation of random().  Return a random integer.
87838 */
87839 static void randomFunc(
87840   sqlite3_context *context,
87841   int NotUsed,
87842   sqlite3_value **NotUsed2
87843 ){
87844   sqlite_int64 r;
87845   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87846   sqlite3_randomness(sizeof(r), &r);
87847   if( r<0 ){
87848     /* We need to prevent a random number of 0x8000000000000000
87849     ** (or -9223372036854775808) since when you do abs() of that
87850     ** number of you get the same value back again.  To do this
87851     ** in a way that is testable, mask the sign bit off of negative
87852     ** values, resulting in a positive value.  Then take the
87853     ** 2s complement of that positive value.  The end result can
87854     ** therefore be no less than -9223372036854775807.
87855     */
87856     r = -(r & LARGEST_INT64);
87857   }
87858   sqlite3_result_int64(context, r);
87859 }
87860
87861 /*
87862 ** Implementation of randomblob(N).  Return a random blob
87863 ** that is N bytes long.
87864 */
87865 static void randomBlob(
87866   sqlite3_context *context,
87867   int argc,
87868   sqlite3_value **argv
87869 ){
87870   int n;
87871   unsigned char *p;
87872   assert( argc==1 );
87873   UNUSED_PARAMETER(argc);
87874   n = sqlite3_value_int(argv[0]);
87875   if( n<1 ){
87876     n = 1;
87877   }
87878   p = contextMalloc(context, n);
87879   if( p ){
87880     sqlite3_randomness(n, p);
87881     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
87882   }
87883 }
87884
87885 /*
87886 ** Implementation of the last_insert_rowid() SQL function.  The return
87887 ** value is the same as the sqlite3_last_insert_rowid() API function.
87888 */
87889 static void last_insert_rowid(
87890   sqlite3_context *context,
87891   int NotUsed,
87892   sqlite3_value **NotUsed2
87893 ){
87894   sqlite3 *db = sqlite3_context_db_handle(context);
87895   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87896   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
87897   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
87898   ** function. */
87899   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
87900 }
87901
87902 /*
87903 ** Implementation of the changes() SQL function.
87904 **
87905 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
87906 ** around the sqlite3_changes() C/C++ function and hence follows the same
87907 ** rules for counting changes.
87908 */
87909 static void changes(
87910   sqlite3_context *context,
87911   int NotUsed,
87912   sqlite3_value **NotUsed2
87913 ){
87914   sqlite3 *db = sqlite3_context_db_handle(context);
87915   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87916   sqlite3_result_int(context, sqlite3_changes(db));
87917 }
87918
87919 /*
87920 ** Implementation of the total_changes() SQL function.  The return value is
87921 ** the same as the sqlite3_total_changes() API function.
87922 */
87923 static void total_changes(
87924   sqlite3_context *context,
87925   int NotUsed,
87926   sqlite3_value **NotUsed2
87927 ){
87928   sqlite3 *db = sqlite3_context_db_handle(context);
87929   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87930   /* IMP: R-52756-41993 This function is a wrapper around the
87931   ** sqlite3_total_changes() C/C++ interface. */
87932   sqlite3_result_int(context, sqlite3_total_changes(db));
87933 }
87934
87935 /*
87936 ** A structure defining how to do GLOB-style comparisons.
87937 */
87938 struct compareInfo {
87939   u8 matchAll;
87940   u8 matchOne;
87941   u8 matchSet;
87942   u8 noCase;
87943 };
87944
87945 /*
87946 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
87947 ** character is exactly one byte in size.  Also, all characters are
87948 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
87949 ** whereas only characters less than 0x80 do in ASCII.
87950 */
87951 #if defined(SQLITE_EBCDIC)
87952 # define sqlite3Utf8Read(A)    (*((*A)++))
87953 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
87954 #else
87955 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
87956 #endif
87957
87958 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
87959 /* The correct SQL-92 behavior is for the LIKE operator to ignore
87960 ** case.  Thus  'a' LIKE 'A' would be true. */
87961 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
87962 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
87963 ** is case sensitive causing 'a' LIKE 'A' to be false */
87964 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
87965
87966 /*
87967 ** Compare two UTF-8 strings for equality where the first string can
87968 ** potentially be a "glob" expression.  Return true (1) if they
87969 ** are the same and false (0) if they are different.
87970 **
87971 ** Globbing rules:
87972 **
87973 **      '*'       Matches any sequence of zero or more characters.
87974 **
87975 **      '?'       Matches exactly one character.
87976 **
87977 **     [...]      Matches one character from the enclosed list of
87978 **                characters.
87979 **
87980 **     [^...]     Matches one character not in the enclosed list.
87981 **
87982 ** With the [...] and [^...] matching, a ']' character can be included
87983 ** in the list by making it the first character after '[' or '^'.  A
87984 ** range of characters can be specified using '-'.  Example:
87985 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
87986 ** it the last character in the list.
87987 **
87988 ** This routine is usually quick, but can be N**2 in the worst case.
87989 **
87990 ** Hints: to match '*' or '?', put them in "[]".  Like this:
87991 **
87992 **         abc[*]xyz        Matches "abc*xyz" only
87993 */
87994 static int patternCompare(
87995   const u8 *zPattern,              /* The glob pattern */
87996   const u8 *zString,               /* The string to compare against the glob */
87997   const struct compareInfo *pInfo, /* Information about how to do the compare */
87998   u32 esc                          /* The escape character */
87999 ){
88000   u32 c, c2;
88001   int invert;
88002   int seen;
88003   u8 matchOne = pInfo->matchOne;
88004   u8 matchAll = pInfo->matchAll;
88005   u8 matchSet = pInfo->matchSet;
88006   u8 noCase = pInfo->noCase;
88007   int prevEscape = 0;     /* True if the previous character was 'escape' */
88008
88009   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
88010     if( c==matchAll && !prevEscape ){
88011       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
88012                || c == matchOne ){
88013         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
88014           return 0;
88015         }
88016       }
88017       if( c==0 ){
88018         return 1;
88019       }else if( c==esc ){
88020         c = sqlite3Utf8Read(&zPattern);
88021         if( c==0 ){
88022           return 0;
88023         }
88024       }else if( c==matchSet ){
88025         assert( esc==0 );         /* This is GLOB, not LIKE */
88026         assert( matchSet<0x80 );  /* '[' is a single-byte character */
88027         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
88028           SQLITE_SKIP_UTF8(zString);
88029         }
88030         return *zString!=0;
88031       }
88032       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
88033         if( noCase ){
88034           GlogUpperToLower(c2);
88035           GlogUpperToLower(c);
88036           while( c2 != 0 && c2 != c ){
88037             c2 = sqlite3Utf8Read(&zString);
88038             GlogUpperToLower(c2);
88039           }
88040         }else{
88041           while( c2 != 0 && c2 != c ){
88042             c2 = sqlite3Utf8Read(&zString);
88043           }
88044         }
88045         if( c2==0 ) return 0;
88046         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
88047       }
88048       return 0;
88049     }else if( c==matchOne && !prevEscape ){
88050       if( sqlite3Utf8Read(&zString)==0 ){
88051         return 0;
88052       }
88053     }else if( c==matchSet ){
88054       u32 prior_c = 0;
88055       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
88056       seen = 0;
88057       invert = 0;
88058       c = sqlite3Utf8Read(&zString);
88059       if( c==0 ) return 0;
88060       c2 = sqlite3Utf8Read(&zPattern);
88061       if( c2=='^' ){
88062         invert = 1;
88063         c2 = sqlite3Utf8Read(&zPattern);
88064       }
88065       if( c2==']' ){
88066         if( c==']' ) seen = 1;
88067         c2 = sqlite3Utf8Read(&zPattern);
88068       }
88069       while( c2 && c2!=']' ){
88070         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
88071           c2 = sqlite3Utf8Read(&zPattern);
88072           if( c>=prior_c && c<=c2 ) seen = 1;
88073           prior_c = 0;
88074         }else{
88075           if( c==c2 ){
88076             seen = 1;
88077           }
88078           prior_c = c2;
88079         }
88080         c2 = sqlite3Utf8Read(&zPattern);
88081       }
88082       if( c2==0 || (seen ^ invert)==0 ){
88083         return 0;
88084       }
88085     }else if( esc==c && !prevEscape ){
88086       prevEscape = 1;
88087     }else{
88088       c2 = sqlite3Utf8Read(&zString);
88089       if( noCase ){
88090         GlogUpperToLower(c);
88091         GlogUpperToLower(c2);
88092       }
88093       if( c!=c2 ){
88094         return 0;
88095       }
88096       prevEscape = 0;
88097     }
88098   }
88099   return *zString==0;
88100 }
88101
88102 /*
88103 ** Count the number of times that the LIKE operator (or GLOB which is
88104 ** just a variation of LIKE) gets called.  This is used for testing
88105 ** only.
88106 */
88107 #ifdef SQLITE_TEST
88108 SQLITE_API int sqlite3_like_count = 0;
88109 #endif
88110
88111
88112 /*
88113 ** Implementation of the like() SQL function.  This function implements
88114 ** the build-in LIKE operator.  The first argument to the function is the
88115 ** pattern and the second argument is the string.  So, the SQL statements:
88116 **
88117 **       A LIKE B
88118 **
88119 ** is implemented as like(B,A).
88120 **
88121 ** This same function (with a different compareInfo structure) computes
88122 ** the GLOB operator.
88123 */
88124 static void likeFunc(
88125   sqlite3_context *context,
88126   int argc,
88127   sqlite3_value **argv
88128 ){
88129   const unsigned char *zA, *zB;
88130   u32 escape = 0;
88131   int nPat;
88132   sqlite3 *db = sqlite3_context_db_handle(context);
88133
88134   zB = sqlite3_value_text(argv[0]);
88135   zA = sqlite3_value_text(argv[1]);
88136
88137   /* Limit the length of the LIKE or GLOB pattern to avoid problems
88138   ** of deep recursion and N*N behavior in patternCompare().
88139   */
88140   nPat = sqlite3_value_bytes(argv[0]);
88141   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
88142   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
88143   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
88144     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
88145     return;
88146   }
88147   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
88148
88149   if( argc==3 ){
88150     /* The escape character string must consist of a single UTF-8 character.
88151     ** Otherwise, return an error.
88152     */
88153     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
88154     if( zEsc==0 ) return;
88155     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
88156       sqlite3_result_error(context,
88157           "ESCAPE expression must be a single character", -1);
88158       return;
88159     }
88160     escape = sqlite3Utf8Read(&zEsc);
88161   }
88162   if( zA && zB ){
88163     struct compareInfo *pInfo = sqlite3_user_data(context);
88164 #ifdef SQLITE_TEST
88165     sqlite3_like_count++;
88166 #endif
88167
88168     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
88169   }
88170 }
88171
88172 /*
88173 ** Implementation of the NULLIF(x,y) function.  The result is the first
88174 ** argument if the arguments are different.  The result is NULL if the
88175 ** arguments are equal to each other.
88176 */
88177 static void nullifFunc(
88178   sqlite3_context *context,
88179   int NotUsed,
88180   sqlite3_value **argv
88181 ){
88182   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
88183   UNUSED_PARAMETER(NotUsed);
88184   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
88185     sqlite3_result_value(context, argv[0]);
88186   }
88187 }
88188
88189 /*
88190 ** Implementation of the sqlite_version() function.  The result is the version
88191 ** of the SQLite library that is running.
88192 */
88193 static void versionFunc(
88194   sqlite3_context *context,
88195   int NotUsed,
88196   sqlite3_value **NotUsed2
88197 ){
88198   UNUSED_PARAMETER2(NotUsed, NotUsed2);
88199   /* IMP: R-48699-48617 This function is an SQL wrapper around the
88200   ** sqlite3_libversion() C-interface. */
88201   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
88202 }
88203
88204 /*
88205 ** Implementation of the sqlite_source_id() function. The result is a string
88206 ** that identifies the particular version of the source code used to build
88207 ** SQLite.
88208 */
88209 static void sourceidFunc(
88210   sqlite3_context *context,
88211   int NotUsed,
88212   sqlite3_value **NotUsed2
88213 ){
88214   UNUSED_PARAMETER2(NotUsed, NotUsed2);
88215   /* IMP: R-24470-31136 This function is an SQL wrapper around the
88216   ** sqlite3_sourceid() C interface. */
88217   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
88218 }
88219
88220 /*
88221 ** Implementation of the sqlite_log() function.  This is a wrapper around
88222 ** sqlite3_log().  The return value is NULL.  The function exists purely for
88223 ** its side-effects.
88224 */
88225 static void errlogFunc(
88226   sqlite3_context *context,
88227   int argc,
88228   sqlite3_value **argv
88229 ){
88230   UNUSED_PARAMETER(argc);
88231   UNUSED_PARAMETER(context);
88232   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
88233 }
88234
88235 /*
88236 ** Implementation of the sqlite_compileoption_used() function.
88237 ** The result is an integer that identifies if the compiler option
88238 ** was used to build SQLite.
88239 */
88240 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88241 static void compileoptionusedFunc(
88242   sqlite3_context *context,
88243   int argc,
88244   sqlite3_value **argv
88245 ){
88246   const char *zOptName;
88247   assert( argc==1 );
88248   UNUSED_PARAMETER(argc);
88249   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
88250   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
88251   ** function.
88252   */
88253   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
88254     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
88255   }
88256 }
88257 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88258
88259 /*
88260 ** Implementation of the sqlite_compileoption_get() function.
88261 ** The result is a string that identifies the compiler options
88262 ** used to build SQLite.
88263 */
88264 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88265 static void compileoptiongetFunc(
88266   sqlite3_context *context,
88267   int argc,
88268   sqlite3_value **argv
88269 ){
88270   int n;
88271   assert( argc==1 );
88272   UNUSED_PARAMETER(argc);
88273   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
88274   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
88275   */
88276   n = sqlite3_value_int(argv[0]);
88277   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
88278 }
88279 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88280
88281 /* Array for converting from half-bytes (nybbles) into ASCII hex
88282 ** digits. */
88283 static const char hexdigits[] = {
88284   '0', '1', '2', '3', '4', '5', '6', '7',
88285   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
88286 };
88287
88288 /*
88289 ** EXPERIMENTAL - This is not an official function.  The interface may
88290 ** change.  This function may disappear.  Do not write code that depends
88291 ** on this function.
88292 **
88293 ** Implementation of the QUOTE() function.  This function takes a single
88294 ** argument.  If the argument is numeric, the return value is the same as
88295 ** the argument.  If the argument is NULL, the return value is the string
88296 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
88297 ** single-quote escapes.
88298 */
88299 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
88300   assert( argc==1 );
88301   UNUSED_PARAMETER(argc);
88302   switch( sqlite3_value_type(argv[0]) ){
88303     case SQLITE_FLOAT: {
88304       double r1, r2;
88305       char zBuf[50];
88306       r1 = sqlite3_value_double(argv[0]);
88307       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
88308       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
88309       if( r1!=r2 ){
88310         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
88311       }
88312       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
88313       break;
88314     }
88315     case SQLITE_INTEGER: {
88316       sqlite3_result_value(context, argv[0]);
88317       break;
88318     }
88319     case SQLITE_BLOB: {
88320       char *zText = 0;
88321       char const *zBlob = sqlite3_value_blob(argv[0]);
88322       int nBlob = sqlite3_value_bytes(argv[0]);
88323       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
88324       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
88325       if( zText ){
88326         int i;
88327         for(i=0; i<nBlob; i++){
88328           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
88329           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
88330         }
88331         zText[(nBlob*2)+2] = '\'';
88332         zText[(nBlob*2)+3] = '\0';
88333         zText[0] = 'X';
88334         zText[1] = '\'';
88335         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
88336         sqlite3_free(zText);
88337       }
88338       break;
88339     }
88340     case SQLITE_TEXT: {
88341       int i,j;
88342       u64 n;
88343       const unsigned char *zArg = sqlite3_value_text(argv[0]);
88344       char *z;
88345
88346       if( zArg==0 ) return;
88347       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
88348       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
88349       if( z ){
88350         z[0] = '\'';
88351         for(i=0, j=1; zArg[i]; i++){
88352           z[j++] = zArg[i];
88353           if( zArg[i]=='\'' ){
88354             z[j++] = '\'';
88355           }
88356         }
88357         z[j++] = '\'';
88358         z[j] = 0;
88359         sqlite3_result_text(context, z, j, sqlite3_free);
88360       }
88361       break;
88362     }
88363     default: {
88364       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
88365       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
88366       break;
88367     }
88368   }
88369 }
88370
88371 /*
88372 ** The hex() function.  Interpret the argument as a blob.  Return
88373 ** a hexadecimal rendering as text.
88374 */
88375 static void hexFunc(
88376   sqlite3_context *context,
88377   int argc,
88378   sqlite3_value **argv
88379 ){
88380   int i, n;
88381   const unsigned char *pBlob;
88382   char *zHex, *z;
88383   assert( argc==1 );
88384   UNUSED_PARAMETER(argc);
88385   pBlob = sqlite3_value_blob(argv[0]);
88386   n = sqlite3_value_bytes(argv[0]);
88387   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
88388   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
88389   if( zHex ){
88390     for(i=0; i<n; i++, pBlob++){
88391       unsigned char c = *pBlob;
88392       *(z++) = hexdigits[(c>>4)&0xf];
88393       *(z++) = hexdigits[c&0xf];
88394     }
88395     *z = 0;
88396     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
88397   }
88398 }
88399
88400 /*
88401 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
88402 */
88403 static void zeroblobFunc(
88404   sqlite3_context *context,
88405   int argc,
88406   sqlite3_value **argv
88407 ){
88408   i64 n;
88409   sqlite3 *db = sqlite3_context_db_handle(context);
88410   assert( argc==1 );
88411   UNUSED_PARAMETER(argc);
88412   n = sqlite3_value_int64(argv[0]);
88413   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
88414   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
88415   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88416     sqlite3_result_error_toobig(context);
88417   }else{
88418     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
88419   }
88420 }
88421
88422 /*
88423 ** The replace() function.  Three arguments are all strings: call
88424 ** them A, B, and C. The result is also a string which is derived
88425 ** from A by replacing every occurance of B with C.  The match
88426 ** must be exact.  Collating sequences are not used.
88427 */
88428 static void replaceFunc(
88429   sqlite3_context *context,
88430   int argc,
88431   sqlite3_value **argv
88432 ){
88433   const unsigned char *zStr;        /* The input string A */
88434   const unsigned char *zPattern;    /* The pattern string B */
88435   const unsigned char *zRep;        /* The replacement string C */
88436   unsigned char *zOut;              /* The output */
88437   int nStr;                /* Size of zStr */
88438   int nPattern;            /* Size of zPattern */
88439   int nRep;                /* Size of zRep */
88440   i64 nOut;                /* Maximum size of zOut */
88441   int loopLimit;           /* Last zStr[] that might match zPattern[] */
88442   int i, j;                /* Loop counters */
88443
88444   assert( argc==3 );
88445   UNUSED_PARAMETER(argc);
88446   zStr = sqlite3_value_text(argv[0]);
88447   if( zStr==0 ) return;
88448   nStr = sqlite3_value_bytes(argv[0]);
88449   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
88450   zPattern = sqlite3_value_text(argv[1]);
88451   if( zPattern==0 ){
88452     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
88453             || sqlite3_context_db_handle(context)->mallocFailed );
88454     return;
88455   }
88456   if( zPattern[0]==0 ){
88457     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
88458     sqlite3_result_value(context, argv[0]);
88459     return;
88460   }
88461   nPattern = sqlite3_value_bytes(argv[1]);
88462   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
88463   zRep = sqlite3_value_text(argv[2]);
88464   if( zRep==0 ) return;
88465   nRep = sqlite3_value_bytes(argv[2]);
88466   assert( zRep==sqlite3_value_text(argv[2]) );
88467   nOut = nStr + 1;
88468   assert( nOut<SQLITE_MAX_LENGTH );
88469   zOut = contextMalloc(context, (i64)nOut);
88470   if( zOut==0 ){
88471     return;
88472   }
88473   loopLimit = nStr - nPattern;
88474   for(i=j=0; i<=loopLimit; i++){
88475     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
88476       zOut[j++] = zStr[i];
88477     }else{
88478       u8 *zOld;
88479       sqlite3 *db = sqlite3_context_db_handle(context);
88480       nOut += nRep - nPattern;
88481       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
88482       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
88483       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88484         sqlite3_result_error_toobig(context);
88485         sqlite3_free(zOut);
88486         return;
88487       }
88488       zOld = zOut;
88489       zOut = sqlite3_realloc(zOut, (int)nOut);
88490       if( zOut==0 ){
88491         sqlite3_result_error_nomem(context);
88492         sqlite3_free(zOld);
88493         return;
88494       }
88495       memcpy(&zOut[j], zRep, nRep);
88496       j += nRep;
88497       i += nPattern-1;
88498     }
88499   }
88500   assert( j+nStr-i+1==nOut );
88501   memcpy(&zOut[j], &zStr[i], nStr-i);
88502   j += nStr - i;
88503   assert( j<=nOut );
88504   zOut[j] = 0;
88505   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
88506 }
88507
88508 /*
88509 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
88510 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
88511 */
88512 static void trimFunc(
88513   sqlite3_context *context,
88514   int argc,
88515   sqlite3_value **argv
88516 ){
88517   const unsigned char *zIn;         /* Input string */
88518   const unsigned char *zCharSet;    /* Set of characters to trim */
88519   int nIn;                          /* Number of bytes in input */
88520   int flags;                        /* 1: trimleft  2: trimright  3: trim */
88521   int i;                            /* Loop counter */
88522   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
88523   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
88524   int nChar;                        /* Number of characters in zCharSet */
88525
88526   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88527     return;
88528   }
88529   zIn = sqlite3_value_text(argv[0]);
88530   if( zIn==0 ) return;
88531   nIn = sqlite3_value_bytes(argv[0]);
88532   assert( zIn==sqlite3_value_text(argv[0]) );
88533   if( argc==1 ){
88534     static const unsigned char lenOne[] = { 1 };
88535     static unsigned char * const azOne[] = { (u8*)" " };
88536     nChar = 1;
88537     aLen = (u8*)lenOne;
88538     azChar = (unsigned char **)azOne;
88539     zCharSet = 0;
88540   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
88541     return;
88542   }else{
88543     const unsigned char *z;
88544     for(z=zCharSet, nChar=0; *z; nChar++){
88545       SQLITE_SKIP_UTF8(z);
88546     }
88547     if( nChar>0 ){
88548       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
88549       if( azChar==0 ){
88550         return;
88551       }
88552       aLen = (unsigned char*)&azChar[nChar];
88553       for(z=zCharSet, nChar=0; *z; nChar++){
88554         azChar[nChar] = (unsigned char *)z;
88555         SQLITE_SKIP_UTF8(z);
88556         aLen[nChar] = (u8)(z - azChar[nChar]);
88557       }
88558     }
88559   }
88560   if( nChar>0 ){
88561     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
88562     if( flags & 1 ){
88563       while( nIn>0 ){
88564         int len = 0;
88565         for(i=0; i<nChar; i++){
88566           len = aLen[i];
88567           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
88568         }
88569         if( i>=nChar ) break;
88570         zIn += len;
88571         nIn -= len;
88572       }
88573     }
88574     if( flags & 2 ){
88575       while( nIn>0 ){
88576         int len = 0;
88577         for(i=0; i<nChar; i++){
88578           len = aLen[i];
88579           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
88580         }
88581         if( i>=nChar ) break;
88582         nIn -= len;
88583       }
88584     }
88585     if( zCharSet ){
88586       sqlite3_free(azChar);
88587     }
88588   }
88589   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
88590 }
88591
88592
88593 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
88594 ** is only available if the SQLITE_SOUNDEX compile-time option is used
88595 ** when SQLite is built.
88596 */
88597 #ifdef SQLITE_SOUNDEX
88598 /*
88599 ** Compute the soundex encoding of a word.
88600 **
88601 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
88602 ** soundex encoding of the string X.
88603 */
88604 static void soundexFunc(
88605   sqlite3_context *context,
88606   int argc,
88607   sqlite3_value **argv
88608 ){
88609   char zResult[8];
88610   const u8 *zIn;
88611   int i, j;
88612   static const unsigned char iCode[] = {
88613     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88614     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88615     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88616     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88617     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88618     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88619     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88620     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88621   };
88622   assert( argc==1 );
88623   zIn = (u8*)sqlite3_value_text(argv[0]);
88624   if( zIn==0 ) zIn = (u8*)"";
88625   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
88626   if( zIn[i] ){
88627     u8 prevcode = iCode[zIn[i]&0x7f];
88628     zResult[0] = sqlite3Toupper(zIn[i]);
88629     for(j=1; j<4 && zIn[i]; i++){
88630       int code = iCode[zIn[i]&0x7f];
88631       if( code>0 ){
88632         if( code!=prevcode ){
88633           prevcode = code;
88634           zResult[j++] = code + '0';
88635         }
88636       }else{
88637         prevcode = 0;
88638       }
88639     }
88640     while( j<4 ){
88641       zResult[j++] = '0';
88642     }
88643     zResult[j] = 0;
88644     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
88645   }else{
88646     /* IMP: R-64894-50321 The string "?000" is returned if the argument
88647     ** is NULL or contains no ASCII alphabetic characters. */
88648     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
88649   }
88650 }
88651 #endif /* SQLITE_SOUNDEX */
88652
88653 #ifndef SQLITE_OMIT_LOAD_EXTENSION
88654 /*
88655 ** A function that loads a shared-library extension then returns NULL.
88656 */
88657 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
88658   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
88659   const char *zProc;
88660   sqlite3 *db = sqlite3_context_db_handle(context);
88661   char *zErrMsg = 0;
88662
88663   if( argc==2 ){
88664     zProc = (const char *)sqlite3_value_text(argv[1]);
88665   }else{
88666     zProc = 0;
88667   }
88668   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
88669     sqlite3_result_error(context, zErrMsg, -1);
88670     sqlite3_free(zErrMsg);
88671   }
88672 }
88673 #endif
88674
88675
88676 /*
88677 ** An instance of the following structure holds the context of a
88678 ** sum() or avg() aggregate computation.
88679 */
88680 typedef struct SumCtx SumCtx;
88681 struct SumCtx {
88682   double rSum;      /* Floating point sum */
88683   i64 iSum;         /* Integer sum */
88684   i64 cnt;          /* Number of elements summed */
88685   u8 overflow;      /* True if integer overflow seen */
88686   u8 approx;        /* True if non-integer value was input to the sum */
88687 };
88688
88689 /*
88690 ** Routines used to compute the sum, average, and total.
88691 **
88692 ** The SUM() function follows the (broken) SQL standard which means
88693 ** that it returns NULL if it sums over no inputs.  TOTAL returns
88694 ** 0.0 in that case.  In addition, TOTAL always returns a float where
88695 ** SUM might return an integer if it never encounters a floating point
88696 ** value.  TOTAL never fails, but SUM might through an exception if
88697 ** it overflows an integer.
88698 */
88699 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88700   SumCtx *p;
88701   int type;
88702   assert( argc==1 );
88703   UNUSED_PARAMETER(argc);
88704   p = sqlite3_aggregate_context(context, sizeof(*p));
88705   type = sqlite3_value_numeric_type(argv[0]);
88706   if( p && type!=SQLITE_NULL ){
88707     p->cnt++;
88708     if( type==SQLITE_INTEGER ){
88709       i64 v = sqlite3_value_int64(argv[0]);
88710       p->rSum += v;
88711       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
88712         p->overflow = 1;
88713       }
88714     }else{
88715       p->rSum += sqlite3_value_double(argv[0]);
88716       p->approx = 1;
88717     }
88718   }
88719 }
88720 static void sumFinalize(sqlite3_context *context){
88721   SumCtx *p;
88722   p = sqlite3_aggregate_context(context, 0);
88723   if( p && p->cnt>0 ){
88724     if( p->overflow ){
88725       sqlite3_result_error(context,"integer overflow",-1);
88726     }else if( p->approx ){
88727       sqlite3_result_double(context, p->rSum);
88728     }else{
88729       sqlite3_result_int64(context, p->iSum);
88730     }
88731   }
88732 }
88733 static void avgFinalize(sqlite3_context *context){
88734   SumCtx *p;
88735   p = sqlite3_aggregate_context(context, 0);
88736   if( p && p->cnt>0 ){
88737     sqlite3_result_double(context, p->rSum/(double)p->cnt);
88738   }
88739 }
88740 static void totalFinalize(sqlite3_context *context){
88741   SumCtx *p;
88742   p = sqlite3_aggregate_context(context, 0);
88743   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88744   sqlite3_result_double(context, p ? p->rSum : (double)0);
88745 }
88746
88747 /*
88748 ** The following structure keeps track of state information for the
88749 ** count() aggregate function.
88750 */
88751 typedef struct CountCtx CountCtx;
88752 struct CountCtx {
88753   i64 n;
88754 };
88755
88756 /*
88757 ** Routines to implement the count() aggregate function.
88758 */
88759 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88760   CountCtx *p;
88761   p = sqlite3_aggregate_context(context, sizeof(*p));
88762   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
88763     p->n++;
88764   }
88765
88766 #ifndef SQLITE_OMIT_DEPRECATED
88767   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
88768   ** sure it still operates correctly, verify that its count agrees with our
88769   ** internal count when using count(*) and when the total count can be
88770   ** expressed as a 32-bit integer. */
88771   assert( argc==1 || p==0 || p->n>0x7fffffff
88772           || p->n==sqlite3_aggregate_count(context) );
88773 #endif
88774 }
88775 static void countFinalize(sqlite3_context *context){
88776   CountCtx *p;
88777   p = sqlite3_aggregate_context(context, 0);
88778   sqlite3_result_int64(context, p ? p->n : 0);
88779 }
88780
88781 /*
88782 ** Routines to implement min() and max() aggregate functions.
88783 */
88784 static void minmaxStep(
88785   sqlite3_context *context,
88786   int NotUsed,
88787   sqlite3_value **argv
88788 ){
88789   Mem *pArg  = (Mem *)argv[0];
88790   Mem *pBest;
88791   UNUSED_PARAMETER(NotUsed);
88792
88793   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
88794   if( !pBest ) return;
88795
88796   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88797     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
88798   }else if( pBest->flags ){
88799     int max;
88800     int cmp;
88801     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
88802     /* This step function is used for both the min() and max() aggregates,
88803     ** the only difference between the two being that the sense of the
88804     ** comparison is inverted. For the max() aggregate, the
88805     ** sqlite3_user_data() function returns (void *)-1. For min() it
88806     ** returns (void *)db, where db is the sqlite3* database pointer.
88807     ** Therefore the next statement sets variable 'max' to 1 for the max()
88808     ** aggregate, or 0 for min().
88809     */
88810     max = sqlite3_user_data(context)!=0;
88811     cmp = sqlite3MemCompare(pBest, pArg, pColl);
88812     if( (max && cmp<0) || (!max && cmp>0) ){
88813       sqlite3VdbeMemCopy(pBest, pArg);
88814     }else{
88815       sqlite3SkipAccumulatorLoad(context);
88816     }
88817   }else{
88818     sqlite3VdbeMemCopy(pBest, pArg);
88819   }
88820 }
88821 static void minMaxFinalize(sqlite3_context *context){
88822   sqlite3_value *pRes;
88823   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
88824   if( pRes ){
88825     if( pRes->flags ){
88826       sqlite3_result_value(context, pRes);
88827     }
88828     sqlite3VdbeMemRelease(pRes);
88829   }
88830 }
88831
88832 /*
88833 ** group_concat(EXPR, ?SEPARATOR?)
88834 */
88835 static void groupConcatStep(
88836   sqlite3_context *context,
88837   int argc,
88838   sqlite3_value **argv
88839 ){
88840   const char *zVal;
88841   StrAccum *pAccum;
88842   const char *zSep;
88843   int nVal, nSep;
88844   assert( argc==1 || argc==2 );
88845   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
88846   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
88847
88848   if( pAccum ){
88849     sqlite3 *db = sqlite3_context_db_handle(context);
88850     int firstTerm = pAccum->useMalloc==0;
88851     pAccum->useMalloc = 2;
88852     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
88853     if( !firstTerm ){
88854       if( argc==2 ){
88855         zSep = (char*)sqlite3_value_text(argv[1]);
88856         nSep = sqlite3_value_bytes(argv[1]);
88857       }else{
88858         zSep = ",";
88859         nSep = 1;
88860       }
88861       sqlite3StrAccumAppend(pAccum, zSep, nSep);
88862     }
88863     zVal = (char*)sqlite3_value_text(argv[0]);
88864     nVal = sqlite3_value_bytes(argv[0]);
88865     sqlite3StrAccumAppend(pAccum, zVal, nVal);
88866   }
88867 }
88868 static void groupConcatFinalize(sqlite3_context *context){
88869   StrAccum *pAccum;
88870   pAccum = sqlite3_aggregate_context(context, 0);
88871   if( pAccum ){
88872     if( pAccum->tooBig ){
88873       sqlite3_result_error_toobig(context);
88874     }else if( pAccum->mallocFailed ){
88875       sqlite3_result_error_nomem(context);
88876     }else{
88877       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
88878                           sqlite3_free);
88879     }
88880   }
88881 }
88882
88883 /*
88884 ** This routine does per-connection function registration.  Most
88885 ** of the built-in functions above are part of the global function set.
88886 ** This routine only deals with those that are not global.
88887 */
88888 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
88889   int rc = sqlite3_overload_function(db, "MATCH", 2);
88890 #ifndef OMIT_EXPORT
88891   extern void sqlcipher_exportFunc(sqlite3_context *, int, sqlite3_value **);
88892 #endif
88893   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
88894   if( rc==SQLITE_NOMEM ){
88895     db->mallocFailed = 1;
88896   }
88897 #ifndef OMIT_EXPORT
88898   sqlite3CreateFunc(db, "sqlcipher_export", 1, SQLITE_TEXT, 0, sqlcipher_exportFunc, 0, 0, 0);
88899 #endif
88900 }
88901
88902 /*
88903 ** Set the LIKEOPT flag on the 2-argument function with the given name.
88904 */
88905 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
88906   FuncDef *pDef;
88907   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
88908                              2, SQLITE_UTF8, 0);
88909   if( ALWAYS(pDef) ){
88910     pDef->flags = flagVal;
88911   }
88912 }
88913
88914 /*
88915 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
88916 ** parameter determines whether or not the LIKE operator is case
88917 ** sensitive.  GLOB is always case sensitive.
88918 */
88919 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
88920   struct compareInfo *pInfo;
88921   if( caseSensitive ){
88922     pInfo = (struct compareInfo*)&likeInfoAlt;
88923   }else{
88924     pInfo = (struct compareInfo*)&likeInfoNorm;
88925   }
88926   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88927   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88928   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
88929       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
88930   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
88931   setLikeOptFlag(db, "like",
88932       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
88933 }
88934
88935 /*
88936 ** pExpr points to an expression which implements a function.  If
88937 ** it is appropriate to apply the LIKE optimization to that function
88938 ** then set aWc[0] through aWc[2] to the wildcard characters and
88939 ** return TRUE.  If the function is not a LIKE-style function then
88940 ** return FALSE.
88941 */
88942 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
88943   FuncDef *pDef;
88944   if( pExpr->op!=TK_FUNCTION
88945    || !pExpr->x.pList
88946    || pExpr->x.pList->nExpr!=2
88947   ){
88948     return 0;
88949   }
88950   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88951   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
88952                              sqlite3Strlen30(pExpr->u.zToken),
88953                              2, SQLITE_UTF8, 0);
88954   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
88955     return 0;
88956   }
88957
88958   /* The memcpy() statement assumes that the wildcard characters are
88959   ** the first three statements in the compareInfo structure.  The
88960   ** asserts() that follow verify that assumption
88961   */
88962   memcpy(aWc, pDef->pUserData, 3);
88963   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
88964   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
88965   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
88966   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
88967   return 1;
88968 }
88969
88970 /*
88971 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
88972 ** to the global function hash table.  This occurs at start-time (as
88973 ** a consequence of calling sqlite3_initialize()).
88974 **
88975 ** After this routine runs
88976 */
88977 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
88978   /*
88979   ** The following array holds FuncDef structures for all of the functions
88980   ** defined in this file.
88981   **
88982   ** The array cannot be constant since changes are made to the
88983   ** FuncDef.pHash elements at start-time.  The elements of this array
88984   ** are read-only after initialization is complete.
88985   */
88986   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
88987     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
88988     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
88989     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
88990     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
88991     FUNCTION(trim,               1, 3, 0, trimFunc         ),
88992     FUNCTION(trim,               2, 3, 0, trimFunc         ),
88993     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
88994     FUNCTION(min,                0, 0, 1, 0                ),
88995     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
88996     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
88997     FUNCTION(max,                0, 1, 1, 0                ),
88998     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
88999     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
89000     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
89001     FUNCTION(instr,              2, 0, 0, instrFunc        ),
89002     FUNCTION(substr,             2, 0, 0, substrFunc       ),
89003     FUNCTION(substr,             3, 0, 0, substrFunc       ),
89004     FUNCTION(abs,                1, 0, 0, absFunc          ),
89005 #ifndef SQLITE_OMIT_FLOATING_POINT
89006     FUNCTION(round,              1, 0, 0, roundFunc        ),
89007     FUNCTION(round,              2, 0, 0, roundFunc        ),
89008 #endif
89009     FUNCTION(upper,              1, 0, 0, upperFunc        ),
89010     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
89011     FUNCTION(coalesce,           1, 0, 0, 0                ),
89012     FUNCTION(coalesce,           0, 0, 0, 0                ),
89013     FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
89014     FUNCTION(hex,                1, 0, 0, hexFunc          ),
89015     FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
89016     FUNCTION(random,             0, 0, 0, randomFunc       ),
89017     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
89018     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
89019     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
89020     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
89021     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
89022 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
89023     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
89024     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
89025 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
89026     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
89027     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
89028     FUNCTION(changes,            0, 0, 0, changes          ),
89029     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
89030     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
89031     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
89032   #ifdef SQLITE_SOUNDEX
89033     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
89034   #endif
89035   #ifndef SQLITE_OMIT_LOAD_EXTENSION
89036     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
89037     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
89038   #endif
89039     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
89040     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
89041     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
89042  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
89043     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
89044     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
89045     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
89046     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
89047
89048     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
89049   #ifdef SQLITE_CASE_SENSITIVE_LIKE
89050     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
89051     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
89052   #else
89053     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
89054     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
89055   #endif
89056   };
89057
89058   int i;
89059   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
89060   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
89061
89062   for(i=0; i<ArraySize(aBuiltinFunc); i++){
89063     sqlite3FuncDefInsert(pHash, &aFunc[i]);
89064   }
89065   sqlite3RegisterDateTimeFunctions();
89066 #ifndef SQLITE_OMIT_ALTERTABLE
89067   sqlite3AlterFunctions();
89068 #endif
89069 }
89070
89071 /************** End of func.c ************************************************/
89072 /************** Begin file fkey.c ********************************************/
89073 /*
89074 **
89075 ** The author disclaims copyright to this source code.  In place of
89076 ** a legal notice, here is a blessing:
89077 **
89078 **    May you do good and not evil.
89079 **    May you find forgiveness for yourself and forgive others.
89080 **    May you share freely, never taking more than you give.
89081 **
89082 *************************************************************************
89083 ** This file contains code used by the compiler to add foreign key
89084 ** support to compiled SQL statements.
89085 */
89086
89087 #ifndef SQLITE_OMIT_FOREIGN_KEY
89088 #ifndef SQLITE_OMIT_TRIGGER
89089
89090 /*
89091 ** Deferred and Immediate FKs
89092 ** --------------------------
89093 **
89094 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
89095 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
89096 ** is returned and the current statement transaction rolled back. If a
89097 ** deferred foreign key constraint is violated, no action is taken
89098 ** immediately. However if the application attempts to commit the
89099 ** transaction before fixing the constraint violation, the attempt fails.
89100 **
89101 ** Deferred constraints are implemented using a simple counter associated
89102 ** with the database handle. The counter is set to zero each time a
89103 ** database transaction is opened. Each time a statement is executed
89104 ** that causes a foreign key violation, the counter is incremented. Each
89105 ** time a statement is executed that removes an existing violation from
89106 ** the database, the counter is decremented. When the transaction is
89107 ** committed, the commit fails if the current value of the counter is
89108 ** greater than zero. This scheme has two big drawbacks:
89109 **
89110 **   * When a commit fails due to a deferred foreign key constraint,
89111 **     there is no way to tell which foreign constraint is not satisfied,
89112 **     or which row it is not satisfied for.
89113 **
89114 **   * If the database contains foreign key violations when the
89115 **     transaction is opened, this may cause the mechanism to malfunction.
89116 **
89117 ** Despite these problems, this approach is adopted as it seems simpler
89118 ** than the alternatives.
89119 **
89120 ** INSERT operations:
89121 **
89122 **   I.1) For each FK for which the table is the child table, search
89123 **        the parent table for a match. If none is found increment the
89124 **        constraint counter.
89125 **
89126 **   I.2) For each FK for which the table is the parent table,
89127 **        search the child table for rows that correspond to the new
89128 **        row in the parent table. Decrement the counter for each row
89129 **        found (as the constraint is now satisfied).
89130 **
89131 ** DELETE operations:
89132 **
89133 **   D.1) For each FK for which the table is the child table,
89134 **        search the parent table for a row that corresponds to the
89135 **        deleted row in the child table. If such a row is not found,
89136 **        decrement the counter.
89137 **
89138 **   D.2) For each FK for which the table is the parent table, search
89139 **        the child table for rows that correspond to the deleted row
89140 **        in the parent table. For each found increment the counter.
89141 **
89142 ** UPDATE operations:
89143 **
89144 **   An UPDATE command requires that all 4 steps above are taken, but only
89145 **   for FK constraints for which the affected columns are actually
89146 **   modified (values must be compared at runtime).
89147 **
89148 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
89149 ** This simplifies the implementation a bit.
89150 **
89151 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
89152 ** resolution is considered to delete rows before the new row is inserted.
89153 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
89154 ** is thrown, even if the FK constraint would be satisfied after the new
89155 ** row is inserted.
89156 **
89157 ** Immediate constraints are usually handled similarly. The only difference
89158 ** is that the counter used is stored as part of each individual statement
89159 ** object (struct Vdbe). If, after the statement has run, its immediate
89160 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
89161 ** and the statement transaction is rolled back. An exception is an INSERT
89162 ** statement that inserts a single row only (no triggers). In this case,
89163 ** instead of using a counter, an exception is thrown immediately if the
89164 ** INSERT violates a foreign key constraint. This is necessary as such
89165 ** an INSERT does not open a statement transaction.
89166 **
89167 ** TODO: How should dropping a table be handled? How should renaming a
89168 ** table be handled?
89169 **
89170 **
89171 ** Query API Notes
89172 ** ---------------
89173 **
89174 ** Before coding an UPDATE or DELETE row operation, the code-generator
89175 ** for those two operations needs to know whether or not the operation
89176 ** requires any FK processing and, if so, which columns of the original
89177 ** row are required by the FK processing VDBE code (i.e. if FKs were
89178 ** implemented using triggers, which of the old.* columns would be
89179 ** accessed). No information is required by the code-generator before
89180 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
89181 ** generation code to query for this information are:
89182 **
89183 **   sqlite3FkRequired() - Test to see if FK processing is required.
89184 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
89185 **
89186 **
89187 ** Externally accessible module functions
89188 ** --------------------------------------
89189 **
89190 **   sqlite3FkCheck()    - Check for foreign key violations.
89191 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
89192 **   sqlite3FkDelete()   - Delete an FKey structure.
89193 */
89194
89195 /*
89196 ** VDBE Calling Convention
89197 ** -----------------------
89198 **
89199 ** Example:
89200 **
89201 **   For the following INSERT statement:
89202 **
89203 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
89204 **     INSERT INTO t1 VALUES(1, 2, 3.1);
89205 **
89206 **   Register (x):        2    (type integer)
89207 **   Register (x+1):      1    (type integer)
89208 **   Register (x+2):      NULL (type NULL)
89209 **   Register (x+3):      3.1  (type real)
89210 */
89211
89212 /*
89213 ** A foreign key constraint requires that the key columns in the parent
89214 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
89215 ** Given that pParent is the parent table for foreign key constraint pFKey,
89216 ** search the schema a unique index on the parent key columns.
89217 **
89218 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
89219 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
89220 ** is set to point to the unique index.
89221 **
89222 ** If the parent key consists of a single column (the foreign key constraint
89223 ** is not a composite foreign key), output variable *paiCol is set to NULL.
89224 ** Otherwise, it is set to point to an allocated array of size N, where
89225 ** N is the number of columns in the parent key. The first element of the
89226 ** array is the index of the child table column that is mapped by the FK
89227 ** constraint to the parent table column stored in the left-most column
89228 ** of index *ppIdx. The second element of the array is the index of the
89229 ** child table column that corresponds to the second left-most column of
89230 ** *ppIdx, and so on.
89231 **
89232 ** If the required index cannot be found, either because:
89233 **
89234 **   1) The named parent key columns do not exist, or
89235 **
89236 **   2) The named parent key columns do exist, but are not subject to a
89237 **      UNIQUE or PRIMARY KEY constraint, or
89238 **
89239 **   3) No parent key columns were provided explicitly as part of the
89240 **      foreign key definition, and the parent table does not have a
89241 **      PRIMARY KEY, or
89242 **
89243 **   4) No parent key columns were provided explicitly as part of the
89244 **      foreign key definition, and the PRIMARY KEY of the parent table
89245 **      consists of a a different number of columns to the child key in
89246 **      the child table.
89247 **
89248 ** then non-zero is returned, and a "foreign key mismatch" error loaded
89249 ** into pParse. If an OOM error occurs, non-zero is returned and the
89250 ** pParse->db->mallocFailed flag is set.
89251 */
89252 static int locateFkeyIndex(
89253   Parse *pParse,                  /* Parse context to store any error in */
89254   Table *pParent,                 /* Parent table of FK constraint pFKey */
89255   FKey *pFKey,                    /* Foreign key to find index for */
89256   Index **ppIdx,                  /* OUT: Unique index on parent table */
89257   int **paiCol                    /* OUT: Map of index columns in pFKey */
89258 ){
89259   Index *pIdx = 0;                    /* Value to return via *ppIdx */
89260   int *aiCol = 0;                     /* Value to return via *paiCol */
89261   int nCol = pFKey->nCol;             /* Number of columns in parent key */
89262   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
89263
89264   /* The caller is responsible for zeroing output parameters. */
89265   assert( ppIdx && *ppIdx==0 );
89266   assert( !paiCol || *paiCol==0 );
89267   assert( pParse );
89268
89269   /* If this is a non-composite (single column) foreign key, check if it
89270   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
89271   ** and *paiCol set to zero and return early.
89272   **
89273   ** Otherwise, for a composite foreign key (more than one column), allocate
89274   ** space for the aiCol array (returned via output parameter *paiCol).
89275   ** Non-composite foreign keys do not require the aiCol array.
89276   */
89277   if( nCol==1 ){
89278     /* The FK maps to the IPK if any of the following are true:
89279     **
89280     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
89281     **      mapped to the primary key of table pParent, or
89282     **   2) The FK is explicitly mapped to a column declared as INTEGER
89283     **      PRIMARY KEY.
89284     */
89285     if( pParent->iPKey>=0 ){
89286       if( !zKey ) return 0;
89287       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
89288     }
89289   }else if( paiCol ){
89290     assert( nCol>1 );
89291     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
89292     if( !aiCol ) return 1;
89293     *paiCol = aiCol;
89294   }
89295
89296   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
89297     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
89298       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
89299       ** of columns. If each indexed column corresponds to a foreign key
89300       ** column of pFKey, then this index is a winner.  */
89301
89302       if( zKey==0 ){
89303         /* If zKey is NULL, then this foreign key is implicitly mapped to
89304         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
89305         ** identified by the test (Index.autoIndex==2).  */
89306         if( pIdx->autoIndex==2 ){
89307           if( aiCol ){
89308             int i;
89309             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
89310           }
89311           break;
89312         }
89313       }else{
89314         /* If zKey is non-NULL, then this foreign key was declared to
89315         ** map to an explicit list of columns in table pParent. Check if this
89316         ** index matches those columns. Also, check that the index uses
89317         ** the default collation sequences for each column. */
89318         int i, j;
89319         for(i=0; i<nCol; i++){
89320           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
89321           char *zDfltColl;                  /* Def. collation for column */
89322           char *zIdxCol;                    /* Name of indexed column */
89323
89324           /* If the index uses a collation sequence that is different from
89325           ** the default collation sequence for the column, this index is
89326           ** unusable. Bail out early in this case.  */
89327           zDfltColl = pParent->aCol[iCol].zColl;
89328           if( !zDfltColl ){
89329             zDfltColl = "BINARY";
89330           }
89331           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
89332
89333           zIdxCol = pParent->aCol[iCol].zName;
89334           for(j=0; j<nCol; j++){
89335             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
89336               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
89337               break;
89338             }
89339           }
89340           if( j==nCol ) break;
89341         }
89342         if( i==nCol ) break;      /* pIdx is usable */
89343       }
89344     }
89345   }
89346
89347   if( !pIdx ){
89348     if( !pParse->disableTriggers ){
89349       sqlite3ErrorMsg(pParse, "foreign key mismatch");
89350     }
89351     sqlite3DbFree(pParse->db, aiCol);
89352     return 1;
89353   }
89354
89355   *ppIdx = pIdx;
89356   return 0;
89357 }
89358
89359 /*
89360 ** This function is called when a row is inserted into or deleted from the
89361 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
89362 ** on the child table of pFKey, this function is invoked twice for each row
89363 ** affected - once to "delete" the old row, and then again to "insert" the
89364 ** new row.
89365 **
89366 ** Each time it is called, this function generates VDBE code to locate the
89367 ** row in the parent table that corresponds to the row being inserted into
89368 ** or deleted from the child table. If the parent row can be found, no
89369 ** special action is taken. Otherwise, if the parent row can *not* be
89370 ** found in the parent table:
89371 **
89372 **   Operation | FK type   | Action taken
89373 **   --------------------------------------------------------------------------
89374 **   INSERT      immediate   Increment the "immediate constraint counter".
89375 **
89376 **   DELETE      immediate   Decrement the "immediate constraint counter".
89377 **
89378 **   INSERT      deferred    Increment the "deferred constraint counter".
89379 **
89380 **   DELETE      deferred    Decrement the "deferred constraint counter".
89381 **
89382 ** These operations are identified in the comment at the top of this file
89383 ** (fkey.c) as "I.1" and "D.1".
89384 */
89385 static void fkLookupParent(
89386   Parse *pParse,        /* Parse context */
89387   int iDb,              /* Index of database housing pTab */
89388   Table *pTab,          /* Parent table of FK pFKey */
89389   Index *pIdx,          /* Unique index on parent key columns in pTab */
89390   FKey *pFKey,          /* Foreign key constraint */
89391   int *aiCol,           /* Map from parent key columns to child table columns */
89392   int regData,          /* Address of array containing child table row */
89393   int nIncr,            /* Increment constraint counter by this */
89394   int isIgnore          /* If true, pretend pTab contains all NULL values */
89395 ){
89396   int i;                                    /* Iterator variable */
89397   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
89398   int iCur = pParse->nTab - 1;              /* Cursor number to use */
89399   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
89400
89401   /* If nIncr is less than zero, then check at runtime if there are any
89402   ** outstanding constraints to resolve. If there are not, there is no need
89403   ** to check if deleting this row resolves any outstanding violations.
89404   **
89405   ** Check if any of the key columns in the child table row are NULL. If
89406   ** any are, then the constraint is considered satisfied. No need to
89407   ** search for a matching row in the parent table.  */
89408   if( nIncr<0 ){
89409     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
89410   }
89411   for(i=0; i<pFKey->nCol; i++){
89412     int iReg = aiCol[i] + regData + 1;
89413     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
89414   }
89415
89416   if( isIgnore==0 ){
89417     if( pIdx==0 ){
89418       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
89419       ** column of the parent table (table pTab).  */
89420       int iMustBeInt;               /* Address of MustBeInt instruction */
89421       int regTemp = sqlite3GetTempReg(pParse);
89422
89423       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
89424       ** apply the affinity of the parent key). If this fails, then there
89425       ** is no matching parent key. Before using MustBeInt, make a copy of
89426       ** the value. Otherwise, the value inserted into the child key column
89427       ** will have INTEGER affinity applied to it, which may not be correct.  */
89428       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
89429       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
89430
89431       /* If the parent table is the same as the child table, and we are about
89432       ** to increment the constraint-counter (i.e. this is an INSERT operation),
89433       ** then check if the row being inserted matches itself. If so, do not
89434       ** increment the constraint-counter.  */
89435       if( pTab==pFKey->pFrom && nIncr==1 ){
89436         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
89437       }
89438
89439       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
89440       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
89441       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89442       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
89443       sqlite3VdbeJumpHere(v, iMustBeInt);
89444       sqlite3ReleaseTempReg(pParse, regTemp);
89445     }else{
89446       int nCol = pFKey->nCol;
89447       int regTemp = sqlite3GetTempRange(pParse, nCol);
89448       int regRec = sqlite3GetTempReg(pParse);
89449       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
89450
89451       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
89452       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
89453       for(i=0; i<nCol; i++){
89454         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
89455       }
89456
89457       /* If the parent table is the same as the child table, and we are about
89458       ** to increment the constraint-counter (i.e. this is an INSERT operation),
89459       ** then check if the row being inserted matches itself. If so, do not
89460       ** increment the constraint-counter.
89461       **
89462       ** If any of the parent-key values are NULL, then the row cannot match
89463       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
89464       ** of the parent-key values are NULL (at this point it is known that
89465       ** none of the child key values are).
89466       */
89467       if( pTab==pFKey->pFrom && nIncr==1 ){
89468         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
89469         for(i=0; i<nCol; i++){
89470           int iChild = aiCol[i]+1+regData;
89471           int iParent = pIdx->aiColumn[i]+1+regData;
89472           assert( aiCol[i]!=pTab->iPKey );
89473           if( pIdx->aiColumn[i]==pTab->iPKey ){
89474             /* The parent key is a composite key that includes the IPK column */
89475             iParent = regData;
89476           }
89477           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
89478           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89479         }
89480         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89481       }
89482
89483       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
89484       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
89485       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
89486
89487       sqlite3ReleaseTempReg(pParse, regRec);
89488       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
89489     }
89490   }
89491
89492   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89493     /* Special case: If this is an INSERT statement that will insert exactly
89494     ** one row into the table, raise a constraint immediately instead of
89495     ** incrementing a counter. This is necessary as the VM code is being
89496     ** generated for will not open a statement transaction.  */
89497     assert( nIncr==1 );
89498     sqlite3HaltConstraint(
89499         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
89500     );
89501   }else{
89502     if( nIncr>0 && pFKey->isDeferred==0 ){
89503       sqlite3ParseToplevel(pParse)->mayAbort = 1;
89504     }
89505     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89506   }
89507
89508   sqlite3VdbeResolveLabel(v, iOk);
89509   sqlite3VdbeAddOp1(v, OP_Close, iCur);
89510 }
89511
89512 /*
89513 ** This function is called to generate code executed when a row is deleted
89514 ** from the parent table of foreign key constraint pFKey and, if pFKey is
89515 ** deferred, when a row is inserted into the same table. When generating
89516 ** code for an SQL UPDATE operation, this function may be called twice -
89517 ** once to "delete" the old row and once to "insert" the new row.
89518 **
89519 ** The code generated by this function scans through the rows in the child
89520 ** table that correspond to the parent table row being deleted or inserted.
89521 ** For each child row found, one of the following actions is taken:
89522 **
89523 **   Operation | FK type   | Action taken
89524 **   --------------------------------------------------------------------------
89525 **   DELETE      immediate   Increment the "immediate constraint counter".
89526 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89527 **                           throw a "foreign key constraint failed" exception.
89528 **
89529 **   INSERT      immediate   Decrement the "immediate constraint counter".
89530 **
89531 **   DELETE      deferred    Increment the "deferred constraint counter".
89532 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89533 **                           throw a "foreign key constraint failed" exception.
89534 **
89535 **   INSERT      deferred    Decrement the "deferred constraint counter".
89536 **
89537 ** These operations are identified in the comment at the top of this file
89538 ** (fkey.c) as "I.2" and "D.2".
89539 */
89540 static void fkScanChildren(
89541   Parse *pParse,                  /* Parse context */
89542   SrcList *pSrc,                  /* SrcList containing the table to scan */
89543   Table *pTab,
89544   Index *pIdx,                    /* Foreign key index */
89545   FKey *pFKey,                    /* Foreign key relationship */
89546   int *aiCol,                     /* Map from pIdx cols to child table cols */
89547   int regData,                    /* Referenced table data starts here */
89548   int nIncr                       /* Amount to increment deferred counter by */
89549 ){
89550   sqlite3 *db = pParse->db;       /* Database handle */
89551   int i;                          /* Iterator variable */
89552   Expr *pWhere = 0;               /* WHERE clause to scan with */
89553   NameContext sNameContext;       /* Context used to resolve WHERE clause */
89554   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
89555   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
89556   Vdbe *v = sqlite3GetVdbe(pParse);
89557
89558   assert( !pIdx || pIdx->pTable==pTab );
89559
89560   if( nIncr<0 ){
89561     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
89562   }
89563
89564   /* Create an Expr object representing an SQL expression like:
89565   **
89566   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
89567   **
89568   ** The collation sequence used for the comparison should be that of
89569   ** the parent key columns. The affinity of the parent key column should
89570   ** be applied to each child key value before the comparison takes place.
89571   */
89572   for(i=0; i<pFKey->nCol; i++){
89573     Expr *pLeft;                  /* Value from parent table row */
89574     Expr *pRight;                 /* Column ref to child table */
89575     Expr *pEq;                    /* Expression (pLeft = pRight) */
89576     int iCol;                     /* Index of column in child table */
89577     const char *zCol;             /* Name of column in child table */
89578
89579     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89580     if( pLeft ){
89581       /* Set the collation sequence and affinity of the LHS of each TK_EQ
89582       ** expression to the parent key column defaults.  */
89583       if( pIdx ){
89584         Column *pCol;
89585         const char *zColl;
89586         iCol = pIdx->aiColumn[i];
89587         pCol = &pTab->aCol[iCol];
89588         if( pTab->iPKey==iCol ) iCol = -1;
89589         pLeft->iTable = regData+iCol+1;
89590         pLeft->affinity = pCol->affinity;
89591         zColl = pCol->zColl;
89592         if( zColl==0 ) zColl = db->pDfltColl->zName;
89593         pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
89594       }else{
89595         pLeft->iTable = regData;
89596         pLeft->affinity = SQLITE_AFF_INTEGER;
89597       }
89598     }
89599     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89600     assert( iCol>=0 );
89601     zCol = pFKey->pFrom->aCol[iCol].zName;
89602     pRight = sqlite3Expr(db, TK_ID, zCol);
89603     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
89604     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89605   }
89606
89607   /* If the child table is the same as the parent table, and this scan
89608   ** is taking place as part of a DELETE operation (operation D.2), omit the
89609   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
89610   ** clause, where $rowid is the rowid of the row being deleted.  */
89611   if( pTab==pFKey->pFrom && nIncr>0 ){
89612     Expr *pEq;                    /* Expression (pLeft = pRight) */
89613     Expr *pLeft;                  /* Value from parent table row */
89614     Expr *pRight;                 /* Column ref to child table */
89615     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89616     pRight = sqlite3Expr(db, TK_COLUMN, 0);
89617     if( pLeft && pRight ){
89618       pLeft->iTable = regData;
89619       pLeft->affinity = SQLITE_AFF_INTEGER;
89620       pRight->iTable = pSrc->a[0].iCursor;
89621       pRight->iColumn = -1;
89622     }
89623     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
89624     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89625   }
89626
89627   /* Resolve the references in the WHERE clause. */
89628   memset(&sNameContext, 0, sizeof(NameContext));
89629   sNameContext.pSrcList = pSrc;
89630   sNameContext.pParse = pParse;
89631   sqlite3ResolveExprNames(&sNameContext, pWhere);
89632
89633   /* Create VDBE to loop through the entries in pSrc that match the WHERE
89634   ** clause. If the constraint is not deferred, throw an exception for
89635   ** each row found. Otherwise, for deferred constraints, increment the
89636   ** deferred constraint counter by nIncr for each row selected.  */
89637   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
89638   if( nIncr>0 && pFKey->isDeferred==0 ){
89639     sqlite3ParseToplevel(pParse)->mayAbort = 1;
89640   }
89641   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89642   if( pWInfo ){
89643     sqlite3WhereEnd(pWInfo);
89644   }
89645
89646   /* Clean up the WHERE clause constructed above. */
89647   sqlite3ExprDelete(db, pWhere);
89648   if( iFkIfZero ){
89649     sqlite3VdbeJumpHere(v, iFkIfZero);
89650   }
89651 }
89652
89653 /*
89654 ** This function returns a pointer to the head of a linked list of FK
89655 ** constraints for which table pTab is the parent table. For example,
89656 ** given the following schema:
89657 **
89658 **   CREATE TABLE t1(a PRIMARY KEY);
89659 **   CREATE TABLE t2(b REFERENCES t1(a);
89660 **
89661 ** Calling this function with table "t1" as an argument returns a pointer
89662 ** to the FKey structure representing the foreign key constraint on table
89663 ** "t2". Calling this function with "t2" as the argument would return a
89664 ** NULL pointer (as there are no FK constraints for which t2 is the parent
89665 ** table).
89666 */
89667 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
89668   int nName = sqlite3Strlen30(pTab->zName);
89669   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
89670 }
89671
89672 /*
89673 ** The second argument is a Trigger structure allocated by the
89674 ** fkActionTrigger() routine. This function deletes the Trigger structure
89675 ** and all of its sub-components.
89676 **
89677 ** The Trigger structure or any of its sub-components may be allocated from
89678 ** the lookaside buffer belonging to database handle dbMem.
89679 */
89680 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
89681   if( p ){
89682     TriggerStep *pStep = p->step_list;
89683     sqlite3ExprDelete(dbMem, pStep->pWhere);
89684     sqlite3ExprListDelete(dbMem, pStep->pExprList);
89685     sqlite3SelectDelete(dbMem, pStep->pSelect);
89686     sqlite3ExprDelete(dbMem, p->pWhen);
89687     sqlite3DbFree(dbMem, p);
89688   }
89689 }
89690
89691 /*
89692 ** This function is called to generate code that runs when table pTab is
89693 ** being dropped from the database. The SrcList passed as the second argument
89694 ** to this function contains a single entry guaranteed to resolve to
89695 ** table pTab.
89696 **
89697 ** Normally, no code is required. However, if either
89698 **
89699 **   (a) The table is the parent table of a FK constraint, or
89700 **   (b) The table is the child table of a deferred FK constraint and it is
89701 **       determined at runtime that there are outstanding deferred FK
89702 **       constraint violations in the database,
89703 **
89704 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
89705 ** the table from the database. Triggers are disabled while running this
89706 ** DELETE, but foreign key actions are not.
89707 */
89708 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
89709   sqlite3 *db = pParse->db;
89710   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
89711     int iSkip = 0;
89712     Vdbe *v = sqlite3GetVdbe(pParse);
89713
89714     assert( v );                  /* VDBE has already been allocated */
89715     if( sqlite3FkReferences(pTab)==0 ){
89716       /* Search for a deferred foreign key constraint for which this table
89717       ** is the child table. If one cannot be found, return without
89718       ** generating any VDBE code. If one can be found, then jump over
89719       ** the entire DELETE if there are no outstanding deferred constraints
89720       ** when this statement is run.  */
89721       FKey *p;
89722       for(p=pTab->pFKey; p; p=p->pNextFrom){
89723         if( p->isDeferred ) break;
89724       }
89725       if( !p ) return;
89726       iSkip = sqlite3VdbeMakeLabel(v);
89727       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
89728     }
89729
89730     pParse->disableTriggers = 1;
89731     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
89732     pParse->disableTriggers = 0;
89733
89734     /* If the DELETE has generated immediate foreign key constraint
89735     ** violations, halt the VDBE and return an error at this point, before
89736     ** any modifications to the schema are made. This is because statement
89737     ** transactions are not able to rollback schema changes.  */
89738     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
89739     sqlite3HaltConstraint(
89740         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
89741     );
89742
89743     if( iSkip ){
89744       sqlite3VdbeResolveLabel(v, iSkip);
89745     }
89746   }
89747 }
89748
89749 /*
89750 ** This function is called when inserting, deleting or updating a row of
89751 ** table pTab to generate VDBE code to perform foreign key constraint
89752 ** processing for the operation.
89753 **
89754 ** For a DELETE operation, parameter regOld is passed the index of the
89755 ** first register in an array of (pTab->nCol+1) registers containing the
89756 ** rowid of the row being deleted, followed by each of the column values
89757 ** of the row being deleted, from left to right. Parameter regNew is passed
89758 ** zero in this case.
89759 **
89760 ** For an INSERT operation, regOld is passed zero and regNew is passed the
89761 ** first register of an array of (pTab->nCol+1) registers containing the new
89762 ** row data.
89763 **
89764 ** For an UPDATE operation, this function is called twice. Once before
89765 ** the original record is deleted from the table using the calling convention
89766 ** described for DELETE. Then again after the original record is deleted
89767 ** but before the new record is inserted using the INSERT convention.
89768 */
89769 SQLITE_PRIVATE void sqlite3FkCheck(
89770   Parse *pParse,                  /* Parse context */
89771   Table *pTab,                    /* Row is being deleted from this table */
89772   int regOld,                     /* Previous row data is stored here */
89773   int regNew                      /* New row data is stored here */
89774 ){
89775   sqlite3 *db = pParse->db;       /* Database handle */
89776   FKey *pFKey;                    /* Used to iterate through FKs */
89777   int iDb;                        /* Index of database containing pTab */
89778   const char *zDb;                /* Name of database containing pTab */
89779   int isIgnoreErrors = pParse->disableTriggers;
89780
89781   /* Exactly one of regOld and regNew should be non-zero. */
89782   assert( (regOld==0)!=(regNew==0) );
89783
89784   /* If foreign-keys are disabled, this function is a no-op. */
89785   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
89786
89787   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89788   zDb = db->aDb[iDb].zName;
89789
89790   /* Loop through all the foreign key constraints for which pTab is the
89791   ** child table (the table that the foreign key definition is part of).  */
89792   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
89793     Table *pTo;                   /* Parent table of foreign key pFKey */
89794     Index *pIdx = 0;              /* Index on key columns in pTo */
89795     int *aiFree = 0;
89796     int *aiCol;
89797     int iCol;
89798     int i;
89799     int isIgnore = 0;
89800
89801     /* Find the parent table of this foreign key. Also find a unique index
89802     ** on the parent key columns in the parent table. If either of these
89803     ** schema items cannot be located, set an error in pParse and return
89804     ** early.  */
89805     if( pParse->disableTriggers ){
89806       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
89807     }else{
89808       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
89809     }
89810     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
89811       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
89812       if( !isIgnoreErrors || db->mallocFailed ) return;
89813       if( pTo==0 ){
89814         /* If isIgnoreErrors is true, then a table is being dropped. In this
89815         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
89816         ** before actually dropping it in order to check FK constraints.
89817         ** If the parent table of an FK constraint on the current table is
89818         ** missing, behave as if it is empty. i.e. decrement the relevant
89819         ** FK counter for each row of the current table with non-NULL keys.
89820         */
89821         Vdbe *v = sqlite3GetVdbe(pParse);
89822         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
89823         for(i=0; i<pFKey->nCol; i++){
89824           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
89825           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
89826         }
89827         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
89828       }
89829       continue;
89830     }
89831     assert( pFKey->nCol==1 || (aiFree && pIdx) );
89832
89833     if( aiFree ){
89834       aiCol = aiFree;
89835     }else{
89836       iCol = pFKey->aCol[0].iFrom;
89837       aiCol = &iCol;
89838     }
89839     for(i=0; i<pFKey->nCol; i++){
89840       if( aiCol[i]==pTab->iPKey ){
89841         aiCol[i] = -1;
89842       }
89843 #ifndef SQLITE_OMIT_AUTHORIZATION
89844       /* Request permission to read the parent key columns. If the
89845       ** authorization callback returns SQLITE_IGNORE, behave as if any
89846       ** values read from the parent table are NULL. */
89847       if( db->xAuth ){
89848         int rcauth;
89849         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
89850         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
89851         isIgnore = (rcauth==SQLITE_IGNORE);
89852       }
89853 #endif
89854     }
89855
89856     /* Take a shared-cache advisory read-lock on the parent table. Allocate
89857     ** a cursor to use to search the unique index on the parent key columns
89858     ** in the parent table.  */
89859     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
89860     pParse->nTab++;
89861
89862     if( regOld!=0 ){
89863       /* A row is being removed from the child table. Search for the parent.
89864       ** If the parent does not exist, removing the child row resolves an
89865       ** outstanding foreign key constraint violation. */
89866       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
89867     }
89868     if( regNew!=0 ){
89869       /* A row is being added to the child table. If a parent row cannot
89870       ** be found, adding the child row has violated the FK constraint. */
89871       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
89872     }
89873
89874     sqlite3DbFree(db, aiFree);
89875   }
89876
89877   /* Loop through all the foreign key constraints that refer to this table */
89878   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
89879     Index *pIdx = 0;              /* Foreign key index for pFKey */
89880     SrcList *pSrc;
89881     int *aiCol = 0;
89882
89883     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89884       assert( regOld==0 && regNew!=0 );
89885       /* Inserting a single row into a parent table cannot cause an immediate
89886       ** foreign key violation. So do nothing in this case.  */
89887       continue;
89888     }
89889
89890     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
89891       if( !isIgnoreErrors || db->mallocFailed ) return;
89892       continue;
89893     }
89894     assert( aiCol || pFKey->nCol==1 );
89895
89896     /* Create a SrcList structure containing a single table (the table
89897     ** the foreign key that refers to this table is attached to). This
89898     ** is required for the sqlite3WhereXXX() interface.  */
89899     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
89900     if( pSrc ){
89901       struct SrcList_item *pItem = pSrc->a;
89902       pItem->pTab = pFKey->pFrom;
89903       pItem->zName = pFKey->pFrom->zName;
89904       pItem->pTab->nRef++;
89905       pItem->iCursor = pParse->nTab++;
89906
89907       if( regNew!=0 ){
89908         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
89909       }
89910       if( regOld!=0 ){
89911         /* If there is a RESTRICT action configured for the current operation
89912         ** on the parent table of this FK, then throw an exception
89913         ** immediately if the FK constraint is violated, even if this is a
89914         ** deferred trigger. That's what RESTRICT means. To defer checking
89915         ** the constraint, the FK should specify NO ACTION (represented
89916         ** using OE_None). NO ACTION is the default.  */
89917         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
89918       }
89919       pItem->zName = 0;
89920       sqlite3SrcListDelete(db, pSrc);
89921     }
89922     sqlite3DbFree(db, aiCol);
89923   }
89924 }
89925
89926 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
89927
89928 /*
89929 ** This function is called before generating code to update or delete a
89930 ** row contained in table pTab.
89931 */
89932 SQLITE_PRIVATE u32 sqlite3FkOldmask(
89933   Parse *pParse,                  /* Parse context */
89934   Table *pTab                     /* Table being modified */
89935 ){
89936   u32 mask = 0;
89937   if( pParse->db->flags&SQLITE_ForeignKeys ){
89938     FKey *p;
89939     int i;
89940     for(p=pTab->pFKey; p; p=p->pNextFrom){
89941       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
89942     }
89943     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89944       Index *pIdx = 0;
89945       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
89946       if( pIdx ){
89947         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
89948       }
89949     }
89950   }
89951   return mask;
89952 }
89953
89954 /*
89955 ** This function is called before generating code to update or delete a
89956 ** row contained in table pTab. If the operation is a DELETE, then
89957 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
89958 ** to an array of size N, where N is the number of columns in table pTab.
89959 ** If the i'th column is not modified by the UPDATE, then the corresponding
89960 ** entry in the aChange[] array is set to -1. If the column is modified,
89961 ** the value is 0 or greater. Parameter chngRowid is set to true if the
89962 ** UPDATE statement modifies the rowid fields of the table.
89963 **
89964 ** If any foreign key processing will be required, this function returns
89965 ** true. If there is no foreign key related processing, this function
89966 ** returns false.
89967 */
89968 SQLITE_PRIVATE int sqlite3FkRequired(
89969   Parse *pParse,                  /* Parse context */
89970   Table *pTab,                    /* Table being modified */
89971   int *aChange,                   /* Non-NULL for UPDATE operations */
89972   int chngRowid                   /* True for UPDATE that affects rowid */
89973 ){
89974   if( pParse->db->flags&SQLITE_ForeignKeys ){
89975     if( !aChange ){
89976       /* A DELETE operation. Foreign key processing is required if the
89977       ** table in question is either the child or parent table for any
89978       ** foreign key constraint.  */
89979       return (sqlite3FkReferences(pTab) || pTab->pFKey);
89980     }else{
89981       /* This is an UPDATE. Foreign key processing is only required if the
89982       ** operation modifies one or more child or parent key columns. */
89983       int i;
89984       FKey *p;
89985
89986       /* Check if any child key columns are being modified. */
89987       for(p=pTab->pFKey; p; p=p->pNextFrom){
89988         for(i=0; i<p->nCol; i++){
89989           int iChildKey = p->aCol[i].iFrom;
89990           if( aChange[iChildKey]>=0 ) return 1;
89991           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
89992         }
89993       }
89994
89995       /* Check if any parent key columns are being modified. */
89996       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89997         for(i=0; i<p->nCol; i++){
89998           char *zKey = p->aCol[i].zCol;
89999           int iKey;
90000           for(iKey=0; iKey<pTab->nCol; iKey++){
90001             Column *pCol = &pTab->aCol[iKey];
90002             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
90003                       : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
90004               if( aChange[iKey]>=0 ) return 1;
90005               if( iKey==pTab->iPKey && chngRowid ) return 1;
90006             }
90007           }
90008         }
90009       }
90010     }
90011   }
90012   return 0;
90013 }
90014
90015 /*
90016 ** This function is called when an UPDATE or DELETE operation is being
90017 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
90018 ** If the current operation is an UPDATE, then the pChanges parameter is
90019 ** passed a pointer to the list of columns being modified. If it is a
90020 ** DELETE, pChanges is passed a NULL pointer.
90021 **
90022 ** It returns a pointer to a Trigger structure containing a trigger
90023 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
90024 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
90025 ** returned (these actions require no special handling by the triggers
90026 ** sub-system, code for them is created by fkScanChildren()).
90027 **
90028 ** For example, if pFKey is the foreign key and pTab is table "p" in
90029 ** the following schema:
90030 **
90031 **   CREATE TABLE p(pk PRIMARY KEY);
90032 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
90033 **
90034 ** then the returned trigger structure is equivalent to:
90035 **
90036 **   CREATE TRIGGER ... DELETE ON p BEGIN
90037 **     DELETE FROM c WHERE ck = old.pk;
90038 **   END;
90039 **
90040 ** The returned pointer is cached as part of the foreign key object. It
90041 ** is eventually freed along with the rest of the foreign key object by
90042 ** sqlite3FkDelete().
90043 */
90044 static Trigger *fkActionTrigger(
90045   Parse *pParse,                  /* Parse context */
90046   Table *pTab,                    /* Table being updated or deleted from */
90047   FKey *pFKey,                    /* Foreign key to get action for */
90048   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
90049 ){
90050   sqlite3 *db = pParse->db;       /* Database handle */
90051   int action;                     /* One of OE_None, OE_Cascade etc. */
90052   Trigger *pTrigger;              /* Trigger definition to return */
90053   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
90054
90055   action = pFKey->aAction[iAction];
90056   pTrigger = pFKey->apTrigger[iAction];
90057
90058   if( action!=OE_None && !pTrigger ){
90059     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
90060     char const *zFrom;            /* Name of child table */
90061     int nFrom;                    /* Length in bytes of zFrom */
90062     Index *pIdx = 0;              /* Parent key index for this FK */
90063     int *aiCol = 0;               /* child table cols -> parent key cols */
90064     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
90065     Expr *pWhere = 0;             /* WHERE clause of trigger step */
90066     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
90067     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
90068     int i;                        /* Iterator variable */
90069     Expr *pWhen = 0;              /* WHEN clause for the trigger */
90070
90071     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
90072     assert( aiCol || pFKey->nCol==1 );
90073
90074     for(i=0; i<pFKey->nCol; i++){
90075       Token tOld = { "old", 3 };  /* Literal "old" token */
90076       Token tNew = { "new", 3 };  /* Literal "new" token */
90077       Token tFromCol;             /* Name of column in child table */
90078       Token tToCol;               /* Name of column in parent table */
90079       int iFromCol;               /* Idx of column in child table */
90080       Expr *pEq;                  /* tFromCol = OLD.tToCol */
90081
90082       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
90083       assert( iFromCol>=0 );
90084       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
90085       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
90086
90087       tToCol.n = sqlite3Strlen30(tToCol.z);
90088       tFromCol.n = sqlite3Strlen30(tFromCol.z);
90089
90090       /* Create the expression "OLD.zToCol = zFromCol". It is important
90091       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
90092       ** that the affinity and collation sequence associated with the
90093       ** parent table are used for the comparison. */
90094       pEq = sqlite3PExpr(pParse, TK_EQ,
90095           sqlite3PExpr(pParse, TK_DOT,
90096             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
90097             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
90098           , 0),
90099           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
90100       , 0);
90101       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
90102
90103       /* For ON UPDATE, construct the next term of the WHEN clause.
90104       ** The final WHEN clause will be like this:
90105       **
90106       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
90107       */
90108       if( pChanges ){
90109         pEq = sqlite3PExpr(pParse, TK_IS,
90110             sqlite3PExpr(pParse, TK_DOT,
90111               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
90112               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
90113               0),
90114             sqlite3PExpr(pParse, TK_DOT,
90115               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
90116               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
90117               0),
90118             0);
90119         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
90120       }
90121
90122       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
90123         Expr *pNew;
90124         if( action==OE_Cascade ){
90125           pNew = sqlite3PExpr(pParse, TK_DOT,
90126             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
90127             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
90128           , 0);
90129         }else if( action==OE_SetDflt ){
90130           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
90131           if( pDflt ){
90132             pNew = sqlite3ExprDup(db, pDflt, 0);
90133           }else{
90134             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
90135           }
90136         }else{
90137           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
90138         }
90139         pList = sqlite3ExprListAppend(pParse, pList, pNew);
90140         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
90141       }
90142     }
90143     sqlite3DbFree(db, aiCol);
90144
90145     zFrom = pFKey->pFrom->zName;
90146     nFrom = sqlite3Strlen30(zFrom);
90147
90148     if( action==OE_Restrict ){
90149       Token tFrom;
90150       Expr *pRaise;
90151
90152       tFrom.z = zFrom;
90153       tFrom.n = nFrom;
90154       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
90155       if( pRaise ){
90156         pRaise->affinity = OE_Abort;
90157       }
90158       pSelect = sqlite3SelectNew(pParse,
90159           sqlite3ExprListAppend(pParse, 0, pRaise),
90160           sqlite3SrcListAppend(db, 0, &tFrom, 0),
90161           pWhere,
90162           0, 0, 0, 0, 0, 0
90163       );
90164       pWhere = 0;
90165     }
90166
90167     /* Disable lookaside memory allocation */
90168     enableLookaside = db->lookaside.bEnabled;
90169     db->lookaside.bEnabled = 0;
90170
90171     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
90172         sizeof(Trigger) +         /* struct Trigger */
90173         sizeof(TriggerStep) +     /* Single step in trigger program */
90174         nFrom + 1                 /* Space for pStep->target.z */
90175     );
90176     if( pTrigger ){
90177       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
90178       pStep->target.z = (char *)&pStep[1];
90179       pStep->target.n = nFrom;
90180       memcpy((char *)pStep->target.z, zFrom, nFrom);
90181
90182       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
90183       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
90184       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
90185       if( pWhen ){
90186         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
90187         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
90188       }
90189     }
90190
90191     /* Re-enable the lookaside buffer, if it was disabled earlier. */
90192     db->lookaside.bEnabled = enableLookaside;
90193
90194     sqlite3ExprDelete(db, pWhere);
90195     sqlite3ExprDelete(db, pWhen);
90196     sqlite3ExprListDelete(db, pList);
90197     sqlite3SelectDelete(db, pSelect);
90198     if( db->mallocFailed==1 ){
90199       fkTriggerDelete(db, pTrigger);
90200       return 0;
90201     }
90202     assert( pStep!=0 );
90203
90204     switch( action ){
90205       case OE_Restrict:
90206         pStep->op = TK_SELECT;
90207         break;
90208       case OE_Cascade:
90209         if( !pChanges ){
90210           pStep->op = TK_DELETE;
90211           break;
90212         }
90213       default:
90214         pStep->op = TK_UPDATE;
90215     }
90216     pStep->pTrig = pTrigger;
90217     pTrigger->pSchema = pTab->pSchema;
90218     pTrigger->pTabSchema = pTab->pSchema;
90219     pFKey->apTrigger[iAction] = pTrigger;
90220     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
90221   }
90222
90223   return pTrigger;
90224 }
90225
90226 /*
90227 ** This function is called when deleting or updating a row to implement
90228 ** any required CASCADE, SET NULL or SET DEFAULT actions.
90229 */
90230 SQLITE_PRIVATE void sqlite3FkActions(
90231   Parse *pParse,                  /* Parse context */
90232   Table *pTab,                    /* Table being updated or deleted from */
90233   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
90234   int regOld                      /* Address of array containing old row */
90235 ){
90236   /* If foreign-key support is enabled, iterate through all FKs that
90237   ** refer to table pTab. If there is an action associated with the FK
90238   ** for this operation (either update or delete), invoke the associated
90239   ** trigger sub-program.  */
90240   if( pParse->db->flags&SQLITE_ForeignKeys ){
90241     FKey *pFKey;                  /* Iterator variable */
90242     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
90243       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
90244       if( pAction ){
90245         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
90246       }
90247     }
90248   }
90249 }
90250
90251 #endif /* ifndef SQLITE_OMIT_TRIGGER */
90252
90253 /*
90254 ** Free all memory associated with foreign key definitions attached to
90255 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
90256 ** hash table.
90257 */
90258 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
90259   FKey *pFKey;                    /* Iterator variable */
90260   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
90261
90262   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
90263   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
90264
90265     /* Remove the FK from the fkeyHash hash table. */
90266     if( !db || db->pnBytesFreed==0 ){
90267       if( pFKey->pPrevTo ){
90268         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
90269       }else{
90270         void *p = (void *)pFKey->pNextTo;
90271         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
90272         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
90273       }
90274       if( pFKey->pNextTo ){
90275         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
90276       }
90277     }
90278
90279     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
90280     ** classified as either immediate or deferred.
90281     */
90282     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
90283
90284     /* Delete any triggers created to implement actions for this FK. */
90285 #ifndef SQLITE_OMIT_TRIGGER
90286     fkTriggerDelete(db, pFKey->apTrigger[0]);
90287     fkTriggerDelete(db, pFKey->apTrigger[1]);
90288 #endif
90289
90290     pNext = pFKey->pNextFrom;
90291     sqlite3DbFree(db, pFKey);
90292   }
90293 }
90294 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
90295
90296 /************** End of fkey.c ************************************************/
90297 /************** Begin file insert.c ******************************************/
90298 /*
90299 ** 2001 September 15
90300 **
90301 ** The author disclaims copyright to this source code.  In place of
90302 ** a legal notice, here is a blessing:
90303 **
90304 **    May you do good and not evil.
90305 **    May you find forgiveness for yourself and forgive others.
90306 **    May you share freely, never taking more than you give.
90307 **
90308 *************************************************************************
90309 ** This file contains C code routines that are called by the parser
90310 ** to handle INSERT statements in SQLite.
90311 */
90312
90313 /*
90314 ** Generate code that will open a table for reading.
90315 */
90316 SQLITE_PRIVATE void sqlite3OpenTable(
90317   Parse *p,       /* Generate code into this VDBE */
90318   int iCur,       /* The cursor number of the table */
90319   int iDb,        /* The database index in sqlite3.aDb[] */
90320   Table *pTab,    /* The table to be opened */
90321   int opcode      /* OP_OpenRead or OP_OpenWrite */
90322 ){
90323   Vdbe *v;
90324   assert( !IsVirtual(pTab) );
90325   v = sqlite3GetVdbe(p);
90326   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
90327   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
90328   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
90329   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
90330   VdbeComment((v, "%s", pTab->zName));
90331 }
90332
90333 /*
90334 ** Return a pointer to the column affinity string associated with index
90335 ** pIdx. A column affinity string has one character for each column in
90336 ** the table, according to the affinity of the column:
90337 **
90338 **  Character      Column affinity
90339 **  ------------------------------
90340 **  'a'            TEXT
90341 **  'b'            NONE
90342 **  'c'            NUMERIC
90343 **  'd'            INTEGER
90344 **  'e'            REAL
90345 **
90346 ** An extra 'd' is appended to the end of the string to cover the
90347 ** rowid that appears as the last column in every index.
90348 **
90349 ** Memory for the buffer containing the column index affinity string
90350 ** is managed along with the rest of the Index structure. It will be
90351 ** released when sqlite3DeleteIndex() is called.
90352 */
90353 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
90354   if( !pIdx->zColAff ){
90355     /* The first time a column affinity string for a particular index is
90356     ** required, it is allocated and populated here. It is then stored as
90357     ** a member of the Index structure for subsequent use.
90358     **
90359     ** The column affinity string will eventually be deleted by
90360     ** sqliteDeleteIndex() when the Index structure itself is cleaned
90361     ** up.
90362     */
90363     int n;
90364     Table *pTab = pIdx->pTable;
90365     sqlite3 *db = sqlite3VdbeDb(v);
90366     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
90367     if( !pIdx->zColAff ){
90368       db->mallocFailed = 1;
90369       return 0;
90370     }
90371     for(n=0; n<pIdx->nColumn; n++){
90372       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
90373     }
90374     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
90375     pIdx->zColAff[n] = 0;
90376   }
90377
90378   return pIdx->zColAff;
90379 }
90380
90381 /*
90382 ** Set P4 of the most recently inserted opcode to a column affinity
90383 ** string for table pTab. A column affinity string has one character
90384 ** for each column indexed by the index, according to the affinity of the
90385 ** column:
90386 **
90387 **  Character      Column affinity
90388 **  ------------------------------
90389 **  'a'            TEXT
90390 **  'b'            NONE
90391 **  'c'            NUMERIC
90392 **  'd'            INTEGER
90393 **  'e'            REAL
90394 */
90395 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
90396   /* The first time a column affinity string for a particular table
90397   ** is required, it is allocated and populated here. It is then
90398   ** stored as a member of the Table structure for subsequent use.
90399   **
90400   ** The column affinity string will eventually be deleted by
90401   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
90402   */
90403   if( !pTab->zColAff ){
90404     char *zColAff;
90405     int i;
90406     sqlite3 *db = sqlite3VdbeDb(v);
90407
90408     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
90409     if( !zColAff ){
90410       db->mallocFailed = 1;
90411       return;
90412     }
90413
90414     for(i=0; i<pTab->nCol; i++){
90415       zColAff[i] = pTab->aCol[i].affinity;
90416     }
90417     zColAff[pTab->nCol] = '\0';
90418
90419     pTab->zColAff = zColAff;
90420   }
90421
90422   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
90423 }
90424
90425 /*
90426 ** Return non-zero if the table pTab in database iDb or any of its indices
90427 ** have been opened at any point in the VDBE program beginning at location
90428 ** iStartAddr throught the end of the program.  This is used to see if
90429 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
90430 ** run without using temporary table for the results of the SELECT.
90431 */
90432 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
90433   Vdbe *v = sqlite3GetVdbe(p);
90434   int i;
90435   int iEnd = sqlite3VdbeCurrentAddr(v);
90436 #ifndef SQLITE_OMIT_VIRTUALTABLE
90437   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
90438 #endif
90439
90440   for(i=iStartAddr; i<iEnd; i++){
90441     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
90442     assert( pOp!=0 );
90443     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
90444       Index *pIndex;
90445       int tnum = pOp->p2;
90446       if( tnum==pTab->tnum ){
90447         return 1;
90448       }
90449       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
90450         if( tnum==pIndex->tnum ){
90451           return 1;
90452         }
90453       }
90454     }
90455 #ifndef SQLITE_OMIT_VIRTUALTABLE
90456     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
90457       assert( pOp->p4.pVtab!=0 );
90458       assert( pOp->p4type==P4_VTAB );
90459       return 1;
90460     }
90461 #endif
90462   }
90463   return 0;
90464 }
90465
90466 #ifndef SQLITE_OMIT_AUTOINCREMENT
90467 /*
90468 ** Locate or create an AutoincInfo structure associated with table pTab
90469 ** which is in database iDb.  Return the register number for the register
90470 ** that holds the maximum rowid.
90471 **
90472 ** There is at most one AutoincInfo structure per table even if the
90473 ** same table is autoincremented multiple times due to inserts within
90474 ** triggers.  A new AutoincInfo structure is created if this is the
90475 ** first use of table pTab.  On 2nd and subsequent uses, the original
90476 ** AutoincInfo structure is used.
90477 **
90478 ** Three memory locations are allocated:
90479 **
90480 **   (1)  Register to hold the name of the pTab table.
90481 **   (2)  Register to hold the maximum ROWID of pTab.
90482 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
90483 **
90484 ** The 2nd register is the one that is returned.  That is all the
90485 ** insert routine needs to know about.
90486 */
90487 static int autoIncBegin(
90488   Parse *pParse,      /* Parsing context */
90489   int iDb,            /* Index of the database holding pTab */
90490   Table *pTab         /* The table we are writing to */
90491 ){
90492   int memId = 0;      /* Register holding maximum rowid */
90493   if( pTab->tabFlags & TF_Autoincrement ){
90494     Parse *pToplevel = sqlite3ParseToplevel(pParse);
90495     AutoincInfo *pInfo;
90496
90497     pInfo = pToplevel->pAinc;
90498     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
90499     if( pInfo==0 ){
90500       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
90501       if( pInfo==0 ) return 0;
90502       pInfo->pNext = pToplevel->pAinc;
90503       pToplevel->pAinc = pInfo;
90504       pInfo->pTab = pTab;
90505       pInfo->iDb = iDb;
90506       pToplevel->nMem++;                  /* Register to hold name of table */
90507       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
90508       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
90509     }
90510     memId = pInfo->regCtr;
90511   }
90512   return memId;
90513 }
90514
90515 /*
90516 ** This routine generates code that will initialize all of the
90517 ** register used by the autoincrement tracker.
90518 */
90519 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
90520   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
90521   sqlite3 *db = pParse->db;  /* The database connection */
90522   Db *pDb;                   /* Database only autoinc table */
90523   int memId;                 /* Register holding max rowid */
90524   int addr;                  /* A VDBE address */
90525   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
90526
90527   /* This routine is never called during trigger-generation.  It is
90528   ** only called from the top-level */
90529   assert( pParse->pTriggerTab==0 );
90530   assert( pParse==sqlite3ParseToplevel(pParse) );
90531
90532   assert( v );   /* We failed long ago if this is not so */
90533   for(p = pParse->pAinc; p; p = p->pNext){
90534     pDb = &db->aDb[p->iDb];
90535     memId = p->regCtr;
90536     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90537     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
90538     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
90539     addr = sqlite3VdbeCurrentAddr(v);
90540     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
90541     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
90542     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
90543     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
90544     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
90545     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90546     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
90547     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
90548     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
90549     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
90550     sqlite3VdbeAddOp0(v, OP_Close);
90551   }
90552 }
90553
90554 /*
90555 ** Update the maximum rowid for an autoincrement calculation.
90556 **
90557 ** This routine should be called when the top of the stack holds a
90558 ** new rowid that is about to be inserted.  If that new rowid is
90559 ** larger than the maximum rowid in the memId memory cell, then the
90560 ** memory cell is updated.  The stack is unchanged.
90561 */
90562 static void autoIncStep(Parse *pParse, int memId, int regRowid){
90563   if( memId>0 ){
90564     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
90565   }
90566 }
90567
90568 /*
90569 ** This routine generates the code needed to write autoincrement
90570 ** maximum rowid values back into the sqlite_sequence register.
90571 ** Every statement that might do an INSERT into an autoincrement
90572 ** table (either directly or through triggers) needs to call this
90573 ** routine just before the "exit" code.
90574 */
90575 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
90576   AutoincInfo *p;
90577   Vdbe *v = pParse->pVdbe;
90578   sqlite3 *db = pParse->db;
90579
90580   assert( v );
90581   for(p = pParse->pAinc; p; p = p->pNext){
90582     Db *pDb = &db->aDb[p->iDb];
90583     int j1, j2, j3, j4, j5;
90584     int iRec;
90585     int memId = p->regCtr;
90586
90587     iRec = sqlite3GetTempReg(pParse);
90588     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90589     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
90590     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
90591     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
90592     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
90593     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
90594     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
90595     sqlite3VdbeJumpHere(v, j2);
90596     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
90597     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
90598     sqlite3VdbeJumpHere(v, j4);
90599     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90600     sqlite3VdbeJumpHere(v, j1);
90601     sqlite3VdbeJumpHere(v, j5);
90602     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
90603     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
90604     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90605     sqlite3VdbeAddOp0(v, OP_Close);
90606     sqlite3ReleaseTempReg(pParse, iRec);
90607   }
90608 }
90609 #else
90610 /*
90611 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
90612 ** above are all no-ops
90613 */
90614 # define autoIncBegin(A,B,C) (0)
90615 # define autoIncStep(A,B,C)
90616 #endif /* SQLITE_OMIT_AUTOINCREMENT */
90617
90618
90619 /*
90620 ** Generate code for a co-routine that will evaluate a subquery one
90621 ** row at a time.
90622 **
90623 ** The pSelect parameter is the subquery that the co-routine will evaluation.
90624 ** Information about the location of co-routine and the registers it will use
90625 ** is returned by filling in the pDest object.
90626 **
90627 ** Registers are allocated as follows:
90628 **
90629 **   pDest->iSDParm      The register holding the next entry-point of the
90630 **                       co-routine.  Run the co-routine to its next breakpoint
90631 **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
90632 **
90633 **   pDest->iSDParm+1    The register holding the "completed" flag for the
90634 **                       co-routine. This register is 0 if the previous Yield
90635 **                       generated a new result row, or 1 if the subquery
90636 **                       has completed.  If the Yield is called again
90637 **                       after this register becomes 1, then the VDBE will
90638 **                       halt with an SQLITE_INTERNAL error.
90639 **
90640 **   pDest->iSdst        First result register.
90641 **
90642 **   pDest->nSdst        Number of result registers.
90643 **
90644 ** This routine handles all of the register allocation and fills in the
90645 ** pDest structure appropriately.
90646 **
90647 ** Here is a schematic of the generated code assuming that X is the
90648 ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
90649 ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
90650 ** registers that hold the result set, reg[pDest->iSdst] through
90651 ** reg[pDest->iSdst+pDest->nSdst-1]:
90652 **
90653 **         X <- A
90654 **         EOF <- 0
90655 **         goto B
90656 **      A: setup for the SELECT
90657 **         loop rows in the SELECT
90658 **           load results into registers R..S
90659 **           yield X
90660 **         end loop
90661 **         cleanup after the SELECT
90662 **         EOF <- 1
90663 **         yield X
90664 **         halt-error
90665 **      B:
90666 **
90667 ** To use this subroutine, the caller generates code as follows:
90668 **
90669 **         [ Co-routine generated by this subroutine, shown above ]
90670 **      S: yield X
90671 **         if EOF goto E
90672 **         if skip this row, goto C
90673 **         if terminate loop, goto E
90674 **         deal with this row
90675 **      C: goto S
90676 **      E:
90677 */
90678 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
90679   int regYield;       /* Register holding co-routine entry-point */
90680   int regEof;         /* Register holding co-routine completion flag */
90681   int addrTop;        /* Top of the co-routine */
90682   int j1;             /* Jump instruction */
90683   int rc;             /* Result code */
90684   Vdbe *v;            /* VDBE under construction */
90685
90686   regYield = ++pParse->nMem;
90687   regEof = ++pParse->nMem;
90688   v = sqlite3GetVdbe(pParse);
90689   addrTop = sqlite3VdbeCurrentAddr(v);
90690   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
90691   VdbeComment((v, "Co-routine entry point"));
90692   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
90693   VdbeComment((v, "Co-routine completion flag"));
90694   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
90695   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90696   rc = sqlite3Select(pParse, pSelect, pDest);
90697   assert( pParse->nErr==0 || rc );
90698   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
90699   if( rc ) return rc;
90700   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
90701   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
90702   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
90703   VdbeComment((v, "End of coroutine"));
90704   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
90705   return rc;
90706 }
90707
90708
90709
90710 /* Forward declaration */
90711 static int xferOptimization(
90712   Parse *pParse,        /* Parser context */
90713   Table *pDest,         /* The table we are inserting into */
90714   Select *pSelect,      /* A SELECT statement to use as the data source */
90715   int onError,          /* How to handle constraint errors */
90716   int iDbDest           /* The database of pDest */
90717 );
90718
90719 /*
90720 ** This routine is call to handle SQL of the following forms:
90721 **
90722 **    insert into TABLE (IDLIST) values(EXPRLIST)
90723 **    insert into TABLE (IDLIST) select
90724 **
90725 ** The IDLIST following the table name is always optional.  If omitted,
90726 ** then a list of all columns for the table is substituted.  The IDLIST
90727 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
90728 **
90729 ** The pList parameter holds EXPRLIST in the first form of the INSERT
90730 ** statement above, and pSelect is NULL.  For the second form, pList is
90731 ** NULL and pSelect is a pointer to the select statement used to generate
90732 ** data for the insert.
90733 **
90734 ** The code generated follows one of four templates.  For a simple
90735 ** select with data coming from a VALUES clause, the code executes
90736 ** once straight down through.  Pseudo-code follows (we call this
90737 ** the "1st template"):
90738 **
90739 **         open write cursor to <table> and its indices
90740 **         puts VALUES clause expressions onto the stack
90741 **         write the resulting record into <table>
90742 **         cleanup
90743 **
90744 ** The three remaining templates assume the statement is of the form
90745 **
90746 **   INSERT INTO <table> SELECT ...
90747 **
90748 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
90749 ** in other words if the SELECT pulls all columns from a single table
90750 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
90751 ** if <table2> and <table1> are distinct tables but have identical
90752 ** schemas, including all the same indices, then a special optimization
90753 ** is invoked that copies raw records from <table2> over to <table1>.
90754 ** See the xferOptimization() function for the implementation of this
90755 ** template.  This is the 2nd template.
90756 **
90757 **         open a write cursor to <table>
90758 **         open read cursor on <table2>
90759 **         transfer all records in <table2> over to <table>
90760 **         close cursors
90761 **         foreach index on <table>
90762 **           open a write cursor on the <table> index
90763 **           open a read cursor on the corresponding <table2> index
90764 **           transfer all records from the read to the write cursors
90765 **           close cursors
90766 **         end foreach
90767 **
90768 ** The 3rd template is for when the second template does not apply
90769 ** and the SELECT clause does not read from <table> at any time.
90770 ** The generated code follows this template:
90771 **
90772 **         EOF <- 0
90773 **         X <- A
90774 **         goto B
90775 **      A: setup for the SELECT
90776 **         loop over the rows in the SELECT
90777 **           load values into registers R..R+n
90778 **           yield X
90779 **         end loop
90780 **         cleanup after the SELECT
90781 **         EOF <- 1
90782 **         yield X
90783 **         goto A
90784 **      B: open write cursor to <table> and its indices
90785 **      C: yield X
90786 **         if EOF goto D
90787 **         insert the select result into <table> from R..R+n
90788 **         goto C
90789 **      D: cleanup
90790 **
90791 ** The 4th template is used if the insert statement takes its
90792 ** values from a SELECT but the data is being inserted into a table
90793 ** that is also read as part of the SELECT.  In the third form,
90794 ** we have to use a intermediate table to store the results of
90795 ** the select.  The template is like this:
90796 **
90797 **         EOF <- 0
90798 **         X <- A
90799 **         goto B
90800 **      A: setup for the SELECT
90801 **         loop over the tables in the SELECT
90802 **           load value into register R..R+n
90803 **           yield X
90804 **         end loop
90805 **         cleanup after the SELECT
90806 **         EOF <- 1
90807 **         yield X
90808 **         halt-error
90809 **      B: open temp table
90810 **      L: yield X
90811 **         if EOF goto M
90812 **         insert row from R..R+n into temp table
90813 **         goto L
90814 **      M: open write cursor to <table> and its indices
90815 **         rewind temp table
90816 **      C: loop over rows of intermediate table
90817 **           transfer values form intermediate table into <table>
90818 **         end loop
90819 **      D: cleanup
90820 */
90821 SQLITE_PRIVATE void sqlite3Insert(
90822   Parse *pParse,        /* Parser context */
90823   SrcList *pTabList,    /* Name of table into which we are inserting */
90824   ExprList *pList,      /* List of values to be inserted */
90825   Select *pSelect,      /* A SELECT statement to use as the data source */
90826   IdList *pColumn,      /* Column names corresponding to IDLIST. */
90827   int onError           /* How to handle constraint errors */
90828 ){
90829   sqlite3 *db;          /* The main database structure */
90830   Table *pTab;          /* The table to insert into.  aka TABLE */
90831   char *zTab;           /* Name of the table into which we are inserting */
90832   const char *zDb;      /* Name of the database holding this table */
90833   int i, j, idx;        /* Loop counters */
90834   Vdbe *v;              /* Generate code into this virtual machine */
90835   Index *pIdx;          /* For looping over indices of the table */
90836   int nColumn;          /* Number of columns in the data */
90837   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
90838   int baseCur = 0;      /* VDBE Cursor number for pTab */
90839   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
90840   int endOfLoop;        /* Label for the end of the insertion loop */
90841   int useTempTable = 0; /* Store SELECT results in intermediate table */
90842   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
90843   int addrInsTop = 0;   /* Jump to label "D" */
90844   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
90845   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
90846   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
90847   int iDb;              /* Index of database holding TABLE */
90848   Db *pDb;              /* The database containing table being inserted into */
90849   int appendFlag = 0;   /* True if the insert is likely to be an append */
90850
90851   /* Register allocations */
90852   int regFromSelect = 0;/* Base register for data coming from SELECT */
90853   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
90854   int regRowCount = 0;  /* Memory cell used for the row counter */
90855   int regIns;           /* Block of regs holding rowid+data being inserted */
90856   int regRowid;         /* registers holding insert rowid */
90857   int regData;          /* register holding first column to insert */
90858   int regEof = 0;       /* Register recording end of SELECT data */
90859   int *aRegIdx = 0;     /* One register allocated to each index */
90860
90861 #ifndef SQLITE_OMIT_TRIGGER
90862   int isView;                 /* True if attempting to insert into a view */
90863   Trigger *pTrigger;          /* List of triggers on pTab, if required */
90864   int tmask;                  /* Mask of trigger times */
90865 #endif
90866
90867   db = pParse->db;
90868   memset(&dest, 0, sizeof(dest));
90869   if( pParse->nErr || db->mallocFailed ){
90870     goto insert_cleanup;
90871   }
90872
90873   /* Locate the table into which we will be inserting new information.
90874   */
90875   assert( pTabList->nSrc==1 );
90876   zTab = pTabList->a[0].zName;
90877   if( NEVER(zTab==0) ) goto insert_cleanup;
90878   pTab = sqlite3SrcListLookup(pParse, pTabList);
90879   if( pTab==0 ){
90880     goto insert_cleanup;
90881   }
90882   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90883   assert( iDb<db->nDb );
90884   pDb = &db->aDb[iDb];
90885   zDb = pDb->zName;
90886   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
90887     goto insert_cleanup;
90888   }
90889
90890   /* Figure out if we have any triggers and if the table being
90891   ** inserted into is a view
90892   */
90893 #ifndef SQLITE_OMIT_TRIGGER
90894   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
90895   isView = pTab->pSelect!=0;
90896 #else
90897 # define pTrigger 0
90898 # define tmask 0
90899 # define isView 0
90900 #endif
90901 #ifdef SQLITE_OMIT_VIEW
90902 # undef isView
90903 # define isView 0
90904 #endif
90905   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
90906
90907   /* If pTab is really a view, make sure it has been initialized.
90908   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
90909   ** module table).
90910   */
90911   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
90912     goto insert_cleanup;
90913   }
90914
90915   /* Ensure that:
90916   *  (a) the table is not read-only,
90917   *  (b) that if it is a view then ON INSERT triggers exist
90918   */
90919   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
90920     goto insert_cleanup;
90921   }
90922
90923   /* Allocate a VDBE
90924   */
90925   v = sqlite3GetVdbe(pParse);
90926   if( v==0 ) goto insert_cleanup;
90927   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
90928   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
90929
90930 #ifndef SQLITE_OMIT_XFER_OPT
90931   /* If the statement is of the form
90932   **
90933   **       INSERT INTO <table1> SELECT * FROM <table2>;
90934   **
90935   ** Then special optimizations can be applied that make the transfer
90936   ** very fast and which reduce fragmentation of indices.
90937   **
90938   ** This is the 2nd template.
90939   */
90940   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
90941     assert( !pTrigger );
90942     assert( pList==0 );
90943     goto insert_end;
90944   }
90945 #endif /* SQLITE_OMIT_XFER_OPT */
90946
90947   /* If this is an AUTOINCREMENT table, look up the sequence number in the
90948   ** sqlite_sequence table and store it in memory cell regAutoinc.
90949   */
90950   regAutoinc = autoIncBegin(pParse, iDb, pTab);
90951
90952   /* Figure out how many columns of data are supplied.  If the data
90953   ** is coming from a SELECT statement, then generate a co-routine that
90954   ** produces a single row of the SELECT on each invocation.  The
90955   ** co-routine is the common header to the 3rd and 4th templates.
90956   */
90957   if( pSelect ){
90958     /* Data is coming from a SELECT.  Generate a co-routine to run that
90959     ** SELECT. */
90960     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
90961     if( rc ) goto insert_cleanup;
90962
90963     regEof = dest.iSDParm + 1;
90964     regFromSelect = dest.iSdst;
90965     assert( pSelect->pEList );
90966     nColumn = pSelect->pEList->nExpr;
90967     assert( dest.nSdst==nColumn );
90968
90969     /* Set useTempTable to TRUE if the result of the SELECT statement
90970     ** should be written into a temporary table (template 4).  Set to
90971     ** FALSE if each* row of the SELECT can be written directly into
90972     ** the destination table (template 3).
90973     **
90974     ** A temp table must be used if the table being updated is also one
90975     ** of the tables being read by the SELECT statement.  Also use a
90976     ** temp table in the case of row triggers.
90977     */
90978     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
90979       useTempTable = 1;
90980     }
90981
90982     if( useTempTable ){
90983       /* Invoke the coroutine to extract information from the SELECT
90984       ** and add it to a transient table srcTab.  The code generated
90985       ** here is from the 4th template:
90986       **
90987       **      B: open temp table
90988       **      L: yield X
90989       **         if EOF goto M
90990       **         insert row from R..R+n into temp table
90991       **         goto L
90992       **      M: ...
90993       */
90994       int regRec;          /* Register to hold packed record */
90995       int regTempRowid;    /* Register to hold temp table ROWID */
90996       int addrTop;         /* Label "L" */
90997       int addrIf;          /* Address of jump to M */
90998
90999       srcTab = pParse->nTab++;
91000       regRec = sqlite3GetTempReg(pParse);
91001       regTempRowid = sqlite3GetTempReg(pParse);
91002       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
91003       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
91004       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
91005       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
91006       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
91007       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
91008       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
91009       sqlite3VdbeJumpHere(v, addrIf);
91010       sqlite3ReleaseTempReg(pParse, regRec);
91011       sqlite3ReleaseTempReg(pParse, regTempRowid);
91012     }
91013   }else{
91014     /* This is the case if the data for the INSERT is coming from a VALUES
91015     ** clause
91016     */
91017     NameContext sNC;
91018     memset(&sNC, 0, sizeof(sNC));
91019     sNC.pParse = pParse;
91020     srcTab = -1;
91021     assert( useTempTable==0 );
91022     nColumn = pList ? pList->nExpr : 0;
91023     for(i=0; i<nColumn; i++){
91024       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
91025         goto insert_cleanup;
91026       }
91027     }
91028   }
91029
91030   /* Make sure the number of columns in the source data matches the number
91031   ** of columns to be inserted into the table.
91032   */
91033   if( IsVirtual(pTab) ){
91034     for(i=0; i<pTab->nCol; i++){
91035       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
91036     }
91037   }
91038   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
91039     sqlite3ErrorMsg(pParse,
91040        "table %S has %d columns but %d values were supplied",
91041        pTabList, 0, pTab->nCol-nHidden, nColumn);
91042     goto insert_cleanup;
91043   }
91044   if( pColumn!=0 && nColumn!=pColumn->nId ){
91045     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
91046     goto insert_cleanup;
91047   }
91048
91049   /* If the INSERT statement included an IDLIST term, then make sure
91050   ** all elements of the IDLIST really are columns of the table and
91051   ** remember the column indices.
91052   **
91053   ** If the table has an INTEGER PRIMARY KEY column and that column
91054   ** is named in the IDLIST, then record in the keyColumn variable
91055   ** the index into IDLIST of the primary key column.  keyColumn is
91056   ** the index of the primary key as it appears in IDLIST, not as
91057   ** is appears in the original table.  (The index of the primary
91058   ** key in the original table is pTab->iPKey.)
91059   */
91060   if( pColumn ){
91061     for(i=0; i<pColumn->nId; i++){
91062       pColumn->a[i].idx = -1;
91063     }
91064     for(i=0; i<pColumn->nId; i++){
91065       for(j=0; j<pTab->nCol; j++){
91066         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
91067           pColumn->a[i].idx = j;
91068           if( j==pTab->iPKey ){
91069             keyColumn = i;
91070           }
91071           break;
91072         }
91073       }
91074       if( j>=pTab->nCol ){
91075         if( sqlite3IsRowid(pColumn->a[i].zName) ){
91076           keyColumn = i;
91077         }else{
91078           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
91079               pTabList, 0, pColumn->a[i].zName);
91080           pParse->checkSchema = 1;
91081           goto insert_cleanup;
91082         }
91083       }
91084     }
91085   }
91086
91087   /* If there is no IDLIST term but the table has an integer primary
91088   ** key, the set the keyColumn variable to the primary key column index
91089   ** in the original table definition.
91090   */
91091   if( pColumn==0 && nColumn>0 ){
91092     keyColumn = pTab->iPKey;
91093   }
91094
91095   /* Initialize the count of rows to be inserted
91096   */
91097   if( db->flags & SQLITE_CountRows ){
91098     regRowCount = ++pParse->nMem;
91099     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
91100   }
91101
91102   /* If this is not a view, open the table and and all indices */
91103   if( !isView ){
91104     int nIdx;
91105
91106     baseCur = pParse->nTab;
91107     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
91108     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
91109     if( aRegIdx==0 ){
91110       goto insert_cleanup;
91111     }
91112     for(i=0; i<nIdx; i++){
91113       aRegIdx[i] = ++pParse->nMem;
91114     }
91115   }
91116
91117   /* This is the top of the main insertion loop */
91118   if( useTempTable ){
91119     /* This block codes the top of loop only.  The complete loop is the
91120     ** following pseudocode (template 4):
91121     **
91122     **         rewind temp table
91123     **      C: loop over rows of intermediate table
91124     **           transfer values form intermediate table into <table>
91125     **         end loop
91126     **      D: ...
91127     */
91128     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
91129     addrCont = sqlite3VdbeCurrentAddr(v);
91130   }else if( pSelect ){
91131     /* This block codes the top of loop only.  The complete loop is the
91132     ** following pseudocode (template 3):
91133     **
91134     **      C: yield X
91135     **         if EOF goto D
91136     **         insert the select result into <table> from R..R+n
91137     **         goto C
91138     **      D: ...
91139     */
91140     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
91141     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
91142   }
91143
91144   /* Allocate registers for holding the rowid of the new row,
91145   ** the content of the new row, and the assemblied row record.
91146   */
91147   regRowid = regIns = pParse->nMem+1;
91148   pParse->nMem += pTab->nCol + 1;
91149   if( IsVirtual(pTab) ){
91150     regRowid++;
91151     pParse->nMem++;
91152   }
91153   regData = regRowid+1;
91154
91155   /* Run the BEFORE and INSTEAD OF triggers, if there are any
91156   */
91157   endOfLoop = sqlite3VdbeMakeLabel(v);
91158   if( tmask & TRIGGER_BEFORE ){
91159     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
91160
91161     /* build the NEW.* reference row.  Note that if there is an INTEGER
91162     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
91163     ** translated into a unique ID for the row.  But on a BEFORE trigger,
91164     ** we do not know what the unique ID will be (because the insert has
91165     ** not happened yet) so we substitute a rowid of -1
91166     */
91167     if( keyColumn<0 ){
91168       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
91169     }else{
91170       int j1;
91171       if( useTempTable ){
91172         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
91173       }else{
91174         assert( pSelect==0 );  /* Otherwise useTempTable is true */
91175         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
91176       }
91177       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
91178       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
91179       sqlite3VdbeJumpHere(v, j1);
91180       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
91181     }
91182
91183     /* Cannot have triggers on a virtual table. If it were possible,
91184     ** this block would have to account for hidden column.
91185     */
91186     assert( !IsVirtual(pTab) );
91187
91188     /* Create the new column data
91189     */
91190     for(i=0; i<pTab->nCol; i++){
91191       if( pColumn==0 ){
91192         j = i;
91193       }else{
91194         for(j=0; j<pColumn->nId; j++){
91195           if( pColumn->a[j].idx==i ) break;
91196         }
91197       }
91198       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
91199         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
91200       }else if( useTempTable ){
91201         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
91202       }else{
91203         assert( pSelect==0 ); /* Otherwise useTempTable is true */
91204         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
91205       }
91206     }
91207
91208     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
91209     ** do not attempt any conversions before assembling the record.
91210     ** If this is a real table, attempt conversions as required by the
91211     ** table column affinities.
91212     */
91213     if( !isView ){
91214       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
91215       sqlite3TableAffinityStr(v, pTab);
91216     }
91217
91218     /* Fire BEFORE or INSTEAD OF triggers */
91219     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
91220         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
91221
91222     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
91223   }
91224
91225   /* Push the record number for the new entry onto the stack.  The
91226   ** record number is a randomly generate integer created by NewRowid
91227   ** except when the table has an INTEGER PRIMARY KEY column, in which
91228   ** case the record number is the same as that column.
91229   */
91230   if( !isView ){
91231     if( IsVirtual(pTab) ){
91232       /* The row that the VUpdate opcode will delete: none */
91233       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
91234     }
91235     if( keyColumn>=0 ){
91236       if( useTempTable ){
91237         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
91238       }else if( pSelect ){
91239         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
91240       }else{
91241         VdbeOp *pOp;
91242         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
91243         pOp = sqlite3VdbeGetOp(v, -1);
91244         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
91245           appendFlag = 1;
91246           pOp->opcode = OP_NewRowid;
91247           pOp->p1 = baseCur;
91248           pOp->p2 = regRowid;
91249           pOp->p3 = regAutoinc;
91250         }
91251       }
91252       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
91253       ** to generate a unique primary key value.
91254       */
91255       if( !appendFlag ){
91256         int j1;
91257         if( !IsVirtual(pTab) ){
91258           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
91259           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91260           sqlite3VdbeJumpHere(v, j1);
91261         }else{
91262           j1 = sqlite3VdbeCurrentAddr(v);
91263           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
91264         }
91265         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
91266       }
91267     }else if( IsVirtual(pTab) ){
91268       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
91269     }else{
91270       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91271       appendFlag = 1;
91272     }
91273     autoIncStep(pParse, regAutoinc, regRowid);
91274
91275     /* Push onto the stack, data for all columns of the new entry, beginning
91276     ** with the first column.
91277     */
91278     nHidden = 0;
91279     for(i=0; i<pTab->nCol; i++){
91280       int iRegStore = regRowid+1+i;
91281       if( i==pTab->iPKey ){
91282         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
91283         ** Whenever this column is read, the record number will be substituted
91284         ** in its place.  So will fill this column with a NULL to avoid
91285         ** taking up data space with information that will never be used. */
91286         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
91287         continue;
91288       }
91289       if( pColumn==0 ){
91290         if( IsHiddenColumn(&pTab->aCol[i]) ){
91291           assert( IsVirtual(pTab) );
91292           j = -1;
91293           nHidden++;
91294         }else{
91295           j = i - nHidden;
91296         }
91297       }else{
91298         for(j=0; j<pColumn->nId; j++){
91299           if( pColumn->a[j].idx==i ) break;
91300         }
91301       }
91302       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
91303         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
91304       }else if( useTempTable ){
91305         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
91306       }else if( pSelect ){
91307         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
91308       }else{
91309         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
91310       }
91311     }
91312
91313     /* Generate code to check constraints and generate index keys and
91314     ** do the insertion.
91315     */
91316 #ifndef SQLITE_OMIT_VIRTUALTABLE
91317     if( IsVirtual(pTab) ){
91318       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
91319       sqlite3VtabMakeWritable(pParse, pTab);
91320       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
91321       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
91322       sqlite3MayAbort(pParse);
91323     }else
91324 #endif
91325     {
91326       int isReplace;    /* Set to true if constraints may cause a replace */
91327       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
91328           keyColumn>=0, 0, onError, endOfLoop, &isReplace
91329       );
91330       sqlite3FkCheck(pParse, pTab, 0, regIns);
91331       sqlite3CompleteInsertion(
91332           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
91333       );
91334     }
91335   }
91336
91337   /* Update the count of rows that are inserted
91338   */
91339   if( (db->flags & SQLITE_CountRows)!=0 ){
91340     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
91341   }
91342
91343   if( pTrigger ){
91344     /* Code AFTER triggers */
91345     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
91346         pTab, regData-2-pTab->nCol, onError, endOfLoop);
91347   }
91348
91349   /* The bottom of the main insertion loop, if the data source
91350   ** is a SELECT statement.
91351   */
91352   sqlite3VdbeResolveLabel(v, endOfLoop);
91353   if( useTempTable ){
91354     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
91355     sqlite3VdbeJumpHere(v, addrInsTop);
91356     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
91357   }else if( pSelect ){
91358     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
91359     sqlite3VdbeJumpHere(v, addrInsTop);
91360   }
91361
91362   if( !IsVirtual(pTab) && !isView ){
91363     /* Close all tables opened */
91364     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
91365     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
91366       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
91367     }
91368   }
91369
91370 insert_end:
91371   /* Update the sqlite_sequence table by storing the content of the
91372   ** maximum rowid counter values recorded while inserting into
91373   ** autoincrement tables.
91374   */
91375   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91376     sqlite3AutoincrementEnd(pParse);
91377   }
91378
91379   /*
91380   ** Return the number of rows inserted. If this routine is
91381   ** generating code because of a call to sqlite3NestedParse(), do not
91382   ** invoke the callback function.
91383   */
91384   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
91385     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91386     sqlite3VdbeSetNumCols(v, 1);
91387     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
91388   }
91389
91390 insert_cleanup:
91391   sqlite3SrcListDelete(db, pTabList);
91392   sqlite3ExprListDelete(db, pList);
91393   sqlite3SelectDelete(db, pSelect);
91394   sqlite3IdListDelete(db, pColumn);
91395   sqlite3DbFree(db, aRegIdx);
91396 }
91397
91398 /* Make sure "isView" and other macros defined above are undefined. Otherwise
91399 ** thely may interfere with compilation of other functions in this file
91400 ** (or in another file, if this file becomes part of the amalgamation).  */
91401 #ifdef isView
91402  #undef isView
91403 #endif
91404 #ifdef pTrigger
91405  #undef pTrigger
91406 #endif
91407 #ifdef tmask
91408  #undef tmask
91409 #endif
91410
91411
91412 /*
91413 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
91414 **
91415 ** The input is a range of consecutive registers as follows:
91416 **
91417 **    1.  The rowid of the row after the update.
91418 **
91419 **    2.  The data in the first column of the entry after the update.
91420 **
91421 **    i.  Data from middle columns...
91422 **
91423 **    N.  The data in the last column of the entry after the update.
91424 **
91425 ** The regRowid parameter is the index of the register containing (1).
91426 **
91427 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
91428 ** the address of a register containing the rowid before the update takes
91429 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
91430 ** is false, indicating an INSERT statement, then a non-zero rowidChng
91431 ** indicates that the rowid was explicitly specified as part of the
91432 ** INSERT statement. If rowidChng is false, it means that  the rowid is
91433 ** computed automatically in an insert or that the rowid value is not
91434 ** modified by an update.
91435 **
91436 ** The code generated by this routine store new index entries into
91437 ** registers identified by aRegIdx[].  No index entry is created for
91438 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
91439 ** the same as the order of indices on the linked list of indices
91440 ** attached to the table.
91441 **
91442 ** This routine also generates code to check constraints.  NOT NULL,
91443 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
91444 ** then the appropriate action is performed.  There are five possible
91445 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
91446 **
91447 **  Constraint type  Action       What Happens
91448 **  ---------------  ----------   ----------------------------------------
91449 **  any              ROLLBACK     The current transaction is rolled back and
91450 **                                sqlite3_exec() returns immediately with a
91451 **                                return code of SQLITE_CONSTRAINT.
91452 **
91453 **  any              ABORT        Back out changes from the current command
91454 **                                only (do not do a complete rollback) then
91455 **                                cause sqlite3_exec() to return immediately
91456 **                                with SQLITE_CONSTRAINT.
91457 **
91458 **  any              FAIL         Sqlite3_exec() returns immediately with a
91459 **                                return code of SQLITE_CONSTRAINT.  The
91460 **                                transaction is not rolled back and any
91461 **                                prior changes are retained.
91462 **
91463 **  any              IGNORE       The record number and data is popped from
91464 **                                the stack and there is an immediate jump
91465 **                                to label ignoreDest.
91466 **
91467 **  NOT NULL         REPLACE      The NULL value is replace by the default
91468 **                                value for that column.  If the default value
91469 **                                is NULL, the action is the same as ABORT.
91470 **
91471 **  UNIQUE           REPLACE      The other row that conflicts with the row
91472 **                                being inserted is removed.
91473 **
91474 **  CHECK            REPLACE      Illegal.  The results in an exception.
91475 **
91476 ** Which action to take is determined by the overrideError parameter.
91477 ** Or if overrideError==OE_Default, then the pParse->onError parameter
91478 ** is used.  Or if pParse->onError==OE_Default then the onError value
91479 ** for the constraint is used.
91480 **
91481 ** The calling routine must open a read/write cursor for pTab with
91482 ** cursor number "baseCur".  All indices of pTab must also have open
91483 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
91484 ** Except, if there is no possibility of a REPLACE action then
91485 ** cursors do not need to be open for indices where aRegIdx[i]==0.
91486 */
91487 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
91488   Parse *pParse,      /* The parser context */
91489   Table *pTab,        /* the table into which we are inserting */
91490   int baseCur,        /* Index of a read/write cursor pointing at pTab */
91491   int regRowid,       /* Index of the range of input registers */
91492   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91493   int rowidChng,      /* True if the rowid might collide with existing entry */
91494   int isUpdate,       /* True for UPDATE, False for INSERT */
91495   int overrideError,  /* Override onError to this if not OE_Default */
91496   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
91497   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
91498 ){
91499   int i;              /* loop counter */
91500   Vdbe *v;            /* VDBE under constrution */
91501   int nCol;           /* Number of columns */
91502   int onError;        /* Conflict resolution strategy */
91503   int j1;             /* Addresss of jump instruction */
91504   int j2 = 0, j3;     /* Addresses of jump instructions */
91505   int regData;        /* Register containing first data column */
91506   int iCur;           /* Table cursor number */
91507   Index *pIdx;         /* Pointer to one of the indices */
91508   sqlite3 *db;         /* Database connection */
91509   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
91510   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
91511
91512   db = pParse->db;
91513   v = sqlite3GetVdbe(pParse);
91514   assert( v!=0 );
91515   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91516   nCol = pTab->nCol;
91517   regData = regRowid + 1;
91518
91519   /* Test all NOT NULL constraints.
91520   */
91521   for(i=0; i<nCol; i++){
91522     if( i==pTab->iPKey ){
91523       continue;
91524     }
91525     onError = pTab->aCol[i].notNull;
91526     if( onError==OE_None ) continue;
91527     if( overrideError!=OE_Default ){
91528       onError = overrideError;
91529     }else if( onError==OE_Default ){
91530       onError = OE_Abort;
91531     }
91532     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
91533       onError = OE_Abort;
91534     }
91535     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91536         || onError==OE_Ignore || onError==OE_Replace );
91537     switch( onError ){
91538       case OE_Abort:
91539         sqlite3MayAbort(pParse);
91540       case OE_Rollback:
91541       case OE_Fail: {
91542         char *zMsg;
91543         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
91544                                   SQLITE_CONSTRAINT, onError, regData+i);
91545         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
91546                               pTab->zName, pTab->aCol[i].zName);
91547         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
91548         break;
91549       }
91550       case OE_Ignore: {
91551         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
91552         break;
91553       }
91554       default: {
91555         assert( onError==OE_Replace );
91556         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
91557         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
91558         sqlite3VdbeJumpHere(v, j1);
91559         break;
91560       }
91561     }
91562   }
91563
91564   /* Test all CHECK constraints
91565   */
91566 #ifndef SQLITE_OMIT_CHECK
91567   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
91568     ExprList *pCheck = pTab->pCheck;
91569     pParse->ckBase = regData;
91570     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
91571     for(i=0; i<pCheck->nExpr; i++){
91572       int allOk = sqlite3VdbeMakeLabel(v);
91573       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
91574       if( onError==OE_Ignore ){
91575         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91576       }else{
91577         char *zConsName = pCheck->a[i].zName;
91578         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
91579         if( zConsName ){
91580           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
91581         }else{
91582           zConsName = 0;
91583         }
91584         sqlite3HaltConstraint(pParse, onError, zConsName, P4_DYNAMIC);
91585       }
91586       sqlite3VdbeResolveLabel(v, allOk);
91587     }
91588   }
91589 #endif /* !defined(SQLITE_OMIT_CHECK) */
91590
91591   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
91592   ** of the new record does not previously exist.  Except, if this
91593   ** is an UPDATE and the primary key is not changing, that is OK.
91594   */
91595   if( rowidChng ){
91596     onError = pTab->keyConf;
91597     if( overrideError!=OE_Default ){
91598       onError = overrideError;
91599     }else if( onError==OE_Default ){
91600       onError = OE_Abort;
91601     }
91602
91603     if( isUpdate ){
91604       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
91605     }
91606     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
91607     switch( onError ){
91608       default: {
91609         onError = OE_Abort;
91610         /* Fall thru into the next case */
91611       }
91612       case OE_Rollback:
91613       case OE_Abort:
91614       case OE_Fail: {
91615         sqlite3HaltConstraint(
91616           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
91617         break;
91618       }
91619       case OE_Replace: {
91620         /* If there are DELETE triggers on this table and the
91621         ** recursive-triggers flag is set, call GenerateRowDelete() to
91622         ** remove the conflicting row from the table. This will fire
91623         ** the triggers and remove both the table and index b-tree entries.
91624         **
91625         ** Otherwise, if there are no triggers or the recursive-triggers
91626         ** flag is not set, but the table has one or more indexes, call
91627         ** GenerateRowIndexDelete(). This removes the index b-tree entries
91628         ** only. The table b-tree entry will be replaced by the new entry
91629         ** when it is inserted.
91630         **
91631         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
91632         ** also invoke MultiWrite() to indicate that this VDBE may require
91633         ** statement rollback (if the statement is aborted after the delete
91634         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
91635         ** but being more selective here allows statements like:
91636         **
91637         **   REPLACE INTO t(rowid) VALUES($newrowid)
91638         **
91639         ** to run without a statement journal if there are no indexes on the
91640         ** table.
91641         */
91642         Trigger *pTrigger = 0;
91643         if( db->flags&SQLITE_RecTriggers ){
91644           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91645         }
91646         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
91647           sqlite3MultiWrite(pParse);
91648           sqlite3GenerateRowDelete(
91649               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
91650           );
91651         }else if( pTab->pIndex ){
91652           sqlite3MultiWrite(pParse);
91653           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
91654         }
91655         seenReplace = 1;
91656         break;
91657       }
91658       case OE_Ignore: {
91659         assert( seenReplace==0 );
91660         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91661         break;
91662       }
91663     }
91664     sqlite3VdbeJumpHere(v, j3);
91665     if( isUpdate ){
91666       sqlite3VdbeJumpHere(v, j2);
91667     }
91668   }
91669
91670   /* Test all UNIQUE constraints by creating entries for each UNIQUE
91671   ** index and making sure that duplicate entries do not already exist.
91672   ** Add the new records to the indices as we go.
91673   */
91674   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
91675     int regIdx;
91676     int regR;
91677
91678     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
91679
91680     /* Create a key for accessing the index entry */
91681     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
91682     for(i=0; i<pIdx->nColumn; i++){
91683       int idx = pIdx->aiColumn[i];
91684       if( idx==pTab->iPKey ){
91685         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91686       }else{
91687         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
91688       }
91689     }
91690     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91691     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
91692     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
91693     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
91694
91695     /* Find out what action to take in case there is an indexing conflict */
91696     onError = pIdx->onError;
91697     if( onError==OE_None ){
91698       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91699       continue;  /* pIdx is not a UNIQUE index */
91700     }
91701     if( overrideError!=OE_Default ){
91702       onError = overrideError;
91703     }else if( onError==OE_Default ){
91704       onError = OE_Abort;
91705     }
91706     if( seenReplace ){
91707       if( onError==OE_Ignore ) onError = OE_Replace;
91708       else if( onError==OE_Fail ) onError = OE_Abort;
91709     }
91710
91711     /* Check to see if the new index entry will be unique */
91712     regR = sqlite3GetTempReg(pParse);
91713     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
91714     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
91715                            regR, SQLITE_INT_TO_PTR(regIdx),
91716                            P4_INT32);
91717     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91718
91719     /* Generate code that executes if the new index entry is not unique */
91720     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91721         || onError==OE_Ignore || onError==OE_Replace );
91722     switch( onError ){
91723       case OE_Rollback:
91724       case OE_Abort:
91725       case OE_Fail: {
91726         int j;
91727         StrAccum errMsg;
91728         const char *zSep;
91729         char *zErr;
91730
91731         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
91732         errMsg.db = db;
91733         zSep = pIdx->nColumn>1 ? "columns " : "column ";
91734         for(j=0; j<pIdx->nColumn; j++){
91735           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
91736           sqlite3StrAccumAppend(&errMsg, zSep, -1);
91737           zSep = ", ";
91738           sqlite3StrAccumAppend(&errMsg, zCol, -1);
91739         }
91740         sqlite3StrAccumAppend(&errMsg,
91741             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
91742         zErr = sqlite3StrAccumFinish(&errMsg);
91743         sqlite3HaltConstraint(pParse, onError, zErr, 0);
91744         sqlite3DbFree(errMsg.db, zErr);
91745         break;
91746       }
91747       case OE_Ignore: {
91748         assert( seenReplace==0 );
91749         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91750         break;
91751       }
91752       default: {
91753         Trigger *pTrigger = 0;
91754         assert( onError==OE_Replace );
91755         sqlite3MultiWrite(pParse);
91756         if( db->flags&SQLITE_RecTriggers ){
91757           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91758         }
91759         sqlite3GenerateRowDelete(
91760             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
91761         );
91762         seenReplace = 1;
91763         break;
91764       }
91765     }
91766     sqlite3VdbeJumpHere(v, j3);
91767     sqlite3ReleaseTempReg(pParse, regR);
91768   }
91769
91770   if( pbMayReplace ){
91771     *pbMayReplace = seenReplace;
91772   }
91773 }
91774
91775 /*
91776 ** This routine generates code to finish the INSERT or UPDATE operation
91777 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
91778 ** A consecutive range of registers starting at regRowid contains the
91779 ** rowid and the content to be inserted.
91780 **
91781 ** The arguments to this routine should be the same as the first six
91782 ** arguments to sqlite3GenerateConstraintChecks.
91783 */
91784 SQLITE_PRIVATE void sqlite3CompleteInsertion(
91785   Parse *pParse,      /* The parser context */
91786   Table *pTab,        /* the table into which we are inserting */
91787   int baseCur,        /* Index of a read/write cursor pointing at pTab */
91788   int regRowid,       /* Range of content */
91789   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91790   int isUpdate,       /* True for UPDATE, False for INSERT */
91791   int appendBias,     /* True if this is likely to be an append */
91792   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
91793 ){
91794   int i;
91795   Vdbe *v;
91796   int nIdx;
91797   Index *pIdx;
91798   u8 pik_flags;
91799   int regData;
91800   int regRec;
91801
91802   v = sqlite3GetVdbe(pParse);
91803   assert( v!=0 );
91804   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91805   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
91806   for(i=nIdx-1; i>=0; i--){
91807     if( aRegIdx[i]==0 ) continue;
91808     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
91809     if( useSeekResult ){
91810       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91811     }
91812   }
91813   regData = regRowid + 1;
91814   regRec = sqlite3GetTempReg(pParse);
91815   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
91816   sqlite3TableAffinityStr(v, pTab);
91817   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
91818   if( pParse->nested ){
91819     pik_flags = 0;
91820   }else{
91821     pik_flags = OPFLAG_NCHANGE;
91822     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
91823   }
91824   if( appendBias ){
91825     pik_flags |= OPFLAG_APPEND;
91826   }
91827   if( useSeekResult ){
91828     pik_flags |= OPFLAG_USESEEKRESULT;
91829   }
91830   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
91831   if( !pParse->nested ){
91832     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
91833   }
91834   sqlite3VdbeChangeP5(v, pik_flags);
91835 }
91836
91837 /*
91838 ** Generate code that will open cursors for a table and for all
91839 ** indices of that table.  The "baseCur" parameter is the cursor number used
91840 ** for the table.  Indices are opened on subsequent cursors.
91841 **
91842 ** Return the number of indices on the table.
91843 */
91844 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
91845   Parse *pParse,   /* Parsing context */
91846   Table *pTab,     /* Table to be opened */
91847   int baseCur,     /* Cursor number assigned to the table */
91848   int op           /* OP_OpenRead or OP_OpenWrite */
91849 ){
91850   int i;
91851   int iDb;
91852   Index *pIdx;
91853   Vdbe *v;
91854
91855   if( IsVirtual(pTab) ) return 0;
91856   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91857   v = sqlite3GetVdbe(pParse);
91858   assert( v!=0 );
91859   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
91860   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91861     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91862     assert( pIdx->pSchema==pTab->pSchema );
91863     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
91864                       (char*)pKey, P4_KEYINFO_HANDOFF);
91865     VdbeComment((v, "%s", pIdx->zName));
91866   }
91867   if( pParse->nTab<baseCur+i ){
91868     pParse->nTab = baseCur+i;
91869   }
91870   return i-1;
91871 }
91872
91873
91874 #ifdef SQLITE_TEST
91875 /*
91876 ** The following global variable is incremented whenever the
91877 ** transfer optimization is used.  This is used for testing
91878 ** purposes only - to make sure the transfer optimization really
91879 ** is happening when it is suppose to.
91880 */
91881 SQLITE_API int sqlite3_xferopt_count;
91882 #endif /* SQLITE_TEST */
91883
91884
91885 #ifndef SQLITE_OMIT_XFER_OPT
91886 /*
91887 ** Check to collation names to see if they are compatible.
91888 */
91889 static int xferCompatibleCollation(const char *z1, const char *z2){
91890   if( z1==0 ){
91891     return z2==0;
91892   }
91893   if( z2==0 ){
91894     return 0;
91895   }
91896   return sqlite3StrICmp(z1, z2)==0;
91897 }
91898
91899
91900 /*
91901 ** Check to see if index pSrc is compatible as a source of data
91902 ** for index pDest in an insert transfer optimization.  The rules
91903 ** for a compatible index:
91904 **
91905 **    *   The index is over the same set of columns
91906 **    *   The same DESC and ASC markings occurs on all columns
91907 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
91908 **    *   The same collating sequence on each column
91909 */
91910 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
91911   int i;
91912   assert( pDest && pSrc );
91913   assert( pDest->pTable!=pSrc->pTable );
91914   if( pDest->nColumn!=pSrc->nColumn ){
91915     return 0;   /* Different number of columns */
91916   }
91917   if( pDest->onError!=pSrc->onError ){
91918     return 0;   /* Different conflict resolution strategies */
91919   }
91920   for(i=0; i<pSrc->nColumn; i++){
91921     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
91922       return 0;   /* Different columns indexed */
91923     }
91924     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
91925       return 0;   /* Different sort orders */
91926     }
91927     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
91928       return 0;   /* Different collating sequences */
91929     }
91930   }
91931
91932   /* If no test above fails then the indices must be compatible */
91933   return 1;
91934 }
91935
91936 /*
91937 ** Attempt the transfer optimization on INSERTs of the form
91938 **
91939 **     INSERT INTO tab1 SELECT * FROM tab2;
91940 **
91941 ** The xfer optimization transfers raw records from tab2 over to tab1.
91942 ** Columns are not decoded and reassemblied, which greatly improves
91943 ** performance.  Raw index records are transferred in the same way.
91944 **
91945 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
91946 ** There are lots of rules for determining compatibility - see comments
91947 ** embedded in the code for details.
91948 **
91949 ** This routine returns TRUE if the optimization is guaranteed to be used.
91950 ** Sometimes the xfer optimization will only work if the destination table
91951 ** is empty - a factor that can only be determined at run-time.  In that
91952 ** case, this routine generates code for the xfer optimization but also
91953 ** does a test to see if the destination table is empty and jumps over the
91954 ** xfer optimization code if the test fails.  In that case, this routine
91955 ** returns FALSE so that the caller will know to go ahead and generate
91956 ** an unoptimized transfer.  This routine also returns FALSE if there
91957 ** is no chance that the xfer optimization can be applied.
91958 **
91959 ** This optimization is particularly useful at making VACUUM run faster.
91960 */
91961 static int xferOptimization(
91962   Parse *pParse,        /* Parser context */
91963   Table *pDest,         /* The table we are inserting into */
91964   Select *pSelect,      /* A SELECT statement to use as the data source */
91965   int onError,          /* How to handle constraint errors */
91966   int iDbDest           /* The database of pDest */
91967 ){
91968   ExprList *pEList;                /* The result set of the SELECT */
91969   Table *pSrc;                     /* The table in the FROM clause of SELECT */
91970   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
91971   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
91972   int i;                           /* Loop counter */
91973   int iDbSrc;                      /* The database of pSrc */
91974   int iSrc, iDest;                 /* Cursors from source and destination */
91975   int addr1, addr2;                /* Loop addresses */
91976   int emptyDestTest;               /* Address of test for empty pDest */
91977   int emptySrcTest;                /* Address of test for empty pSrc */
91978   Vdbe *v;                         /* The VDBE we are building */
91979   KeyInfo *pKey;                   /* Key information for an index */
91980   int regAutoinc;                  /* Memory register used by AUTOINC */
91981   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
91982   int regData, regRowid;           /* Registers holding data and rowid */
91983
91984   if( pSelect==0 ){
91985     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
91986   }
91987   if( sqlite3TriggerList(pParse, pDest) ){
91988     return 0;   /* tab1 must not have triggers */
91989   }
91990 #ifndef SQLITE_OMIT_VIRTUALTABLE
91991   if( pDest->tabFlags & TF_Virtual ){
91992     return 0;   /* tab1 must not be a virtual table */
91993   }
91994 #endif
91995   if( onError==OE_Default ){
91996     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
91997     if( onError==OE_Default ) onError = OE_Abort;
91998   }
91999   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
92000   if( pSelect->pSrc->nSrc!=1 ){
92001     return 0;   /* FROM clause must have exactly one term */
92002   }
92003   if( pSelect->pSrc->a[0].pSelect ){
92004     return 0;   /* FROM clause cannot contain a subquery */
92005   }
92006   if( pSelect->pWhere ){
92007     return 0;   /* SELECT may not have a WHERE clause */
92008   }
92009   if( pSelect->pOrderBy ){
92010     return 0;   /* SELECT may not have an ORDER BY clause */
92011   }
92012   /* Do not need to test for a HAVING clause.  If HAVING is present but
92013   ** there is no ORDER BY, we will get an error. */
92014   if( pSelect->pGroupBy ){
92015     return 0;   /* SELECT may not have a GROUP BY clause */
92016   }
92017   if( pSelect->pLimit ){
92018     return 0;   /* SELECT may not have a LIMIT clause */
92019   }
92020   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
92021   if( pSelect->pPrior ){
92022     return 0;   /* SELECT may not be a compound query */
92023   }
92024   if( pSelect->selFlags & SF_Distinct ){
92025     return 0;   /* SELECT may not be DISTINCT */
92026   }
92027   pEList = pSelect->pEList;
92028   assert( pEList!=0 );
92029   if( pEList->nExpr!=1 ){
92030     return 0;   /* The result set must have exactly one column */
92031   }
92032   assert( pEList->a[0].pExpr );
92033   if( pEList->a[0].pExpr->op!=TK_ALL ){
92034     return 0;   /* The result set must be the special operator "*" */
92035   }
92036
92037   /* At this point we have established that the statement is of the
92038   ** correct syntactic form to participate in this optimization.  Now
92039   ** we have to check the semantics.
92040   */
92041   pItem = pSelect->pSrc->a;
92042   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
92043   if( pSrc==0 ){
92044     return 0;   /* FROM clause does not contain a real table */
92045   }
92046   if( pSrc==pDest ){
92047     return 0;   /* tab1 and tab2 may not be the same table */
92048   }
92049 #ifndef SQLITE_OMIT_VIRTUALTABLE
92050   if( pSrc->tabFlags & TF_Virtual ){
92051     return 0;   /* tab2 must not be a virtual table */
92052   }
92053 #endif
92054   if( pSrc->pSelect ){
92055     return 0;   /* tab2 may not be a view */
92056   }
92057   if( pDest->nCol!=pSrc->nCol ){
92058     return 0;   /* Number of columns must be the same in tab1 and tab2 */
92059   }
92060   if( pDest->iPKey!=pSrc->iPKey ){
92061     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
92062   }
92063   for(i=0; i<pDest->nCol; i++){
92064     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
92065       return 0;    /* Affinity must be the same on all columns */
92066     }
92067     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
92068       return 0;    /* Collating sequence must be the same on all columns */
92069     }
92070     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
92071       return 0;    /* tab2 must be NOT NULL if tab1 is */
92072     }
92073   }
92074   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
92075     if( pDestIdx->onError!=OE_None ){
92076       destHasUniqueIdx = 1;
92077     }
92078     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
92079       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
92080     }
92081     if( pSrcIdx==0 ){
92082       return 0;    /* pDestIdx has no corresponding index in pSrc */
92083     }
92084   }
92085 #ifndef SQLITE_OMIT_CHECK
92086   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
92087     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
92088   }
92089 #endif
92090 #ifndef SQLITE_OMIT_FOREIGN_KEY
92091   /* Disallow the transfer optimization if the destination table constains
92092   ** any foreign key constraints.  This is more restrictive than necessary.
92093   ** But the main beneficiary of the transfer optimization is the VACUUM
92094   ** command, and the VACUUM command disables foreign key constraints.  So
92095   ** the extra complication to make this rule less restrictive is probably
92096   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
92097   */
92098   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
92099     return 0;
92100   }
92101 #endif
92102   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
92103     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
92104   }
92105
92106   /* If we get this far, it means that the xfer optimization is at
92107   ** least a possibility, though it might only work if the destination
92108   ** table (tab1) is initially empty.
92109   */
92110 #ifdef SQLITE_TEST
92111   sqlite3_xferopt_count++;
92112 #endif
92113   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
92114   v = sqlite3GetVdbe(pParse);
92115   sqlite3CodeVerifySchema(pParse, iDbSrc);
92116   iSrc = pParse->nTab++;
92117   iDest = pParse->nTab++;
92118   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
92119   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
92120   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
92121    || destHasUniqueIdx                              /* (2) */
92122    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
92123   ){
92124     /* In some circumstances, we are able to run the xfer optimization
92125     ** only if the destination table is initially empty.  This code makes
92126     ** that determination.  Conditions under which the destination must
92127     ** be empty:
92128     **
92129     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
92130     **     (If the destination is not initially empty, the rowid fields
92131     **     of index entries might need to change.)
92132     **
92133     ** (2) The destination has a unique index.  (The xfer optimization
92134     **     is unable to test uniqueness.)
92135     **
92136     ** (3) onError is something other than OE_Abort and OE_Rollback.
92137     */
92138     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
92139     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
92140     sqlite3VdbeJumpHere(v, addr1);
92141   }else{
92142     emptyDestTest = 0;
92143   }
92144   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
92145   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
92146   regData = sqlite3GetTempReg(pParse);
92147   regRowid = sqlite3GetTempReg(pParse);
92148   if( pDest->iPKey>=0 ){
92149     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
92150     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
92151     sqlite3HaltConstraint(
92152         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
92153     sqlite3VdbeJumpHere(v, addr2);
92154     autoIncStep(pParse, regAutoinc, regRowid);
92155   }else if( pDest->pIndex==0 ){
92156     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
92157   }else{
92158     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
92159     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
92160   }
92161   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
92162   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
92163   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
92164   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
92165   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
92166   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
92167     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
92168       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
92169     }
92170     assert( pSrcIdx );
92171     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
92172     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92173     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
92174     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
92175                       (char*)pKey, P4_KEYINFO_HANDOFF);
92176     VdbeComment((v, "%s", pSrcIdx->zName));
92177     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
92178     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
92179                       (char*)pKey, P4_KEYINFO_HANDOFF);
92180     VdbeComment((v, "%s", pDestIdx->zName));
92181     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
92182     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
92183     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
92184     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
92185     sqlite3VdbeJumpHere(v, addr1);
92186   }
92187   sqlite3VdbeJumpHere(v, emptySrcTest);
92188   sqlite3ReleaseTempReg(pParse, regRowid);
92189   sqlite3ReleaseTempReg(pParse, regData);
92190   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
92191   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92192   if( emptyDestTest ){
92193     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
92194     sqlite3VdbeJumpHere(v, emptyDestTest);
92195     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92196     return 0;
92197   }else{
92198     return 1;
92199   }
92200 }
92201 #endif /* SQLITE_OMIT_XFER_OPT */
92202
92203 /************** End of insert.c **********************************************/
92204 /************** Begin file legacy.c ******************************************/
92205 /*
92206 ** 2001 September 15
92207 **
92208 ** The author disclaims copyright to this source code.  In place of
92209 ** a legal notice, here is a blessing:
92210 **
92211 **    May you do good and not evil.
92212 **    May you find forgiveness for yourself and forgive others.
92213 **    May you share freely, never taking more than you give.
92214 **
92215 *************************************************************************
92216 ** Main file for the SQLite library.  The routines in this file
92217 ** implement the programmer interface to the library.  Routines in
92218 ** other files are for internal use by SQLite and should not be
92219 ** accessed by users of the library.
92220 */
92221
92222
92223 /*
92224 ** Execute SQL code.  Return one of the SQLITE_ success/failure
92225 ** codes.  Also write an error message into memory obtained from
92226 ** malloc() and make *pzErrMsg point to that message.
92227 **
92228 ** If the SQL is a query, then for each row in the query result
92229 ** the xCallback() function is called.  pArg becomes the first
92230 ** argument to xCallback().  If xCallback=NULL then no callback
92231 ** is invoked, even for queries.
92232 */
92233 SQLITE_API int sqlite3_exec(
92234   sqlite3 *db,                /* The database on which the SQL executes */
92235   const char *zSql,           /* The SQL to be executed */
92236   sqlite3_callback xCallback, /* Invoke this callback routine */
92237   void *pArg,                 /* First argument to xCallback() */
92238   char **pzErrMsg             /* Write error messages here */
92239 ){
92240   int rc = SQLITE_OK;         /* Return code */
92241   const char *zLeftover;      /* Tail of unprocessed SQL */
92242   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
92243   char **azCols = 0;          /* Names of result columns */
92244   int nRetry = 0;             /* Number of retry attempts */
92245   int callbackIsInit;         /* True if callback data is initialized */
92246
92247   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
92248   if( zSql==0 ) zSql = "";
92249
92250   sqlite3_mutex_enter(db->mutex);
92251   sqlite3Error(db, SQLITE_OK, 0);
92252   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
92253     int nCol;
92254     char **azVals = 0;
92255
92256     pStmt = 0;
92257     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
92258     assert( rc==SQLITE_OK || pStmt==0 );
92259     if( rc!=SQLITE_OK ){
92260       continue;
92261     }
92262     if( !pStmt ){
92263       /* this happens for a comment or white-space */
92264       zSql = zLeftover;
92265       continue;
92266     }
92267
92268     callbackIsInit = 0;
92269     nCol = sqlite3_column_count(pStmt);
92270
92271     while( 1 ){
92272       int i;
92273       rc = sqlite3_step(pStmt);
92274
92275       /* Invoke the callback function if required */
92276       if( xCallback && (SQLITE_ROW==rc ||
92277           (SQLITE_DONE==rc && !callbackIsInit
92278                            && db->flags&SQLITE_NullCallback)) ){
92279         if( !callbackIsInit ){
92280           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
92281           if( azCols==0 ){
92282             goto exec_out;
92283           }
92284           for(i=0; i<nCol; i++){
92285             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
92286             /* sqlite3VdbeSetColName() installs column names as UTF8
92287             ** strings so there is no way for sqlite3_column_name() to fail. */
92288             assert( azCols[i]!=0 );
92289           }
92290           callbackIsInit = 1;
92291         }
92292         if( rc==SQLITE_ROW ){
92293           azVals = &azCols[nCol];
92294           for(i=0; i<nCol; i++){
92295             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
92296             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
92297               db->mallocFailed = 1;
92298               goto exec_out;
92299             }
92300           }
92301         }
92302         if( xCallback(pArg, nCol, azVals, azCols) ){
92303           rc = SQLITE_ABORT;
92304           sqlite3VdbeFinalize((Vdbe *)pStmt);
92305           pStmt = 0;
92306           sqlite3Error(db, SQLITE_ABORT, 0);
92307           goto exec_out;
92308         }
92309       }
92310
92311       if( rc!=SQLITE_ROW ){
92312         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
92313         pStmt = 0;
92314         if( rc!=SQLITE_SCHEMA ){
92315           nRetry = 0;
92316           zSql = zLeftover;
92317           while( sqlite3Isspace(zSql[0]) ) zSql++;
92318         }
92319         break;
92320       }
92321     }
92322
92323     sqlite3DbFree(db, azCols);
92324     azCols = 0;
92325   }
92326
92327 exec_out:
92328   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
92329   sqlite3DbFree(db, azCols);
92330
92331   rc = sqlite3ApiExit(db, rc);
92332   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
92333     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
92334     *pzErrMsg = sqlite3Malloc(nErrMsg);
92335     if( *pzErrMsg ){
92336       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
92337     }else{
92338       rc = SQLITE_NOMEM;
92339       sqlite3Error(db, SQLITE_NOMEM, 0);
92340     }
92341   }else if( pzErrMsg ){
92342     *pzErrMsg = 0;
92343   }
92344
92345   assert( (rc&db->errMask)==rc );
92346   sqlite3_mutex_leave(db->mutex);
92347   return rc;
92348 }
92349
92350 /************** End of legacy.c **********************************************/
92351 /************** Begin file loadext.c *****************************************/
92352 /*
92353 ** 2006 June 7
92354 **
92355 ** The author disclaims copyright to this source code.  In place of
92356 ** a legal notice, here is a blessing:
92357 **
92358 **    May you do good and not evil.
92359 **    May you find forgiveness for yourself and forgive others.
92360 **    May you share freely, never taking more than you give.
92361 **
92362 *************************************************************************
92363 ** This file contains code used to dynamically load extensions into
92364 ** the SQLite library.
92365 */
92366
92367 #ifndef SQLITE_CORE
92368   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
92369 #endif
92370 /************** Include sqlite3ext.h in the middle of loadext.c **************/
92371 /************** Begin file sqlite3ext.h **************************************/
92372 /*
92373 ** 2006 June 7
92374 **
92375 ** The author disclaims copyright to this source code.  In place of
92376 ** a legal notice, here is a blessing:
92377 **
92378 **    May you do good and not evil.
92379 **    May you find forgiveness for yourself and forgive others.
92380 **    May you share freely, never taking more than you give.
92381 **
92382 *************************************************************************
92383 ** This header file defines the SQLite interface for use by
92384 ** shared libraries that want to be imported as extensions into
92385 ** an SQLite instance.  Shared libraries that intend to be loaded
92386 ** as extensions by SQLite should #include this file instead of
92387 ** sqlite3.h.
92388 */
92389 #ifndef _SQLITE3EXT_H_
92390 #define _SQLITE3EXT_H_
92391
92392 typedef struct sqlite3_api_routines sqlite3_api_routines;
92393
92394 /*
92395 ** The following structure holds pointers to all of the SQLite API
92396 ** routines.
92397 **
92398 ** WARNING:  In order to maintain backwards compatibility, add new
92399 ** interfaces to the end of this structure only.  If you insert new
92400 ** interfaces in the middle of this structure, then older different
92401 ** versions of SQLite will not be able to load each others' shared
92402 ** libraries!
92403 */
92404 struct sqlite3_api_routines {
92405   void * (*aggregate_context)(sqlite3_context*,int nBytes);
92406   int  (*aggregate_count)(sqlite3_context*);
92407   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
92408   int  (*bind_double)(sqlite3_stmt*,int,double);
92409   int  (*bind_int)(sqlite3_stmt*,int,int);
92410   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
92411   int  (*bind_null)(sqlite3_stmt*,int);
92412   int  (*bind_parameter_count)(sqlite3_stmt*);
92413   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
92414   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
92415   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
92416   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
92417   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
92418   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
92419   int  (*busy_timeout)(sqlite3*,int ms);
92420   int  (*changes)(sqlite3*);
92421   int  (*close)(sqlite3*);
92422   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
92423                            int eTextRep,const char*));
92424   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
92425                              int eTextRep,const void*));
92426   const void * (*column_blob)(sqlite3_stmt*,int iCol);
92427   int  (*column_bytes)(sqlite3_stmt*,int iCol);
92428   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
92429   int  (*column_count)(sqlite3_stmt*pStmt);
92430   const char * (*column_database_name)(sqlite3_stmt*,int);
92431   const void * (*column_database_name16)(sqlite3_stmt*,int);
92432   const char * (*column_decltype)(sqlite3_stmt*,int i);
92433   const void * (*column_decltype16)(sqlite3_stmt*,int);
92434   double  (*column_double)(sqlite3_stmt*,int iCol);
92435   int  (*column_int)(sqlite3_stmt*,int iCol);
92436   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
92437   const char * (*column_name)(sqlite3_stmt*,int);
92438   const void * (*column_name16)(sqlite3_stmt*,int);
92439   const char * (*column_origin_name)(sqlite3_stmt*,int);
92440   const void * (*column_origin_name16)(sqlite3_stmt*,int);
92441   const char * (*column_table_name)(sqlite3_stmt*,int);
92442   const void * (*column_table_name16)(sqlite3_stmt*,int);
92443   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
92444   const void * (*column_text16)(sqlite3_stmt*,int iCol);
92445   int  (*column_type)(sqlite3_stmt*,int iCol);
92446   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
92447   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
92448   int  (*complete)(const char*sql);
92449   int  (*complete16)(const void*sql);
92450   int  (*create_collation)(sqlite3*,const char*,int,void*,
92451                            int(*)(void*,int,const void*,int,const void*));
92452   int  (*create_collation16)(sqlite3*,const void*,int,void*,
92453                              int(*)(void*,int,const void*,int,const void*));
92454   int  (*create_function)(sqlite3*,const char*,int,int,void*,
92455                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92456                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92457                           void (*xFinal)(sqlite3_context*));
92458   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
92459                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92460                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92461                             void (*xFinal)(sqlite3_context*));
92462   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
92463   int  (*data_count)(sqlite3_stmt*pStmt);
92464   sqlite3 * (*db_handle)(sqlite3_stmt*);
92465   int (*declare_vtab)(sqlite3*,const char*);
92466   int  (*enable_shared_cache)(int);
92467   int  (*errcode)(sqlite3*db);
92468   const char * (*errmsg)(sqlite3*);
92469   const void * (*errmsg16)(sqlite3*);
92470   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
92471   int  (*expired)(sqlite3_stmt*);
92472   int  (*finalize)(sqlite3_stmt*pStmt);
92473   void  (*free)(void*);
92474   void  (*free_table)(char**result);
92475   int  (*get_autocommit)(sqlite3*);
92476   void * (*get_auxdata)(sqlite3_context*,int);
92477   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
92478   int  (*global_recover)(void);
92479   void  (*interruptx)(sqlite3*);
92480   sqlite_int64  (*last_insert_rowid)(sqlite3*);
92481   const char * (*libversion)(void);
92482   int  (*libversion_number)(void);
92483   void *(*malloc)(int);
92484   char * (*mprintf)(const char*,...);
92485   int  (*open)(const char*,sqlite3**);
92486   int  (*open16)(const void*,sqlite3**);
92487   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92488   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92489   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
92490   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
92491   void *(*realloc)(void*,int);
92492   int  (*reset)(sqlite3_stmt*pStmt);
92493   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
92494   void  (*result_double)(sqlite3_context*,double);
92495   void  (*result_error)(sqlite3_context*,const char*,int);
92496   void  (*result_error16)(sqlite3_context*,const void*,int);
92497   void  (*result_int)(sqlite3_context*,int);
92498   void  (*result_int64)(sqlite3_context*,sqlite_int64);
92499   void  (*result_null)(sqlite3_context*);
92500   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
92501   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
92502   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
92503   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
92504   void  (*result_value)(sqlite3_context*,sqlite3_value*);
92505   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
92506   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
92507                          const char*,const char*),void*);
92508   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
92509   char * (*snprintf)(int,char*,const char*,...);
92510   int  (*step)(sqlite3_stmt*);
92511   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
92512                                 char const**,char const**,int*,int*,int*);
92513   void  (*thread_cleanup)(void);
92514   int  (*total_changes)(sqlite3*);
92515   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
92516   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
92517   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
92518                                          sqlite_int64),void*);
92519   void * (*user_data)(sqlite3_context*);
92520   const void * (*value_blob)(sqlite3_value*);
92521   int  (*value_bytes)(sqlite3_value*);
92522   int  (*value_bytes16)(sqlite3_value*);
92523   double  (*value_double)(sqlite3_value*);
92524   int  (*value_int)(sqlite3_value*);
92525   sqlite_int64  (*value_int64)(sqlite3_value*);
92526   int  (*value_numeric_type)(sqlite3_value*);
92527   const unsigned char * (*value_text)(sqlite3_value*);
92528   const void * (*value_text16)(sqlite3_value*);
92529   const void * (*value_text16be)(sqlite3_value*);
92530   const void * (*value_text16le)(sqlite3_value*);
92531   int  (*value_type)(sqlite3_value*);
92532   char *(*vmprintf)(const char*,va_list);
92533   /* Added ??? */
92534   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
92535   /* Added by 3.3.13 */
92536   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92537   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92538   int (*clear_bindings)(sqlite3_stmt*);
92539   /* Added by 3.4.1 */
92540   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
92541                           void (*xDestroy)(void *));
92542   /* Added by 3.5.0 */
92543   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
92544   int (*blob_bytes)(sqlite3_blob*);
92545   int (*blob_close)(sqlite3_blob*);
92546   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
92547                    int,sqlite3_blob**);
92548   int (*blob_read)(sqlite3_blob*,void*,int,int);
92549   int (*blob_write)(sqlite3_blob*,const void*,int,int);
92550   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
92551                              int(*)(void*,int,const void*,int,const void*),
92552                              void(*)(void*));
92553   int (*file_control)(sqlite3*,const char*,int,void*);
92554   sqlite3_int64 (*memory_highwater)(int);
92555   sqlite3_int64 (*memory_used)(void);
92556   sqlite3_mutex *(*mutex_alloc)(int);
92557   void (*mutex_enter)(sqlite3_mutex*);
92558   void (*mutex_free)(sqlite3_mutex*);
92559   void (*mutex_leave)(sqlite3_mutex*);
92560   int (*mutex_try)(sqlite3_mutex*);
92561   int (*open_v2)(const char*,sqlite3**,int,const char*);
92562   int (*release_memory)(int);
92563   void (*result_error_nomem)(sqlite3_context*);
92564   void (*result_error_toobig)(sqlite3_context*);
92565   int (*sleep)(int);
92566   void (*soft_heap_limit)(int);
92567   sqlite3_vfs *(*vfs_find)(const char*);
92568   int (*vfs_register)(sqlite3_vfs*,int);
92569   int (*vfs_unregister)(sqlite3_vfs*);
92570   int (*xthreadsafe)(void);
92571   void (*result_zeroblob)(sqlite3_context*,int);
92572   void (*result_error_code)(sqlite3_context*,int);
92573   int (*test_control)(int, ...);
92574   void (*randomness)(int,void*);
92575   sqlite3 *(*context_db_handle)(sqlite3_context*);
92576   int (*extended_result_codes)(sqlite3*,int);
92577   int (*limit)(sqlite3*,int,int);
92578   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
92579   const char *(*sql)(sqlite3_stmt*);
92580   int (*status)(int,int*,int*,int);
92581   int (*backup_finish)(sqlite3_backup*);
92582   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
92583   int (*backup_pagecount)(sqlite3_backup*);
92584   int (*backup_remaining)(sqlite3_backup*);
92585   int (*backup_step)(sqlite3_backup*,int);
92586   const char *(*compileoption_get)(int);
92587   int (*compileoption_used)(const char*);
92588   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
92589                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92590                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92591                             void (*xFinal)(sqlite3_context*),
92592                             void(*xDestroy)(void*));
92593   int (*db_config)(sqlite3*,int,...);
92594   sqlite3_mutex *(*db_mutex)(sqlite3*);
92595   int (*db_status)(sqlite3*,int,int*,int*,int);
92596   int (*extended_errcode)(sqlite3*);
92597   void (*log)(int,const char*,...);
92598   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
92599   const char *(*sourceid)(void);
92600   int (*stmt_status)(sqlite3_stmt*,int,int);
92601   int (*strnicmp)(const char*,const char*,int);
92602   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
92603   int (*wal_autocheckpoint)(sqlite3*,int);
92604   int (*wal_checkpoint)(sqlite3*,const char*);
92605   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
92606   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
92607   int (*vtab_config)(sqlite3*,int op,...);
92608   int (*vtab_on_conflict)(sqlite3*);
92609 };
92610
92611 /*
92612 ** The following macros redefine the API routines so that they are
92613 ** redirected throught the global sqlite3_api structure.
92614 **
92615 ** This header file is also used by the loadext.c source file
92616 ** (part of the main SQLite library - not an extension) so that
92617 ** it can get access to the sqlite3_api_routines structure
92618 ** definition.  But the main library does not want to redefine
92619 ** the API.  So the redefinition macros are only valid if the
92620 ** SQLITE_CORE macros is undefined.
92621 */
92622 #ifndef SQLITE_CORE
92623 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
92624 #ifndef SQLITE_OMIT_DEPRECATED
92625 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
92626 #endif
92627 #define sqlite3_bind_blob              sqlite3_api->bind_blob
92628 #define sqlite3_bind_double            sqlite3_api->bind_double
92629 #define sqlite3_bind_int               sqlite3_api->bind_int
92630 #define sqlite3_bind_int64             sqlite3_api->bind_int64
92631 #define sqlite3_bind_null              sqlite3_api->bind_null
92632 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
92633 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
92634 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
92635 #define sqlite3_bind_text              sqlite3_api->bind_text
92636 #define sqlite3_bind_text16            sqlite3_api->bind_text16
92637 #define sqlite3_bind_value             sqlite3_api->bind_value
92638 #define sqlite3_busy_handler           sqlite3_api->busy_handler
92639 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
92640 #define sqlite3_changes                sqlite3_api->changes
92641 #define sqlite3_close                  sqlite3_api->close
92642 #define sqlite3_collation_needed       sqlite3_api->collation_needed
92643 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
92644 #define sqlite3_column_blob            sqlite3_api->column_blob
92645 #define sqlite3_column_bytes           sqlite3_api->column_bytes
92646 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
92647 #define sqlite3_column_count           sqlite3_api->column_count
92648 #define sqlite3_column_database_name   sqlite3_api->column_database_name
92649 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
92650 #define sqlite3_column_decltype        sqlite3_api->column_decltype
92651 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
92652 #define sqlite3_column_double          sqlite3_api->column_double
92653 #define sqlite3_column_int             sqlite3_api->column_int
92654 #define sqlite3_column_int64           sqlite3_api->column_int64
92655 #define sqlite3_column_name            sqlite3_api->column_name
92656 #define sqlite3_column_name16          sqlite3_api->column_name16
92657 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
92658 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
92659 #define sqlite3_column_table_name      sqlite3_api->column_table_name
92660 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
92661 #define sqlite3_column_text            sqlite3_api->column_text
92662 #define sqlite3_column_text16          sqlite3_api->column_text16
92663 #define sqlite3_column_type            sqlite3_api->column_type
92664 #define sqlite3_column_value           sqlite3_api->column_value
92665 #define sqlite3_commit_hook            sqlite3_api->commit_hook
92666 #define sqlite3_complete               sqlite3_api->complete
92667 #define sqlite3_complete16             sqlite3_api->complete16
92668 #define sqlite3_create_collation       sqlite3_api->create_collation
92669 #define sqlite3_create_collation16     sqlite3_api->create_collation16
92670 #define sqlite3_create_function        sqlite3_api->create_function
92671 #define sqlite3_create_function16      sqlite3_api->create_function16
92672 #define sqlite3_create_module          sqlite3_api->create_module
92673 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
92674 #define sqlite3_data_count             sqlite3_api->data_count
92675 #define sqlite3_db_handle              sqlite3_api->db_handle
92676 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
92677 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
92678 #define sqlite3_errcode                sqlite3_api->errcode
92679 #define sqlite3_errmsg                 sqlite3_api->errmsg
92680 #define sqlite3_errmsg16               sqlite3_api->errmsg16
92681 #define sqlite3_exec                   sqlite3_api->exec
92682 #ifndef SQLITE_OMIT_DEPRECATED
92683 #define sqlite3_expired                sqlite3_api->expired
92684 #endif
92685 #define sqlite3_finalize               sqlite3_api->finalize
92686 #define sqlite3_free                   sqlite3_api->free
92687 #define sqlite3_free_table             sqlite3_api->free_table
92688 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
92689 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
92690 #define sqlite3_get_table              sqlite3_api->get_table
92691 #ifndef SQLITE_OMIT_DEPRECATED
92692 #define sqlite3_global_recover         sqlite3_api->global_recover
92693 #endif
92694 #define sqlite3_interrupt              sqlite3_api->interruptx
92695 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
92696 #define sqlite3_libversion             sqlite3_api->libversion
92697 #define sqlite3_libversion_number      sqlite3_api->libversion_number
92698 #define sqlite3_malloc                 sqlite3_api->malloc
92699 #define sqlite3_mprintf                sqlite3_api->mprintf
92700 #define sqlite3_open                   sqlite3_api->open
92701 #define sqlite3_open16                 sqlite3_api->open16
92702 #define sqlite3_prepare                sqlite3_api->prepare
92703 #define sqlite3_prepare16              sqlite3_api->prepare16
92704 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92705 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92706 #define sqlite3_profile                sqlite3_api->profile
92707 #define sqlite3_progress_handler       sqlite3_api->progress_handler
92708 #define sqlite3_realloc                sqlite3_api->realloc
92709 #define sqlite3_reset                  sqlite3_api->reset
92710 #define sqlite3_result_blob            sqlite3_api->result_blob
92711 #define sqlite3_result_double          sqlite3_api->result_double
92712 #define sqlite3_result_error           sqlite3_api->result_error
92713 #define sqlite3_result_error16         sqlite3_api->result_error16
92714 #define sqlite3_result_int             sqlite3_api->result_int
92715 #define sqlite3_result_int64           sqlite3_api->result_int64
92716 #define sqlite3_result_null            sqlite3_api->result_null
92717 #define sqlite3_result_text            sqlite3_api->result_text
92718 #define sqlite3_result_text16          sqlite3_api->result_text16
92719 #define sqlite3_result_text16be        sqlite3_api->result_text16be
92720 #define sqlite3_result_text16le        sqlite3_api->result_text16le
92721 #define sqlite3_result_value           sqlite3_api->result_value
92722 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
92723 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
92724 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
92725 #define sqlite3_snprintf               sqlite3_api->snprintf
92726 #define sqlite3_step                   sqlite3_api->step
92727 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
92728 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
92729 #define sqlite3_total_changes          sqlite3_api->total_changes
92730 #define sqlite3_trace                  sqlite3_api->trace
92731 #ifndef SQLITE_OMIT_DEPRECATED
92732 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
92733 #endif
92734 #define sqlite3_update_hook            sqlite3_api->update_hook
92735 #define sqlite3_user_data              sqlite3_api->user_data
92736 #define sqlite3_value_blob             sqlite3_api->value_blob
92737 #define sqlite3_value_bytes            sqlite3_api->value_bytes
92738 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
92739 #define sqlite3_value_double           sqlite3_api->value_double
92740 #define sqlite3_value_int              sqlite3_api->value_int
92741 #define sqlite3_value_int64            sqlite3_api->value_int64
92742 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
92743 #define sqlite3_value_text             sqlite3_api->value_text
92744 #define sqlite3_value_text16           sqlite3_api->value_text16
92745 #define sqlite3_value_text16be         sqlite3_api->value_text16be
92746 #define sqlite3_value_text16le         sqlite3_api->value_text16le
92747 #define sqlite3_value_type             sqlite3_api->value_type
92748 #define sqlite3_vmprintf               sqlite3_api->vmprintf
92749 #define sqlite3_overload_function      sqlite3_api->overload_function
92750 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92751 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92752 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
92753 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
92754 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
92755 #define sqlite3_blob_close             sqlite3_api->blob_close
92756 #define sqlite3_blob_open              sqlite3_api->blob_open
92757 #define sqlite3_blob_read              sqlite3_api->blob_read
92758 #define sqlite3_blob_write             sqlite3_api->blob_write
92759 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
92760 #define sqlite3_file_control           sqlite3_api->file_control
92761 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
92762 #define sqlite3_memory_used            sqlite3_api->memory_used
92763 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
92764 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
92765 #define sqlite3_mutex_free             sqlite3_api->mutex_free
92766 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
92767 #define sqlite3_mutex_try              sqlite3_api->mutex_try
92768 #define sqlite3_open_v2                sqlite3_api->open_v2
92769 #define sqlite3_release_memory         sqlite3_api->release_memory
92770 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
92771 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
92772 #define sqlite3_sleep                  sqlite3_api->sleep
92773 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
92774 #define sqlite3_vfs_find               sqlite3_api->vfs_find
92775 #define sqlite3_vfs_register           sqlite3_api->vfs_register
92776 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
92777 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
92778 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
92779 #define sqlite3_result_error_code      sqlite3_api->result_error_code
92780 #define sqlite3_test_control           sqlite3_api->test_control
92781 #define sqlite3_randomness             sqlite3_api->randomness
92782 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
92783 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
92784 #define sqlite3_limit                  sqlite3_api->limit
92785 #define sqlite3_next_stmt              sqlite3_api->next_stmt
92786 #define sqlite3_sql                    sqlite3_api->sql
92787 #define sqlite3_status                 sqlite3_api->status
92788 #define sqlite3_backup_finish          sqlite3_api->backup_finish
92789 #define sqlite3_backup_init            sqlite3_api->backup_init
92790 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
92791 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
92792 #define sqlite3_backup_step            sqlite3_api->backup_step
92793 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
92794 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
92795 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
92796 #define sqlite3_db_config              sqlite3_api->db_config
92797 #define sqlite3_db_mutex               sqlite3_api->db_mutex
92798 #define sqlite3_db_status              sqlite3_api->db_status
92799 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
92800 #define sqlite3_log                    sqlite3_api->log
92801 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
92802 #define sqlite3_sourceid               sqlite3_api->sourceid
92803 #define sqlite3_stmt_status            sqlite3_api->stmt_status
92804 #define sqlite3_strnicmp               sqlite3_api->strnicmp
92805 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
92806 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
92807 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
92808 #define sqlite3_wal_hook               sqlite3_api->wal_hook
92809 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
92810 #define sqlite3_vtab_config            sqlite3_api->vtab_config
92811 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
92812 #endif /* SQLITE_CORE */
92813
92814 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
92815 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
92816
92817 #endif /* _SQLITE3EXT_H_ */
92818
92819 /************** End of sqlite3ext.h ******************************************/
92820 /************** Continuing where we left off in loadext.c ********************/
92821 /* #include <string.h> */
92822
92823 #ifndef SQLITE_OMIT_LOAD_EXTENSION
92824
92825 /*
92826 ** Some API routines are omitted when various features are
92827 ** excluded from a build of SQLite.  Substitute a NULL pointer
92828 ** for any missing APIs.
92829 */
92830 #ifndef SQLITE_ENABLE_COLUMN_METADATA
92831 # define sqlite3_column_database_name   0
92832 # define sqlite3_column_database_name16 0
92833 # define sqlite3_column_table_name      0
92834 # define sqlite3_column_table_name16    0
92835 # define sqlite3_column_origin_name     0
92836 # define sqlite3_column_origin_name16   0
92837 # define sqlite3_table_column_metadata  0
92838 #endif
92839
92840 #ifdef SQLITE_OMIT_AUTHORIZATION
92841 # define sqlite3_set_authorizer         0
92842 #endif
92843
92844 #ifdef SQLITE_OMIT_UTF16
92845 # define sqlite3_bind_text16            0
92846 # define sqlite3_collation_needed16     0
92847 # define sqlite3_column_decltype16      0
92848 # define sqlite3_column_name16          0
92849 # define sqlite3_column_text16          0
92850 # define sqlite3_complete16             0
92851 # define sqlite3_create_collation16     0
92852 # define sqlite3_create_function16      0
92853 # define sqlite3_errmsg16               0
92854 # define sqlite3_open16                 0
92855 # define sqlite3_prepare16              0
92856 # define sqlite3_prepare16_v2           0
92857 # define sqlite3_result_error16         0
92858 # define sqlite3_result_text16          0
92859 # define sqlite3_result_text16be        0
92860 # define sqlite3_result_text16le        0
92861 # define sqlite3_value_text16           0
92862 # define sqlite3_value_text16be         0
92863 # define sqlite3_value_text16le         0
92864 # define sqlite3_column_database_name16 0
92865 # define sqlite3_column_table_name16    0
92866 # define sqlite3_column_origin_name16   0
92867 #endif
92868
92869 #ifdef SQLITE_OMIT_COMPLETE
92870 # define sqlite3_complete 0
92871 # define sqlite3_complete16 0
92872 #endif
92873
92874 #ifdef SQLITE_OMIT_DECLTYPE
92875 # define sqlite3_column_decltype16      0
92876 # define sqlite3_column_decltype        0
92877 #endif
92878
92879 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
92880 # define sqlite3_progress_handler 0
92881 #endif
92882
92883 #ifdef SQLITE_OMIT_VIRTUALTABLE
92884 # define sqlite3_create_module 0
92885 # define sqlite3_create_module_v2 0
92886 # define sqlite3_declare_vtab 0
92887 # define sqlite3_vtab_config 0
92888 # define sqlite3_vtab_on_conflict 0
92889 #endif
92890
92891 #ifdef SQLITE_OMIT_SHARED_CACHE
92892 # define sqlite3_enable_shared_cache 0
92893 #endif
92894
92895 #ifdef SQLITE_OMIT_TRACE
92896 # define sqlite3_profile       0
92897 # define sqlite3_trace         0
92898 #endif
92899
92900 #ifdef SQLITE_OMIT_GET_TABLE
92901 # define sqlite3_free_table    0
92902 # define sqlite3_get_table     0
92903 #endif
92904
92905 #ifdef SQLITE_OMIT_INCRBLOB
92906 #define sqlite3_bind_zeroblob  0
92907 #define sqlite3_blob_bytes     0
92908 #define sqlite3_blob_close     0
92909 #define sqlite3_blob_open      0
92910 #define sqlite3_blob_read      0
92911 #define sqlite3_blob_write     0
92912 #define sqlite3_blob_reopen    0
92913 #endif
92914
92915 /*
92916 ** The following structure contains pointers to all SQLite API routines.
92917 ** A pointer to this structure is passed into extensions when they are
92918 ** loaded so that the extension can make calls back into the SQLite
92919 ** library.
92920 **
92921 ** When adding new APIs, add them to the bottom of this structure
92922 ** in order to preserve backwards compatibility.
92923 **
92924 ** Extensions that use newer APIs should first call the
92925 ** sqlite3_libversion_number() to make sure that the API they
92926 ** intend to use is supported by the library.  Extensions should
92927 ** also check to make sure that the pointer to the function is
92928 ** not NULL before calling it.
92929 */
92930 static const sqlite3_api_routines sqlite3Apis = {
92931   sqlite3_aggregate_context,
92932 #ifndef SQLITE_OMIT_DEPRECATED
92933   sqlite3_aggregate_count,
92934 #else
92935   0,
92936 #endif
92937   sqlite3_bind_blob,
92938   sqlite3_bind_double,
92939   sqlite3_bind_int,
92940   sqlite3_bind_int64,
92941   sqlite3_bind_null,
92942   sqlite3_bind_parameter_count,
92943   sqlite3_bind_parameter_index,
92944   sqlite3_bind_parameter_name,
92945   sqlite3_bind_text,
92946   sqlite3_bind_text16,
92947   sqlite3_bind_value,
92948   sqlite3_busy_handler,
92949   sqlite3_busy_timeout,
92950   sqlite3_changes,
92951   sqlite3_close,
92952   sqlite3_collation_needed,
92953   sqlite3_collation_needed16,
92954   sqlite3_column_blob,
92955   sqlite3_column_bytes,
92956   sqlite3_column_bytes16,
92957   sqlite3_column_count,
92958   sqlite3_column_database_name,
92959   sqlite3_column_database_name16,
92960   sqlite3_column_decltype,
92961   sqlite3_column_decltype16,
92962   sqlite3_column_double,
92963   sqlite3_column_int,
92964   sqlite3_column_int64,
92965   sqlite3_column_name,
92966   sqlite3_column_name16,
92967   sqlite3_column_origin_name,
92968   sqlite3_column_origin_name16,
92969   sqlite3_column_table_name,
92970   sqlite3_column_table_name16,
92971   sqlite3_column_text,
92972   sqlite3_column_text16,
92973   sqlite3_column_type,
92974   sqlite3_column_value,
92975   sqlite3_commit_hook,
92976   sqlite3_complete,
92977   sqlite3_complete16,
92978   sqlite3_create_collation,
92979   sqlite3_create_collation16,
92980   sqlite3_create_function,
92981   sqlite3_create_function16,
92982   sqlite3_create_module,
92983   sqlite3_data_count,
92984   sqlite3_db_handle,
92985   sqlite3_declare_vtab,
92986   sqlite3_enable_shared_cache,
92987   sqlite3_errcode,
92988   sqlite3_errmsg,
92989   sqlite3_errmsg16,
92990   sqlite3_exec,
92991 #ifndef SQLITE_OMIT_DEPRECATED
92992   sqlite3_expired,
92993 #else
92994   0,
92995 #endif
92996   sqlite3_finalize,
92997   sqlite3_free,
92998   sqlite3_free_table,
92999   sqlite3_get_autocommit,
93000   sqlite3_get_auxdata,
93001   sqlite3_get_table,
93002   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
93003   sqlite3_interrupt,
93004   sqlite3_last_insert_rowid,
93005   sqlite3_libversion,
93006   sqlite3_libversion_number,
93007   sqlite3_malloc,
93008   sqlite3_mprintf,
93009   sqlite3_open,
93010   sqlite3_open16,
93011   sqlite3_prepare,
93012   sqlite3_prepare16,
93013   sqlite3_profile,
93014   sqlite3_progress_handler,
93015   sqlite3_realloc,
93016   sqlite3_reset,
93017   sqlite3_result_blob,
93018   sqlite3_result_double,
93019   sqlite3_result_error,
93020   sqlite3_result_error16,
93021   sqlite3_result_int,
93022   sqlite3_result_int64,
93023   sqlite3_result_null,
93024   sqlite3_result_text,
93025   sqlite3_result_text16,
93026   sqlite3_result_text16be,
93027   sqlite3_result_text16le,
93028   sqlite3_result_value,
93029   sqlite3_rollback_hook,
93030   sqlite3_set_authorizer,
93031   sqlite3_set_auxdata,
93032   sqlite3_snprintf,
93033   sqlite3_step,
93034   sqlite3_table_column_metadata,
93035 #ifndef SQLITE_OMIT_DEPRECATED
93036   sqlite3_thread_cleanup,
93037 #else
93038   0,
93039 #endif
93040   sqlite3_total_changes,
93041   sqlite3_trace,
93042 #ifndef SQLITE_OMIT_DEPRECATED
93043   sqlite3_transfer_bindings,
93044 #else
93045   0,
93046 #endif
93047   sqlite3_update_hook,
93048   sqlite3_user_data,
93049   sqlite3_value_blob,
93050   sqlite3_value_bytes,
93051   sqlite3_value_bytes16,
93052   sqlite3_value_double,
93053   sqlite3_value_int,
93054   sqlite3_value_int64,
93055   sqlite3_value_numeric_type,
93056   sqlite3_value_text,
93057   sqlite3_value_text16,
93058   sqlite3_value_text16be,
93059   sqlite3_value_text16le,
93060   sqlite3_value_type,
93061   sqlite3_vmprintf,
93062   /*
93063   ** The original API set ends here.  All extensions can call any
93064   ** of the APIs above provided that the pointer is not NULL.  But
93065   ** before calling APIs that follow, extension should check the
93066   ** sqlite3_libversion_number() to make sure they are dealing with
93067   ** a library that is new enough to support that API.
93068   *************************************************************************
93069   */
93070   sqlite3_overload_function,
93071
93072   /*
93073   ** Added after 3.3.13
93074   */
93075   sqlite3_prepare_v2,
93076   sqlite3_prepare16_v2,
93077   sqlite3_clear_bindings,
93078
93079   /*
93080   ** Added for 3.4.1
93081   */
93082   sqlite3_create_module_v2,
93083
93084   /*
93085   ** Added for 3.5.0
93086   */
93087   sqlite3_bind_zeroblob,
93088   sqlite3_blob_bytes,
93089   sqlite3_blob_close,
93090   sqlite3_blob_open,
93091   sqlite3_blob_read,
93092   sqlite3_blob_write,
93093   sqlite3_create_collation_v2,
93094   sqlite3_file_control,
93095   sqlite3_memory_highwater,
93096   sqlite3_memory_used,
93097 #ifdef SQLITE_MUTEX_OMIT
93098   0,
93099   0,
93100   0,
93101   0,
93102   0,
93103 #else
93104   sqlite3_mutex_alloc,
93105   sqlite3_mutex_enter,
93106   sqlite3_mutex_free,
93107   sqlite3_mutex_leave,
93108   sqlite3_mutex_try,
93109 #endif
93110   sqlite3_open_v2,
93111   sqlite3_release_memory,
93112   sqlite3_result_error_nomem,
93113   sqlite3_result_error_toobig,
93114   sqlite3_sleep,
93115   sqlite3_soft_heap_limit,
93116   sqlite3_vfs_find,
93117   sqlite3_vfs_register,
93118   sqlite3_vfs_unregister,
93119
93120   /*
93121   ** Added for 3.5.8
93122   */
93123   sqlite3_threadsafe,
93124   sqlite3_result_zeroblob,
93125   sqlite3_result_error_code,
93126   sqlite3_test_control,
93127   sqlite3_randomness,
93128   sqlite3_context_db_handle,
93129
93130   /*
93131   ** Added for 3.6.0
93132   */
93133   sqlite3_extended_result_codes,
93134   sqlite3_limit,
93135   sqlite3_next_stmt,
93136   sqlite3_sql,
93137   sqlite3_status,
93138
93139   /*
93140   ** Added for 3.7.4
93141   */
93142   sqlite3_backup_finish,
93143   sqlite3_backup_init,
93144   sqlite3_backup_pagecount,
93145   sqlite3_backup_remaining,
93146   sqlite3_backup_step,
93147 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
93148   sqlite3_compileoption_get,
93149   sqlite3_compileoption_used,
93150 #else
93151   0,
93152   0,
93153 #endif
93154   sqlite3_create_function_v2,
93155   sqlite3_db_config,
93156   sqlite3_db_mutex,
93157   sqlite3_db_status,
93158   sqlite3_extended_errcode,
93159   sqlite3_log,
93160   sqlite3_soft_heap_limit64,
93161   sqlite3_sourceid,
93162   sqlite3_stmt_status,
93163   sqlite3_strnicmp,
93164 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
93165   sqlite3_unlock_notify,
93166 #else
93167   0,
93168 #endif
93169 #ifndef SQLITE_OMIT_WAL
93170   sqlite3_wal_autocheckpoint,
93171   sqlite3_wal_checkpoint,
93172   sqlite3_wal_hook,
93173 #else
93174   0,
93175   0,
93176   0,
93177 #endif
93178   sqlite3_blob_reopen,
93179   sqlite3_vtab_config,
93180   sqlite3_vtab_on_conflict,
93181 };
93182
93183 /*
93184 ** Attempt to load an SQLite extension library contained in the file
93185 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
93186 ** default entry point name (sqlite3_extension_init) is used.  Use
93187 ** of the default name is recommended.
93188 **
93189 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
93190 **
93191 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
93192 ** error message text.  The calling function should free this memory
93193 ** by calling sqlite3DbFree(db, ).
93194 */
93195 static int sqlite3LoadExtension(
93196   sqlite3 *db,          /* Load the extension into this database connection */
93197   const char *zFile,    /* Name of the shared library containing extension */
93198   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
93199   char **pzErrMsg       /* Put error message here if not 0 */
93200 ){
93201   sqlite3_vfs *pVfs = db->pVfs;
93202   void *handle;
93203   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93204   char *zErrmsg = 0;
93205   void **aHandle;
93206   int nMsg = 300 + sqlite3Strlen30(zFile);
93207
93208   if( pzErrMsg ) *pzErrMsg = 0;
93209
93210   /* Ticket #1863.  To avoid a creating security problems for older
93211   ** applications that relink against newer versions of SQLite, the
93212   ** ability to run load_extension is turned off by default.  One
93213   ** must call sqlite3_enable_load_extension() to turn on extension
93214   ** loading.  Otherwise you get the following error.
93215   */
93216   if( (db->flags & SQLITE_LoadExtension)==0 ){
93217     if( pzErrMsg ){
93218       *pzErrMsg = sqlite3_mprintf("not authorized");
93219     }
93220     return SQLITE_ERROR;
93221   }
93222
93223   if( zProc==0 ){
93224     zProc = "sqlite3_extension_init";
93225   }
93226
93227   handle = sqlite3OsDlOpen(pVfs, zFile);
93228   if( handle==0 ){
93229     if( pzErrMsg ){
93230       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93231       if( zErrmsg ){
93232         sqlite3_snprintf(nMsg, zErrmsg,
93233             "unable to open shared library [%s]", zFile);
93234         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93235       }
93236     }
93237     return SQLITE_ERROR;
93238   }
93239   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93240                    sqlite3OsDlSym(pVfs, handle, zProc);
93241   if( xInit==0 ){
93242     if( pzErrMsg ){
93243       nMsg += sqlite3Strlen30(zProc);
93244       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93245       if( zErrmsg ){
93246         sqlite3_snprintf(nMsg, zErrmsg,
93247             "no entry point [%s] in shared library [%s]", zProc,zFile);
93248         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93249       }
93250       sqlite3OsDlClose(pVfs, handle);
93251     }
93252     return SQLITE_ERROR;
93253   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
93254     if( pzErrMsg ){
93255       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
93256     }
93257     sqlite3_free(zErrmsg);
93258     sqlite3OsDlClose(pVfs, handle);
93259     return SQLITE_ERROR;
93260   }
93261
93262   /* Append the new shared library handle to the db->aExtension array. */
93263   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
93264   if( aHandle==0 ){
93265     return SQLITE_NOMEM;
93266   }
93267   if( db->nExtension>0 ){
93268     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
93269   }
93270   sqlite3DbFree(db, db->aExtension);
93271   db->aExtension = aHandle;
93272
93273   db->aExtension[db->nExtension++] = handle;
93274   return SQLITE_OK;
93275 }
93276 SQLITE_API int sqlite3_load_extension(
93277   sqlite3 *db,          /* Load the extension into this database connection */
93278   const char *zFile,    /* Name of the shared library containing extension */
93279   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
93280   char **pzErrMsg       /* Put error message here if not 0 */
93281 ){
93282   int rc;
93283   sqlite3_mutex_enter(db->mutex);
93284   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
93285   rc = sqlite3ApiExit(db, rc);
93286   sqlite3_mutex_leave(db->mutex);
93287   return rc;
93288 }
93289
93290 /*
93291 ** Call this routine when the database connection is closing in order
93292 ** to clean up loaded extensions
93293 */
93294 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
93295   int i;
93296   assert( sqlite3_mutex_held(db->mutex) );
93297   for(i=0; i<db->nExtension; i++){
93298     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
93299   }
93300   sqlite3DbFree(db, db->aExtension);
93301 }
93302
93303 /*
93304 ** Enable or disable extension loading.  Extension loading is disabled by
93305 ** default so as not to open security holes in older applications.
93306 */
93307 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
93308   sqlite3_mutex_enter(db->mutex);
93309   if( onoff ){
93310     db->flags |= SQLITE_LoadExtension;
93311   }else{
93312     db->flags &= ~SQLITE_LoadExtension;
93313   }
93314   sqlite3_mutex_leave(db->mutex);
93315   return SQLITE_OK;
93316 }
93317
93318 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
93319
93320 /*
93321 ** The auto-extension code added regardless of whether or not extension
93322 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
93323 ** code if regular extension loading is not available.  This is that
93324 ** dummy pointer.
93325 */
93326 #ifdef SQLITE_OMIT_LOAD_EXTENSION
93327 static const sqlite3_api_routines sqlite3Apis = { 0 };
93328 #endif
93329
93330
93331 /*
93332 ** The following object holds the list of automatically loaded
93333 ** extensions.
93334 **
93335 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
93336 ** mutex must be held while accessing this list.
93337 */
93338 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
93339 static SQLITE_WSD struct sqlite3AutoExtList {
93340   int nExt;              /* Number of entries in aExt[] */
93341   void (**aExt)(void);   /* Pointers to the extension init functions */
93342 } sqlite3Autoext = { 0, 0 };
93343
93344 /* The "wsdAutoext" macro will resolve to the autoextension
93345 ** state vector.  If writable static data is unsupported on the target,
93346 ** we have to locate the state vector at run-time.  In the more common
93347 ** case where writable static data is supported, wsdStat can refer directly
93348 ** to the "sqlite3Autoext" state vector declared above.
93349 */
93350 #ifdef SQLITE_OMIT_WSD
93351 # define wsdAutoextInit \
93352   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
93353 # define wsdAutoext x[0]
93354 #else
93355 # define wsdAutoextInit
93356 # define wsdAutoext sqlite3Autoext
93357 #endif
93358
93359
93360 /*
93361 ** Register a statically linked extension that is automatically
93362 ** loaded by every new database connection.
93363 */
93364 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
93365   int rc = SQLITE_OK;
93366 #ifndef SQLITE_OMIT_AUTOINIT
93367   rc = sqlite3_initialize();
93368   if( rc ){
93369     return rc;
93370   }else
93371 #endif
93372   {
93373     int i;
93374 #if SQLITE_THREADSAFE
93375     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93376 #endif
93377     wsdAutoextInit;
93378     sqlite3_mutex_enter(mutex);
93379     for(i=0; i<wsdAutoext.nExt; i++){
93380       if( wsdAutoext.aExt[i]==xInit ) break;
93381     }
93382     if( i==wsdAutoext.nExt ){
93383       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
93384       void (**aNew)(void);
93385       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
93386       if( aNew==0 ){
93387         rc = SQLITE_NOMEM;
93388       }else{
93389         wsdAutoext.aExt = aNew;
93390         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
93391         wsdAutoext.nExt++;
93392       }
93393     }
93394     sqlite3_mutex_leave(mutex);
93395     assert( (rc&0xff)==rc );
93396     return rc;
93397   }
93398 }
93399
93400 /*
93401 ** Reset the automatic extension loading mechanism.
93402 */
93403 SQLITE_API void sqlite3_reset_auto_extension(void){
93404 #ifndef SQLITE_OMIT_AUTOINIT
93405   if( sqlite3_initialize()==SQLITE_OK )
93406 #endif
93407   {
93408 #if SQLITE_THREADSAFE
93409     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93410 #endif
93411     wsdAutoextInit;
93412     sqlite3_mutex_enter(mutex);
93413     sqlite3_free(wsdAutoext.aExt);
93414     wsdAutoext.aExt = 0;
93415     wsdAutoext.nExt = 0;
93416     sqlite3_mutex_leave(mutex);
93417   }
93418 }
93419
93420 /*
93421 ** Load all automatic extensions.
93422 **
93423 ** If anything goes wrong, set an error in the database connection.
93424 */
93425 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
93426   int i;
93427   int go = 1;
93428   int rc;
93429   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93430
93431   wsdAutoextInit;
93432   if( wsdAutoext.nExt==0 ){
93433     /* Common case: early out without every having to acquire a mutex */
93434     return;
93435   }
93436   for(i=0; go; i++){
93437     char *zErrmsg;
93438 #if SQLITE_THREADSAFE
93439     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93440 #endif
93441     sqlite3_mutex_enter(mutex);
93442     if( i>=wsdAutoext.nExt ){
93443       xInit = 0;
93444       go = 0;
93445     }else{
93446       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93447               wsdAutoext.aExt[i];
93448     }
93449     sqlite3_mutex_leave(mutex);
93450     zErrmsg = 0;
93451     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
93452       sqlite3Error(db, rc,
93453             "automatic extension loading failed: %s", zErrmsg);
93454       go = 0;
93455     }
93456     sqlite3_free(zErrmsg);
93457   }
93458 }
93459
93460 /************** End of loadext.c *********************************************/
93461 /************** Begin file pragma.c ******************************************/
93462 /*
93463 ** 2003 April 6
93464 **
93465 ** The author disclaims copyright to this source code.  In place of
93466 ** a legal notice, here is a blessing:
93467 **
93468 **    May you do good and not evil.
93469 **    May you find forgiveness for yourself and forgive others.
93470 **    May you share freely, never taking more than you give.
93471 **
93472 *************************************************************************
93473 ** This file contains code used to implement the PRAGMA command.
93474 */
93475
93476 /*
93477 ** Interpret the given string as a safety level.  Return 0 for OFF,
93478 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
93479 ** unrecognized string argument.  The FULL option is disallowed
93480 ** if the omitFull parameter it 1.
93481 **
93482 ** Note that the values returned are one less that the values that
93483 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
93484 ** to support legacy SQL code.  The safety level used to be boolean
93485 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
93486 */
93487 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
93488                              /* 123456789 123456789 */
93489   static const char zText[] = "onoffalseyestruefull";
93490   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
93491   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
93492   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
93493   int i, n;
93494   if( sqlite3Isdigit(*z) ){
93495     return (u8)sqlite3Atoi(z);
93496   }
93497   n = sqlite3Strlen30(z);
93498   for(i=0; i<ArraySize(iLength)-omitFull; i++){
93499     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
93500       return iValue[i];
93501     }
93502   }
93503   return dflt;
93504 }
93505
93506 /*
93507 ** Interpret the given string as a boolean value.
93508 */
93509 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
93510   return getSafetyLevel(z,1,dflt)!=0;
93511 }
93512
93513 /* The sqlite3GetBoolean() function is used by other modules but the
93514 ** remainder of this file is specific to PRAGMA processing.  So omit
93515 ** the rest of the file if PRAGMAs are omitted from the build.
93516 */
93517 #if !defined(SQLITE_OMIT_PRAGMA)
93518
93519 /*
93520 ** Interpret the given string as a locking mode value.
93521 */
93522 static int getLockingMode(const char *z){
93523   if( z ){
93524     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
93525     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
93526   }
93527   return PAGER_LOCKINGMODE_QUERY;
93528 }
93529
93530 #ifndef SQLITE_OMIT_AUTOVACUUM
93531 /*
93532 ** Interpret the given string as an auto-vacuum mode value.
93533 **
93534 ** The following strings, "none", "full" and "incremental" are
93535 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
93536 */
93537 static int getAutoVacuum(const char *z){
93538   int i;
93539   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
93540   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
93541   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
93542   i = sqlite3Atoi(z);
93543   return (u8)((i>=0&&i<=2)?i:0);
93544 }
93545 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
93546
93547 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93548 /*
93549 ** Interpret the given string as a temp db location. Return 1 for file
93550 ** backed temporary databases, 2 for the Red-Black tree in memory database
93551 ** and 0 to use the compile-time default.
93552 */
93553 static int getTempStore(const char *z){
93554   if( z[0]>='0' && z[0]<='2' ){
93555     return z[0] - '0';
93556   }else if( sqlite3StrICmp(z, "file")==0 ){
93557     return 1;
93558   }else if( sqlite3StrICmp(z, "memory")==0 ){
93559     return 2;
93560   }else{
93561     return 0;
93562   }
93563 }
93564 #endif /* SQLITE_PAGER_PRAGMAS */
93565
93566 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93567 /*
93568 ** Invalidate temp storage, either when the temp storage is changed
93569 ** from default, or when 'file' and the temp_store_directory has changed
93570 */
93571 static int invalidateTempStorage(Parse *pParse){
93572   sqlite3 *db = pParse->db;
93573   if( db->aDb[1].pBt!=0 ){
93574     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
93575       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
93576         "from within a transaction");
93577       return SQLITE_ERROR;
93578     }
93579     sqlite3BtreeClose(db->aDb[1].pBt);
93580     db->aDb[1].pBt = 0;
93581     sqlite3ResetAllSchemasOfConnection(db);
93582   }
93583   return SQLITE_OK;
93584 }
93585 #endif /* SQLITE_PAGER_PRAGMAS */
93586
93587 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93588 /*
93589 ** If the TEMP database is open, close it and mark the database schema
93590 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
93591 ** or DEFAULT_TEMP_STORE pragmas.
93592 */
93593 static int changeTempStorage(Parse *pParse, const char *zStorageType){
93594   int ts = getTempStore(zStorageType);
93595   sqlite3 *db = pParse->db;
93596   if( db->temp_store==ts ) return SQLITE_OK;
93597   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
93598     return SQLITE_ERROR;
93599   }
93600   db->temp_store = (u8)ts;
93601   return SQLITE_OK;
93602 }
93603 #endif /* SQLITE_PAGER_PRAGMAS */
93604
93605 /*
93606 ** Generate code to return a single integer value.
93607 */
93608 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
93609   Vdbe *v = sqlite3GetVdbe(pParse);
93610   int mem = ++pParse->nMem;
93611   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
93612   if( pI64 ){
93613     memcpy(pI64, &value, sizeof(value));
93614   }
93615   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
93616   sqlite3VdbeSetNumCols(v, 1);
93617   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
93618   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93619 }
93620
93621 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
93622 /*
93623 ** Check to see if zRight and zLeft refer to a pragma that queries
93624 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
93625 ** Also, implement the pragma.
93626 */
93627 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
93628   static const struct sPragmaType {
93629     const char *zName;  /* Name of the pragma */
93630     int mask;           /* Mask for the db->flags value */
93631   } aPragma[] = {
93632     { "full_column_names",        SQLITE_FullColNames  },
93633     { "short_column_names",       SQLITE_ShortColNames },
93634     { "count_changes",            SQLITE_CountRows     },
93635     { "empty_result_callbacks",   SQLITE_NullCallback  },
93636     { "legacy_file_format",       SQLITE_LegacyFileFmt },
93637     { "fullfsync",                SQLITE_FullFSync     },
93638     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
93639     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
93640 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
93641     { "automatic_index",          SQLITE_AutoIndex     },
93642 #endif
93643 #ifdef SQLITE_DEBUG
93644     { "sql_trace",                SQLITE_SqlTrace      },
93645     { "vdbe_listing",             SQLITE_VdbeListing   },
93646     { "vdbe_trace",               SQLITE_VdbeTrace     },
93647 #endif
93648 #ifndef SQLITE_OMIT_CHECK
93649     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
93650 #endif
93651     /* The following is VERY experimental */
93652     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
93653
93654     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
93655     ** flag if there are any active statements. */
93656     { "read_uncommitted",         SQLITE_ReadUncommitted },
93657     { "recursive_triggers",       SQLITE_RecTriggers },
93658
93659     /* This flag may only be set if both foreign-key and trigger support
93660     ** are present in the build.  */
93661 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93662     { "foreign_keys",             SQLITE_ForeignKeys },
93663 #endif
93664   };
93665   int i;
93666   const struct sPragmaType *p;
93667   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
93668     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
93669       sqlite3 *db = pParse->db;
93670       Vdbe *v;
93671       v = sqlite3GetVdbe(pParse);
93672       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
93673       if( ALWAYS(v) ){
93674         if( zRight==0 ){
93675           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
93676         }else{
93677           int mask = p->mask;          /* Mask of bits to set or clear. */
93678           if( db->autoCommit==0 ){
93679             /* Foreign key support may not be enabled or disabled while not
93680             ** in auto-commit mode.  */
93681             mask &= ~(SQLITE_ForeignKeys);
93682           }
93683
93684           if( sqlite3GetBoolean(zRight, 0) ){
93685             db->flags |= mask;
93686           }else{
93687             db->flags &= ~mask;
93688           }
93689
93690           /* Many of the flag-pragmas modify the code generated by the SQL
93691           ** compiler (eg. count_changes). So add an opcode to expire all
93692           ** compiled SQL statements after modifying a pragma value.
93693           */
93694           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
93695         }
93696       }
93697
93698       return 1;
93699     }
93700   }
93701   return 0;
93702 }
93703 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
93704
93705 /*
93706 ** Return a human-readable name for a constraint resolution action.
93707 */
93708 #ifndef SQLITE_OMIT_FOREIGN_KEY
93709 static const char *actionName(u8 action){
93710   const char *zName;
93711   switch( action ){
93712     case OE_SetNull:  zName = "SET NULL";        break;
93713     case OE_SetDflt:  zName = "SET DEFAULT";     break;
93714     case OE_Cascade:  zName = "CASCADE";         break;
93715     case OE_Restrict: zName = "RESTRICT";        break;
93716     default:          zName = "NO ACTION";
93717                       assert( action==OE_None ); break;
93718   }
93719   return zName;
93720 }
93721 #endif
93722
93723
93724 /*
93725 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
93726 ** defined in pager.h. This function returns the associated lowercase
93727 ** journal-mode name.
93728 */
93729 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
93730   static char * const azModeName[] = {
93731     "delete", "persist", "off", "truncate", "memory"
93732 #ifndef SQLITE_OMIT_WAL
93733      , "wal"
93734 #endif
93735   };
93736   assert( PAGER_JOURNALMODE_DELETE==0 );
93737   assert( PAGER_JOURNALMODE_PERSIST==1 );
93738   assert( PAGER_JOURNALMODE_OFF==2 );
93739   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
93740   assert( PAGER_JOURNALMODE_MEMORY==4 );
93741   assert( PAGER_JOURNALMODE_WAL==5 );
93742   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
93743
93744   if( eMode==ArraySize(azModeName) ) return 0;
93745   return azModeName[eMode];
93746 }
93747
93748 /*
93749 ** Process a pragma statement.
93750 **
93751 ** Pragmas are of this form:
93752 **
93753 **      PRAGMA [database.]id [= value]
93754 **
93755 ** The identifier might also be a string.  The value is a string, and
93756 ** identifier, or a number.  If minusFlag is true, then the value is
93757 ** a number that was preceded by a minus sign.
93758 **
93759 ** If the left side is "database.id" then pId1 is the database name
93760 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
93761 ** id and pId2 is any empty string.
93762 */
93763 SQLITE_PRIVATE void sqlite3Pragma(
93764   Parse *pParse,
93765   Token *pId1,        /* First part of [database.]id field */
93766   Token *pId2,        /* Second part of [database.]id field, or NULL */
93767   Token *pValue,      /* Token for <value>, or NULL */
93768   int minusFlag       /* True if a '-' sign preceded <value> */
93769 ){
93770   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
93771   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
93772   const char *zDb = 0;   /* The database name */
93773   Token *pId;            /* Pointer to <id> token */
93774   int iDb;               /* Database index for <database> */
93775   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
93776   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
93777   sqlite3 *db = pParse->db;    /* The database connection */
93778   Db *pDb;                     /* The specific database being pragmaed */
93779   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
93780 /** BEGIN CRYPTO **/
93781 #ifdef SQLITE_HAS_CODEC
93782   extern int codec_pragma(sqlite3*, int, Parse *, const char *, const char *);
93783 #endif
93784 /** END CRYPTO **/
93785
93786
93787   if( v==0 ) return;
93788   sqlite3VdbeRunOnlyOnce(v);
93789   pParse->nMem = 2;
93790
93791   /* Interpret the [database.] part of the pragma statement. iDb is the
93792   ** index of the database this pragma is being applied to in db.aDb[]. */
93793   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
93794   if( iDb<0 ) return;
93795   pDb = &db->aDb[iDb];
93796
93797   /* If the temp database has been explicitly named as part of the
93798   ** pragma, make sure it is open.
93799   */
93800   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
93801     return;
93802   }
93803
93804   zLeft = sqlite3NameFromToken(db, pId);
93805   if( !zLeft ) return;
93806   if( minusFlag ){
93807     zRight = sqlite3MPrintf(db, "-%T", pValue);
93808   }else{
93809     zRight = sqlite3NameFromToken(db, pValue);
93810   }
93811
93812   assert( pId2 );
93813   zDb = pId2->n>0 ? pDb->zName : 0;
93814   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
93815     goto pragma_out;
93816   }
93817
93818   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
93819   ** connection.  If it returns SQLITE_OK, then assume that the VFS
93820   ** handled the pragma and generate a no-op prepared statement.
93821   */
93822   aFcntl[0] = 0;
93823   aFcntl[1] = zLeft;
93824   aFcntl[2] = zRight;
93825   aFcntl[3] = 0;
93826   db->busyHandler.nBusy = 0;
93827   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
93828   if( rc==SQLITE_OK ){
93829     if( aFcntl[0] ){
93830       int mem = ++pParse->nMem;
93831       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
93832       sqlite3VdbeSetNumCols(v, 1);
93833       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
93834       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93835       sqlite3_free(aFcntl[0]);
93836     }
93837   }else if( rc!=SQLITE_NOTFOUND ){
93838     if( aFcntl[0] ){
93839       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
93840       sqlite3_free(aFcntl[0]);
93841     }
93842     pParse->nErr++;
93843     pParse->rc = rc;
93844   }else
93845
93846 /** BEGIN CRYPTO **/
93847 #ifdef SQLITE_HAS_CODEC
93848   if(codec_pragma(db, iDb, pParse, zLeft, zRight)) {
93849     /* codec_pragma executes internal */
93850   }else
93851   #endif
93852 /** END CRYPTO **/
93853
93854 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
93855   /*
93856   **  PRAGMA [database.]default_cache_size
93857   **  PRAGMA [database.]default_cache_size=N
93858   **
93859   ** The first form reports the current persistent setting for the
93860   ** page cache size.  The value returned is the maximum number of
93861   ** pages in the page cache.  The second form sets both the current
93862   ** page cache size value and the persistent page cache size value
93863   ** stored in the database file.
93864   **
93865   ** Older versions of SQLite would set the default cache size to a
93866   ** negative number to indicate synchronous=OFF.  These days, synchronous
93867   ** is always on by default regardless of the sign of the default cache
93868   ** size.  But continue to take the absolute value of the default cache
93869   ** size of historical compatibility.
93870   */
93871   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
93872     static const VdbeOpList getCacheSize[] = {
93873       { OP_Transaction, 0, 0,        0},                         /* 0 */
93874       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
93875       { OP_IfPos,       1, 7,        0},
93876       { OP_Integer,     0, 2,        0},
93877       { OP_Subtract,    1, 2,        1},
93878       { OP_IfPos,       1, 7,        0},
93879       { OP_Integer,     0, 1,        0},                         /* 6 */
93880       { OP_ResultRow,   1, 1,        0},
93881     };
93882     int addr;
93883     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93884     sqlite3VdbeUsesBtree(v, iDb);
93885     if( !zRight ){
93886       sqlite3VdbeSetNumCols(v, 1);
93887       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
93888       pParse->nMem += 2;
93889       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
93890       sqlite3VdbeChangeP1(v, addr, iDb);
93891       sqlite3VdbeChangeP1(v, addr+1, iDb);
93892       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
93893     }else{
93894       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
93895       sqlite3BeginWriteOperation(pParse, 0, iDb);
93896       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
93897       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
93898       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93899       pDb->pSchema->cache_size = size;
93900       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93901     }
93902   }else
93903 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
93904
93905 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
93906   /*
93907   **  PRAGMA [database.]page_size
93908   **  PRAGMA [database.]page_size=N
93909   **
93910   ** The first form reports the current setting for the
93911   ** database page size in bytes.  The second form sets the
93912   ** database page size value.  The value can only be set if
93913   ** the database has not yet been created.
93914   */
93915   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
93916     Btree *pBt = pDb->pBt;
93917     assert( pBt!=0 );
93918     if( !zRight ){
93919       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
93920       returnSingleInt(pParse, "page_size", size);
93921     }else{
93922       /* Malloc may fail when setting the page-size, as there is an internal
93923       ** buffer that the pager module resizes using sqlite3_realloc().
93924       */
93925       db->nextPagesize = sqlite3Atoi(zRight);
93926       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
93927         db->mallocFailed = 1;
93928       }
93929     }
93930   }else
93931
93932   /*
93933   **  PRAGMA [database.]secure_delete
93934   **  PRAGMA [database.]secure_delete=ON/OFF
93935   **
93936   ** The first form reports the current setting for the
93937   ** secure_delete flag.  The second form changes the secure_delete
93938   ** flag setting and reports thenew value.
93939   */
93940   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
93941     Btree *pBt = pDb->pBt;
93942     int b = -1;
93943     assert( pBt!=0 );
93944     if( zRight ){
93945       b = sqlite3GetBoolean(zRight, 0);
93946     }
93947     if( pId2->n==0 && b>=0 ){
93948       int ii;
93949       for(ii=0; ii<db->nDb; ii++){
93950         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
93951       }
93952     }
93953     b = sqlite3BtreeSecureDelete(pBt, b);
93954     returnSingleInt(pParse, "secure_delete", b);
93955   }else
93956
93957   /*
93958   **  PRAGMA [database.]max_page_count
93959   **  PRAGMA [database.]max_page_count=N
93960   **
93961   ** The first form reports the current setting for the
93962   ** maximum number of pages in the database file.  The
93963   ** second form attempts to change this setting.  Both
93964   ** forms return the current setting.
93965   **
93966   ** The absolute value of N is used.  This is undocumented and might
93967   ** change.  The only purpose is to provide an easy way to test
93968   ** the sqlite3AbsInt32() function.
93969   **
93970   **  PRAGMA [database.]page_count
93971   **
93972   ** Return the number of pages in the specified database.
93973   */
93974   if( sqlite3StrICmp(zLeft,"page_count")==0
93975    || sqlite3StrICmp(zLeft,"max_page_count")==0
93976   ){
93977     int iReg;
93978     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93979     sqlite3CodeVerifySchema(pParse, iDb);
93980     iReg = ++pParse->nMem;
93981     if( sqlite3Tolower(zLeft[0])=='p' ){
93982       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
93983     }else{
93984       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
93985                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
93986     }
93987     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
93988     sqlite3VdbeSetNumCols(v, 1);
93989     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93990   }else
93991
93992   /*
93993   **  PRAGMA [database.]locking_mode
93994   **  PRAGMA [database.]locking_mode = (normal|exclusive)
93995   */
93996   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
93997     const char *zRet = "normal";
93998     int eMode = getLockingMode(zRight);
93999
94000     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
94001       /* Simple "PRAGMA locking_mode;" statement. This is a query for
94002       ** the current default locking mode (which may be different to
94003       ** the locking-mode of the main database).
94004       */
94005       eMode = db->dfltLockMode;
94006     }else{
94007       Pager *pPager;
94008       if( pId2->n==0 ){
94009         /* This indicates that no database name was specified as part
94010         ** of the PRAGMA command. In this case the locking-mode must be
94011         ** set on all attached databases, as well as the main db file.
94012         **
94013         ** Also, the sqlite3.dfltLockMode variable is set so that
94014         ** any subsequently attached databases also use the specified
94015         ** locking mode.
94016         */
94017         int ii;
94018         assert(pDb==&db->aDb[0]);
94019         for(ii=2; ii<db->nDb; ii++){
94020           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
94021           sqlite3PagerLockingMode(pPager, eMode);
94022         }
94023         db->dfltLockMode = (u8)eMode;
94024       }
94025       pPager = sqlite3BtreePager(pDb->pBt);
94026       eMode = sqlite3PagerLockingMode(pPager, eMode);
94027     }
94028
94029     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
94030     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
94031       zRet = "exclusive";
94032     }
94033     sqlite3VdbeSetNumCols(v, 1);
94034     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
94035     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
94036     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94037   }else
94038
94039   /*
94040   **  PRAGMA [database.]journal_mode
94041   **  PRAGMA [database.]journal_mode =
94042   **                      (delete|persist|off|truncate|memory|wal|off)
94043   */
94044   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
94045     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
94046     int ii;           /* Loop counter */
94047
94048     /* Force the schema to be loaded on all databases.  This causes all
94049     ** database files to be opened and the journal_modes set.  This is
94050     ** necessary because subsequent processing must know if the databases
94051     ** are in WAL mode. */
94052     if( sqlite3ReadSchema(pParse) ){
94053       goto pragma_out;
94054     }
94055
94056     sqlite3VdbeSetNumCols(v, 1);
94057     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
94058
94059     if( zRight==0 ){
94060       /* If there is no "=MODE" part of the pragma, do a query for the
94061       ** current mode */
94062       eMode = PAGER_JOURNALMODE_QUERY;
94063     }else{
94064       const char *zMode;
94065       int n = sqlite3Strlen30(zRight);
94066       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
94067         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
94068       }
94069       if( !zMode ){
94070         /* If the "=MODE" part does not match any known journal mode,
94071         ** then do a query */
94072         eMode = PAGER_JOURNALMODE_QUERY;
94073       }
94074     }
94075     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
94076       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
94077       iDb = 0;
94078       pId2->n = 1;
94079     }
94080     for(ii=db->nDb-1; ii>=0; ii--){
94081       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
94082         sqlite3VdbeUsesBtree(v, ii);
94083         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
94084       }
94085     }
94086     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94087   }else
94088
94089   /*
94090   **  PRAGMA [database.]journal_size_limit
94091   **  PRAGMA [database.]journal_size_limit=N
94092   **
94093   ** Get or set the size limit on rollback journal files.
94094   */
94095   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
94096     Pager *pPager = sqlite3BtreePager(pDb->pBt);
94097     i64 iLimit = -2;
94098     if( zRight ){
94099       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
94100       if( iLimit<-1 ) iLimit = -1;
94101     }
94102     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
94103     returnSingleInt(pParse, "journal_size_limit", iLimit);
94104   }else
94105
94106 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94107
94108   /*
94109   **  PRAGMA [database.]auto_vacuum
94110   **  PRAGMA [database.]auto_vacuum=N
94111   **
94112   ** Get or set the value of the database 'auto-vacuum' parameter.
94113   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
94114   */
94115 #ifndef SQLITE_OMIT_AUTOVACUUM
94116   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
94117     Btree *pBt = pDb->pBt;
94118     assert( pBt!=0 );
94119     if( sqlite3ReadSchema(pParse) ){
94120       goto pragma_out;
94121     }
94122     if( !zRight ){
94123       int auto_vacuum;
94124       if( ALWAYS(pBt) ){
94125          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
94126       }else{
94127          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
94128       }
94129       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
94130     }else{
94131       int eAuto = getAutoVacuum(zRight);
94132       assert( eAuto>=0 && eAuto<=2 );
94133       db->nextAutovac = (u8)eAuto;
94134       if( ALWAYS(eAuto>=0) ){
94135         /* Call SetAutoVacuum() to set initialize the internal auto and
94136         ** incr-vacuum flags. This is required in case this connection
94137         ** creates the database file. It is important that it is created
94138         ** as an auto-vacuum capable db.
94139         */
94140         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
94141         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
94142           /* When setting the auto_vacuum mode to either "full" or
94143           ** "incremental", write the value of meta[6] in the database
94144           ** file. Before writing to meta[6], check that meta[3] indicates
94145           ** that this really is an auto-vacuum capable database.
94146           */
94147           static const VdbeOpList setMeta6[] = {
94148             { OP_Transaction,    0,         1,                 0},    /* 0 */
94149             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
94150             { OP_If,             1,         0,                 0},    /* 2 */
94151             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
94152             { OP_Integer,        0,         1,                 0},    /* 4 */
94153             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
94154           };
94155           int iAddr;
94156           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
94157           sqlite3VdbeChangeP1(v, iAddr, iDb);
94158           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
94159           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
94160           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
94161           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
94162           sqlite3VdbeUsesBtree(v, iDb);
94163         }
94164       }
94165     }
94166   }else
94167 #endif
94168
94169   /*
94170   **  PRAGMA [database.]incremental_vacuum(N)
94171   **
94172   ** Do N steps of incremental vacuuming on a database.
94173   */
94174 #ifndef SQLITE_OMIT_AUTOVACUUM
94175   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
94176     int iLimit, addr;
94177     if( sqlite3ReadSchema(pParse) ){
94178       goto pragma_out;
94179     }
94180     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
94181       iLimit = 0x7fffffff;
94182     }
94183     sqlite3BeginWriteOperation(pParse, 0, iDb);
94184     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
94185     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
94186     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
94187     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
94188     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
94189     sqlite3VdbeJumpHere(v, addr);
94190   }else
94191 #endif
94192
94193 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
94194   /*
94195   **  PRAGMA [database.]cache_size
94196   **  PRAGMA [database.]cache_size=N
94197   **
94198   ** The first form reports the current local setting for the
94199   ** page cache size. The second form sets the local
94200   ** page cache size value.  If N is positive then that is the
94201   ** number of pages in the cache.  If N is negative, then the
94202   ** number of pages is adjusted so that the cache uses -N kibibytes
94203   ** of memory.
94204   */
94205   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
94206     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94207     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94208     if( !zRight ){
94209       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
94210     }else{
94211       int size = sqlite3Atoi(zRight);
94212       pDb->pSchema->cache_size = size;
94213       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
94214     }
94215   }else
94216
94217   /*
94218   **   PRAGMA temp_store
94219   **   PRAGMA temp_store = "default"|"memory"|"file"
94220   **
94221   ** Return or set the local value of the temp_store flag.  Changing
94222   ** the local value does not make changes to the disk file and the default
94223   ** value will be restored the next time the database is opened.
94224   **
94225   ** Note that it is possible for the library compile-time options to
94226   ** override this setting
94227   */
94228   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
94229     if( !zRight ){
94230       returnSingleInt(pParse, "temp_store", db->temp_store);
94231     }else{
94232       changeTempStorage(pParse, zRight);
94233     }
94234   }else
94235
94236   /*
94237   **   PRAGMA temp_store_directory
94238   **   PRAGMA temp_store_directory = ""|"directory_name"
94239   **
94240   ** Return or set the local value of the temp_store_directory flag.  Changing
94241   ** the value sets a specific directory to be used for temporary files.
94242   ** Setting to a null string reverts to the default temporary directory search.
94243   ** If temporary directory is changed, then invalidateTempStorage.
94244   **
94245   */
94246   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
94247     if( !zRight ){
94248       if( sqlite3_temp_directory ){
94249         sqlite3VdbeSetNumCols(v, 1);
94250         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94251             "temp_store_directory", SQLITE_STATIC);
94252         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
94253         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94254       }
94255     }else{
94256 #ifndef SQLITE_OMIT_WSD
94257       if( zRight[0] ){
94258         int res;
94259         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94260         if( rc!=SQLITE_OK || res==0 ){
94261           sqlite3ErrorMsg(pParse, "not a writable directory");
94262           goto pragma_out;
94263         }
94264       }
94265       if( SQLITE_TEMP_STORE==0
94266        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
94267        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
94268       ){
94269         invalidateTempStorage(pParse);
94270       }
94271       sqlite3_free(sqlite3_temp_directory);
94272       if( zRight[0] ){
94273         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
94274       }else{
94275         sqlite3_temp_directory = 0;
94276       }
94277 #endif /* SQLITE_OMIT_WSD */
94278     }
94279   }else
94280
94281 #if SQLITE_OS_WIN
94282   /*
94283   **   PRAGMA data_store_directory
94284   **   PRAGMA data_store_directory = ""|"directory_name"
94285   **
94286   ** Return or set the local value of the data_store_directory flag.  Changing
94287   ** the value sets a specific directory to be used for database files that
94288   ** were specified with a relative pathname.  Setting to a null string reverts
94289   ** to the default database directory, which for database files specified with
94290   ** a relative path will probably be based on the current directory for the
94291   ** process.  Database file specified with an absolute path are not impacted
94292   ** by this setting, regardless of its value.
94293   **
94294   */
94295   if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
94296     if( !zRight ){
94297       if( sqlite3_data_directory ){
94298         sqlite3VdbeSetNumCols(v, 1);
94299         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94300             "data_store_directory", SQLITE_STATIC);
94301         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
94302         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94303       }
94304     }else{
94305 #ifndef SQLITE_OMIT_WSD
94306       if( zRight[0] ){
94307         int res;
94308         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94309         if( rc!=SQLITE_OK || res==0 ){
94310           sqlite3ErrorMsg(pParse, "not a writable directory");
94311           goto pragma_out;
94312         }
94313       }
94314       sqlite3_free(sqlite3_data_directory);
94315       if( zRight[0] ){
94316         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
94317       }else{
94318         sqlite3_data_directory = 0;
94319       }
94320 #endif /* SQLITE_OMIT_WSD */
94321     }
94322   }else
94323 #endif
94324
94325 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
94326 #  if defined(__APPLE__)
94327 #    define SQLITE_ENABLE_LOCKING_STYLE 1
94328 #  else
94329 #    define SQLITE_ENABLE_LOCKING_STYLE 0
94330 #  endif
94331 #endif
94332 #if SQLITE_ENABLE_LOCKING_STYLE
94333   /*
94334    **   PRAGMA [database.]lock_proxy_file
94335    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
94336    **
94337    ** Return or set the value of the lock_proxy_file flag.  Changing
94338    ** the value sets a specific file to be used for database access locks.
94339    **
94340    */
94341   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
94342     if( !zRight ){
94343       Pager *pPager = sqlite3BtreePager(pDb->pBt);
94344       char *proxy_file_path = NULL;
94345       sqlite3_file *pFile = sqlite3PagerFile(pPager);
94346       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
94347                            &proxy_file_path);
94348
94349       if( proxy_file_path ){
94350         sqlite3VdbeSetNumCols(v, 1);
94351         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
94352                               "lock_proxy_file", SQLITE_STATIC);
94353         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
94354         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94355       }
94356     }else{
94357       Pager *pPager = sqlite3BtreePager(pDb->pBt);
94358       sqlite3_file *pFile = sqlite3PagerFile(pPager);
94359       int res;
94360       if( zRight[0] ){
94361         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
94362                                      zRight);
94363       } else {
94364         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
94365                                      NULL);
94366       }
94367       if( res!=SQLITE_OK ){
94368         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
94369         goto pragma_out;
94370       }
94371     }
94372   }else
94373 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
94374
94375   /*
94376   **   PRAGMA [database.]synchronous
94377   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
94378   **
94379   ** Return or set the local value of the synchronous flag.  Changing
94380   ** the local value does not make changes to the disk file and the
94381   ** default value will be restored the next time the database is
94382   ** opened.
94383   */
94384   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
94385     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94386     if( !zRight ){
94387       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
94388     }else{
94389       if( !db->autoCommit ){
94390         sqlite3ErrorMsg(pParse,
94391             "Safety level may not be changed inside a transaction");
94392       }else{
94393         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
94394       }
94395     }
94396   }else
94397 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94398
94399 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
94400   if( flagPragma(pParse, zLeft, zRight) ){
94401     /* The flagPragma() subroutine also generates any necessary code
94402     ** there is nothing more to do here */
94403   }else
94404 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
94405
94406 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
94407   /*
94408   **   PRAGMA table_info(<table>)
94409   **
94410   ** Return a single row for each column of the named table. The columns of
94411   ** the returned data set are:
94412   **
94413   ** cid:        Column id (numbered from left to right, starting at 0)
94414   ** name:       Column name
94415   ** type:       Column declaration type.
94416   ** notnull:    True if 'NOT NULL' is part of column declaration
94417   ** dflt_value: The default value for the column, if any.
94418   */
94419   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
94420     Table *pTab;
94421     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94422     pTab = sqlite3FindTable(db, zRight, zDb);
94423     if( pTab ){
94424       int i;
94425       int nHidden = 0;
94426       Column *pCol;
94427       sqlite3VdbeSetNumCols(v, 6);
94428       pParse->nMem = 6;
94429       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
94430       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94431       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
94432       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
94433       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
94434       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
94435       sqlite3ViewGetColumnNames(pParse, pTab);
94436       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
94437         if( IsHiddenColumn(pCol) ){
94438           nHidden++;
94439           continue;
94440         }
94441         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
94442         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
94443         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94444            pCol->zType ? pCol->zType : "", 0);
94445         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
94446         if( pCol->zDflt ){
94447           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
94448         }else{
94449           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
94450         }
94451         sqlite3VdbeAddOp2(v, OP_Integer,
94452                             (pCol->colFlags&COLFLAG_PRIMKEY)!=0, 6);
94453         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
94454       }
94455     }
94456   }else
94457
94458   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
94459     Index *pIdx;
94460     Table *pTab;
94461     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94462     pIdx = sqlite3FindIndex(db, zRight, zDb);
94463     if( pIdx ){
94464       int i;
94465       pTab = pIdx->pTable;
94466       sqlite3VdbeSetNumCols(v, 3);
94467       pParse->nMem = 3;
94468       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
94469       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
94470       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
94471       for(i=0; i<pIdx->nColumn; i++){
94472         int cnum = pIdx->aiColumn[i];
94473         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94474         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
94475         assert( pTab->nCol>cnum );
94476         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
94477         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94478       }
94479     }
94480   }else
94481
94482   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
94483     Index *pIdx;
94484     Table *pTab;
94485     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94486     pTab = sqlite3FindTable(db, zRight, zDb);
94487     if( pTab ){
94488       v = sqlite3GetVdbe(pParse);
94489       pIdx = pTab->pIndex;
94490       if( pIdx ){
94491         int i = 0;
94492         sqlite3VdbeSetNumCols(v, 3);
94493         pParse->nMem = 3;
94494         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94495         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94496         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
94497         while(pIdx){
94498           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94499           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
94500           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
94501           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94502           ++i;
94503           pIdx = pIdx->pNext;
94504         }
94505       }
94506     }
94507   }else
94508
94509   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
94510     int i;
94511     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94512     sqlite3VdbeSetNumCols(v, 3);
94513     pParse->nMem = 3;
94514     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94515     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94516     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
94517     for(i=0; i<db->nDb; i++){
94518       if( db->aDb[i].pBt==0 ) continue;
94519       assert( db->aDb[i].zName!=0 );
94520       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94521       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
94522       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94523            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
94524       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94525     }
94526   }else
94527
94528   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
94529     int i = 0;
94530     HashElem *p;
94531     sqlite3VdbeSetNumCols(v, 2);
94532     pParse->nMem = 2;
94533     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94534     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94535     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
94536       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
94537       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
94538       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
94539       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
94540     }
94541   }else
94542 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
94543
94544 #ifndef SQLITE_OMIT_FOREIGN_KEY
94545   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
94546     FKey *pFK;
94547     Table *pTab;
94548     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94549     pTab = sqlite3FindTable(db, zRight, zDb);
94550     if( pTab ){
94551       v = sqlite3GetVdbe(pParse);
94552       pFK = pTab->pFKey;
94553       if( pFK ){
94554         int i = 0;
94555         sqlite3VdbeSetNumCols(v, 8);
94556         pParse->nMem = 8;
94557         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
94558         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
94559         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
94560         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
94561         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
94562         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
94563         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
94564         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
94565         while(pFK){
94566           int j;
94567           for(j=0; j<pFK->nCol; j++){
94568             char *zCol = pFK->aCol[j].zCol;
94569             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
94570             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
94571             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94572             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
94573             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
94574             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
94575                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
94576             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
94577             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
94578             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
94579             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
94580             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
94581           }
94582           ++i;
94583           pFK = pFK->pNextFrom;
94584         }
94585       }
94586     }
94587   }else
94588 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
94589
94590 #ifndef NDEBUG
94591   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
94592     if( zRight ){
94593       if( sqlite3GetBoolean(zRight, 0) ){
94594         sqlite3ParserTrace(stderr, "parser: ");
94595       }else{
94596         sqlite3ParserTrace(0, 0);
94597       }
94598     }
94599   }else
94600 #endif
94601
94602   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
94603   ** used will be case sensitive or not depending on the RHS.
94604   */
94605   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
94606     if( zRight ){
94607       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
94608     }
94609   }else
94610
94611 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
94612 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
94613 #endif
94614
94615 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
94616   /* Pragma "quick_check" is an experimental reduced version of
94617   ** integrity_check designed to detect most database corruption
94618   ** without most of the overhead of a full integrity-check.
94619   */
94620   if( sqlite3StrICmp(zLeft, "integrity_check")==0
94621    || sqlite3StrICmp(zLeft, "quick_check")==0
94622   ){
94623     int i, j, addr, mxErr;
94624
94625     /* Code that appears at the end of the integrity check.  If no error
94626     ** messages have been generated, output OK.  Otherwise output the
94627     ** error message
94628     */
94629     static const VdbeOpList endCode[] = {
94630       { OP_AddImm,      1, 0,        0},    /* 0 */
94631       { OP_IfNeg,       1, 0,        0},    /* 1 */
94632       { OP_String8,     0, 3,        0},    /* 2 */
94633       { OP_ResultRow,   3, 1,        0},
94634     };
94635
94636     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
94637
94638     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
94639     ** then iDb is set to the index of the database identified by <db>.
94640     ** In this case, the integrity of database iDb only is verified by
94641     ** the VDBE created below.
94642     **
94643     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
94644     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
94645     ** to -1 here, to indicate that the VDBE should verify the integrity
94646     ** of all attached databases.  */
94647     assert( iDb>=0 );
94648     assert( iDb==0 || pId2->z );
94649     if( pId2->z==0 ) iDb = -1;
94650
94651     /* Initialize the VDBE program */
94652     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94653     pParse->nMem = 6;
94654     sqlite3VdbeSetNumCols(v, 1);
94655     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
94656
94657     /* Set the maximum error count */
94658     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94659     if( zRight ){
94660       sqlite3GetInt32(zRight, &mxErr);
94661       if( mxErr<=0 ){
94662         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94663       }
94664     }
94665     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
94666
94667     /* Do an integrity check on each database file */
94668     for(i=0; i<db->nDb; i++){
94669       HashElem *x;
94670       Hash *pTbls;
94671       int cnt = 0;
94672
94673       if( OMIT_TEMPDB && i==1 ) continue;
94674       if( iDb>=0 && i!=iDb ) continue;
94675
94676       sqlite3CodeVerifySchema(pParse, i);
94677       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
94678       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94679       sqlite3VdbeJumpHere(v, addr);
94680
94681       /* Do an integrity check of the B-Tree
94682       **
94683       ** Begin by filling registers 2, 3, ... with the root pages numbers
94684       ** for all tables and indices in the database.
94685       */
94686       assert( sqlite3SchemaMutexHeld(db, i, 0) );
94687       pTbls = &db->aDb[i].pSchema->tblHash;
94688       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
94689         Table *pTab = sqliteHashData(x);
94690         Index *pIdx;
94691         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
94692         cnt++;
94693         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94694           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
94695           cnt++;
94696         }
94697       }
94698
94699       /* Make sure sufficient number of registers have been allocated */
94700       if( pParse->nMem < cnt+4 ){
94701         pParse->nMem = cnt+4;
94702       }
94703
94704       /* Do the b-tree integrity checks */
94705       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
94706       sqlite3VdbeChangeP5(v, (u8)i);
94707       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
94708       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94709          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
94710          P4_DYNAMIC);
94711       sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
94712       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
94713       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
94714       sqlite3VdbeJumpHere(v, addr);
94715
94716       /* Make sure all the indices are constructed correctly.
94717       */
94718       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
94719         Table *pTab = sqliteHashData(x);
94720         Index *pIdx;
94721         int loopTop;
94722
94723         if( pTab->pIndex==0 ) continue;
94724         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
94725         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94726         sqlite3VdbeJumpHere(v, addr);
94727         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
94728         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
94729         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
94730         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
94731         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94732           int jmp2;
94733           int r1;
94734           static const VdbeOpList idxErr[] = {
94735             { OP_AddImm,      1, -1,  0},
94736             { OP_String8,     0,  3,  0},    /* 1 */
94737             { OP_Rowid,       1,  4,  0},
94738             { OP_String8,     0,  5,  0},    /* 3 */
94739             { OP_String8,     0,  6,  0},    /* 4 */
94740             { OP_Concat,      4,  3,  3},
94741             { OP_Concat,      5,  3,  3},
94742             { OP_Concat,      6,  3,  3},
94743             { OP_ResultRow,   3,  1,  0},
94744             { OP_IfPos,       1,  0,  0},    /* 9 */
94745             { OP_Halt,        0,  0,  0},
94746           };
94747           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
94748           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
94749           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
94750           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
94751           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
94752           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
94753           sqlite3VdbeJumpHere(v, addr+9);
94754           sqlite3VdbeJumpHere(v, jmp2);
94755         }
94756         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
94757         sqlite3VdbeJumpHere(v, loopTop);
94758         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94759           static const VdbeOpList cntIdx[] = {
94760              { OP_Integer,      0,  3,  0},
94761              { OP_Rewind,       0,  0,  0},  /* 1 */
94762              { OP_AddImm,       3,  1,  0},
94763              { OP_Next,         0,  0,  0},  /* 3 */
94764              { OP_Eq,           2,  0,  3},  /* 4 */
94765              { OP_AddImm,       1, -1,  0},
94766              { OP_String8,      0,  2,  0},  /* 6 */
94767              { OP_String8,      0,  3,  0},  /* 7 */
94768              { OP_Concat,       3,  2,  2},
94769              { OP_ResultRow,    2,  1,  0},
94770           };
94771           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
94772           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94773           sqlite3VdbeJumpHere(v, addr);
94774           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
94775           sqlite3VdbeChangeP1(v, addr+1, j+2);
94776           sqlite3VdbeChangeP2(v, addr+1, addr+4);
94777           sqlite3VdbeChangeP1(v, addr+3, j+2);
94778           sqlite3VdbeChangeP2(v, addr+3, addr+2);
94779           sqlite3VdbeJumpHere(v, addr+4);
94780           sqlite3VdbeChangeP4(v, addr+6,
94781                      "wrong # of entries in index ", P4_STATIC);
94782           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
94783         }
94784       }
94785     }
94786     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
94787     sqlite3VdbeChangeP2(v, addr, -mxErr);
94788     sqlite3VdbeJumpHere(v, addr+1);
94789     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
94790   }else
94791 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
94792
94793 #ifndef SQLITE_OMIT_UTF16
94794   /*
94795   **   PRAGMA encoding
94796   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
94797   **
94798   ** In its first form, this pragma returns the encoding of the main
94799   ** database. If the database is not initialized, it is initialized now.
94800   **
94801   ** The second form of this pragma is a no-op if the main database file
94802   ** has not already been initialized. In this case it sets the default
94803   ** encoding that will be used for the main database file if a new file
94804   ** is created. If an existing main database file is opened, then the
94805   ** default text encoding for the existing database is used.
94806   **
94807   ** In all cases new databases created using the ATTACH command are
94808   ** created to use the same default text encoding as the main database. If
94809   ** the main database has not been initialized and/or created when ATTACH
94810   ** is executed, this is done before the ATTACH operation.
94811   **
94812   ** In the second form this pragma sets the text encoding to be used in
94813   ** new database files created using this database handle. It is only
94814   ** useful if invoked immediately after the main database i
94815   */
94816   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
94817     static const struct EncName {
94818       char *zName;
94819       u8 enc;
94820     } encnames[] = {
94821       { "UTF8",     SQLITE_UTF8        },
94822       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
94823       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
94824       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
94825       { "UTF16le",  SQLITE_UTF16LE     },
94826       { "UTF16be",  SQLITE_UTF16BE     },
94827       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
94828       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
94829       { 0, 0 }
94830     };
94831     const struct EncName *pEnc;
94832     if( !zRight ){    /* "PRAGMA encoding" */
94833       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94834       sqlite3VdbeSetNumCols(v, 1);
94835       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
94836       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
94837       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
94838       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
94839       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
94840       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
94841       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94842     }else{                        /* "PRAGMA encoding = XXX" */
94843       /* Only change the value of sqlite.enc if the database handle is not
94844       ** initialized. If the main database exists, the new sqlite.enc value
94845       ** will be overwritten when the schema is next loaded. If it does not
94846       ** already exists, it will be created to use the new encoding value.
94847       */
94848       if(
94849         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
94850         DbHasProperty(db, 0, DB_Empty)
94851       ){
94852         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
94853           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
94854             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
94855             break;
94856           }
94857         }
94858         if( !pEnc->zName ){
94859           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
94860         }
94861       }
94862     }
94863   }else
94864 #endif /* SQLITE_OMIT_UTF16 */
94865
94866 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
94867   /*
94868   **   PRAGMA [database.]schema_version
94869   **   PRAGMA [database.]schema_version = <integer>
94870   **
94871   **   PRAGMA [database.]user_version
94872   **   PRAGMA [database.]user_version = <integer>
94873   **
94874   ** The pragma's schema_version and user_version are used to set or get
94875   ** the value of the schema-version and user-version, respectively. Both
94876   ** the schema-version and the user-version are 32-bit signed integers
94877   ** stored in the database header.
94878   **
94879   ** The schema-cookie is usually only manipulated internally by SQLite. It
94880   ** is incremented by SQLite whenever the database schema is modified (by
94881   ** creating or dropping a table or index). The schema version is used by
94882   ** SQLite each time a query is executed to ensure that the internal cache
94883   ** of the schema used when compiling the SQL query matches the schema of
94884   ** the database against which the compiled query is actually executed.
94885   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
94886   ** the schema-version is potentially dangerous and may lead to program
94887   ** crashes or database corruption. Use with caution!
94888   **
94889   ** The user-version is not used internally by SQLite. It may be used by
94890   ** applications for any purpose.
94891   */
94892   if( sqlite3StrICmp(zLeft, "schema_version")==0
94893    || sqlite3StrICmp(zLeft, "user_version")==0
94894    || sqlite3StrICmp(zLeft, "freelist_count")==0
94895   ){
94896     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
94897     sqlite3VdbeUsesBtree(v, iDb);
94898     switch( zLeft[0] ){
94899       case 'f': case 'F':
94900         iCookie = BTREE_FREE_PAGE_COUNT;
94901         break;
94902       case 's': case 'S':
94903         iCookie = BTREE_SCHEMA_VERSION;
94904         break;
94905       default:
94906         iCookie = BTREE_USER_VERSION;
94907         break;
94908     }
94909
94910     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
94911       /* Write the specified cookie value */
94912       static const VdbeOpList setCookie[] = {
94913         { OP_Transaction,    0,  1,  0},    /* 0 */
94914         { OP_Integer,        0,  1,  0},    /* 1 */
94915         { OP_SetCookie,      0,  0,  1},    /* 2 */
94916       };
94917       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
94918       sqlite3VdbeChangeP1(v, addr, iDb);
94919       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
94920       sqlite3VdbeChangeP1(v, addr+2, iDb);
94921       sqlite3VdbeChangeP2(v, addr+2, iCookie);
94922     }else{
94923       /* Read the specified cookie value */
94924       static const VdbeOpList readCookie[] = {
94925         { OP_Transaction,     0,  0,  0},    /* 0 */
94926         { OP_ReadCookie,      0,  1,  0},    /* 1 */
94927         { OP_ResultRow,       1,  1,  0}
94928       };
94929       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
94930       sqlite3VdbeChangeP1(v, addr, iDb);
94931       sqlite3VdbeChangeP1(v, addr+1, iDb);
94932       sqlite3VdbeChangeP3(v, addr+1, iCookie);
94933       sqlite3VdbeSetNumCols(v, 1);
94934       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
94935     }
94936   }else
94937 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
94938
94939 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
94940   /*
94941   **   PRAGMA compile_options
94942   **
94943   ** Return the names of all compile-time options used in this build,
94944   ** one option per row.
94945   */
94946   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
94947     int i = 0;
94948     const char *zOpt;
94949     sqlite3VdbeSetNumCols(v, 1);
94950     pParse->nMem = 1;
94951     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
94952     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
94953       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
94954       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94955     }
94956   }else
94957 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
94958
94959 #ifndef SQLITE_OMIT_WAL
94960   /*
94961   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
94962   **
94963   ** Checkpoint the database.
94964   */
94965   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
94966     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
94967     int eMode = SQLITE_CHECKPOINT_PASSIVE;
94968     if( zRight ){
94969       if( sqlite3StrICmp(zRight, "full")==0 ){
94970         eMode = SQLITE_CHECKPOINT_FULL;
94971       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
94972         eMode = SQLITE_CHECKPOINT_RESTART;
94973       }
94974     }
94975     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94976     sqlite3VdbeSetNumCols(v, 3);
94977     pParse->nMem = 3;
94978     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
94979     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
94980     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
94981
94982     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
94983     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94984   }else
94985
94986   /*
94987   **   PRAGMA wal_autocheckpoint
94988   **   PRAGMA wal_autocheckpoint = N
94989   **
94990   ** Configure a database connection to automatically checkpoint a database
94991   ** after accumulating N frames in the log. Or query for the current value
94992   ** of N.
94993   */
94994   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
94995     if( zRight ){
94996       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
94997     }
94998     returnSingleInt(pParse, "wal_autocheckpoint",
94999        db->xWalCallback==sqlite3WalDefaultHook ?
95000            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
95001   }else
95002 #endif
95003
95004   /*
95005   **  PRAGMA shrink_memory
95006   **
95007   ** This pragma attempts to free as much memory as possible from the
95008   ** current database connection.
95009   */
95010   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
95011     sqlite3_db_release_memory(db);
95012   }else
95013
95014   /*
95015   **   PRAGMA busy_timeout
95016   **   PRAGMA busy_timeout = N
95017   **
95018   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
95019   ** if one is set.  If no busy handler or a different busy handler is set
95020   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
95021   ** disables the timeout.
95022   */
95023   if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
95024     if( zRight ){
95025       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
95026     }
95027     returnSingleInt(pParse, "timeout",  db->busyTimeout);
95028   }else
95029
95030 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
95031   /*
95032   ** Report the current state of file logs for all databases
95033   */
95034   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
95035     static const char *const azLockName[] = {
95036       "unlocked", "shared", "reserved", "pending", "exclusive"
95037     };
95038     int i;
95039     sqlite3VdbeSetNumCols(v, 2);
95040     pParse->nMem = 2;
95041     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
95042     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
95043     for(i=0; i<db->nDb; i++){
95044       Btree *pBt;
95045       const char *zState = "unknown";
95046       int j;
95047       if( db->aDb[i].zName==0 ) continue;
95048       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
95049       pBt = db->aDb[i].pBt;
95050       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
95051         zState = "closed";
95052       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
95053                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
95054          zState = azLockName[j];
95055       }
95056       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
95057       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
95058     }
95059
95060   }else
95061 #endif
95062
95063 #ifdef SQLITE_HAS_CODEC
95064   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95065     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
95066   }else
95067   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95068     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
95069   }else
95070   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
95071                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
95072     int i, h1, h2;
95073     char zKey[40];
95074     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
95075       h1 += 9*(1&(h1>>6));
95076       h2 += 9*(1&(h2>>6));
95077       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
95078     }
95079     if( (zLeft[3] & 0xf)==0xb ){
95080       sqlite3_key(db, zKey, i/2);
95081     }else{
95082       sqlite3_rekey(db, zKey, i/2);
95083     }
95084   }else
95085 #endif
95086 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
95087   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
95088 #ifdef SQLITE_HAS_CODEC
95089     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
95090       sqlite3_activate_see(&zRight[4]);
95091     }
95092 #endif
95093 #ifdef SQLITE_ENABLE_CEROD
95094     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
95095       sqlite3_activate_cerod(&zRight[6]);
95096     }
95097 #endif
95098   }else
95099 #endif
95100
95101
95102   {/* Empty ELSE clause */}
95103
95104   /*
95105   ** Reset the safety level, in case the fullfsync flag or synchronous
95106   ** setting changed.
95107   */
95108 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
95109   if( db->autoCommit ){
95110     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
95111                (db->flags&SQLITE_FullFSync)!=0,
95112                (db->flags&SQLITE_CkptFullFSync)!=0);
95113   }
95114 #endif
95115 pragma_out:
95116   sqlite3DbFree(db, zLeft);
95117   sqlite3DbFree(db, zRight);
95118 }
95119
95120 #endif /* SQLITE_OMIT_PRAGMA */
95121
95122 /************** End of pragma.c **********************************************/
95123 /************** Begin file prepare.c *****************************************/
95124 /*
95125 ** 2005 May 25
95126 **
95127 ** The author disclaims copyright to this source code.  In place of
95128 ** a legal notice, here is a blessing:
95129 **
95130 **    May you do good and not evil.
95131 **    May you find forgiveness for yourself and forgive others.
95132 **    May you share freely, never taking more than you give.
95133 **
95134 *************************************************************************
95135 ** This file contains the implementation of the sqlite3_prepare()
95136 ** interface, and routines that contribute to loading the database schema
95137 ** from disk.
95138 */
95139
95140 /*
95141 ** Fill the InitData structure with an error message that indicates
95142 ** that the database is corrupt.
95143 */
95144 static void corruptSchema(
95145   InitData *pData,     /* Initialization context */
95146   const char *zObj,    /* Object being parsed at the point of error */
95147   const char *zExtra   /* Error information */
95148 ){
95149   sqlite3 *db = pData->db;
95150   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
95151     if( zObj==0 ) zObj = "?";
95152     sqlite3SetString(pData->pzErrMsg, db,
95153       "malformed database schema (%s)", zObj);
95154     if( zExtra ){
95155       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
95156                                  "%s - %s", *pData->pzErrMsg, zExtra);
95157     }
95158   }
95159   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
95160 }
95161
95162 /*
95163 ** This is the callback routine for the code that initializes the
95164 ** database.  See sqlite3Init() below for additional information.
95165 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
95166 **
95167 ** Each callback contains the following information:
95168 **
95169 **     argv[0] = name of thing being created
95170 **     argv[1] = root page number for table or index. 0 for trigger or view.
95171 **     argv[2] = SQL text for the CREATE statement.
95172 **
95173 */
95174 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
95175   InitData *pData = (InitData*)pInit;
95176   sqlite3 *db = pData->db;
95177   int iDb = pData->iDb;
95178
95179   assert( argc==3 );
95180   UNUSED_PARAMETER2(NotUsed, argc);
95181   assert( sqlite3_mutex_held(db->mutex) );
95182   DbClearProperty(db, iDb, DB_Empty);
95183   if( db->mallocFailed ){
95184     corruptSchema(pData, argv[0], 0);
95185     return 1;
95186   }
95187
95188   assert( iDb>=0 && iDb<db->nDb );
95189   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
95190   if( argv[1]==0 ){
95191     corruptSchema(pData, argv[0], 0);
95192   }else if( argv[2] && argv[2][0] ){
95193     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
95194     ** But because db->init.busy is set to 1, no VDBE code is generated
95195     ** or executed.  All the parser does is build the internal data
95196     ** structures that describe the table, index, or view.
95197     */
95198     int rc;
95199     sqlite3_stmt *pStmt;
95200     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
95201
95202     assert( db->init.busy );
95203     db->init.iDb = iDb;
95204     db->init.newTnum = sqlite3Atoi(argv[1]);
95205     db->init.orphanTrigger = 0;
95206     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
95207     rc = db->errCode;
95208     assert( (rc&0xFF)==(rcp&0xFF) );
95209     db->init.iDb = 0;
95210     if( SQLITE_OK!=rc ){
95211       if( db->init.orphanTrigger ){
95212         assert( iDb==1 );
95213       }else{
95214         pData->rc = rc;
95215         if( rc==SQLITE_NOMEM ){
95216           db->mallocFailed = 1;
95217         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
95218           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
95219         }
95220       }
95221     }
95222     sqlite3_finalize(pStmt);
95223   }else if( argv[0]==0 ){
95224     corruptSchema(pData, 0, 0);
95225   }else{
95226     /* If the SQL column is blank it means this is an index that
95227     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
95228     ** constraint for a CREATE TABLE.  The index should have already
95229     ** been created when we processed the CREATE TABLE.  All we have
95230     ** to do here is record the root page number for that index.
95231     */
95232     Index *pIndex;
95233     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
95234     if( pIndex==0 ){
95235       /* This can occur if there exists an index on a TEMP table which
95236       ** has the same name as another index on a permanent index.  Since
95237       ** the permanent table is hidden by the TEMP table, we can also
95238       ** safely ignore the index on the permanent table.
95239       */
95240       /* Do Nothing */;
95241     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
95242       corruptSchema(pData, argv[0], "invalid rootpage");
95243     }
95244   }
95245   return 0;
95246 }
95247
95248 /*
95249 ** Attempt to read the database schema and initialize internal
95250 ** data structures for a single database file.  The index of the
95251 ** database file is given by iDb.  iDb==0 is used for the main
95252 ** database.  iDb==1 should never be used.  iDb>=2 is used for
95253 ** auxiliary databases.  Return one of the SQLITE_ error codes to
95254 ** indicate success or failure.
95255 */
95256 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
95257   int rc;
95258   int i;
95259 #ifndef SQLITE_OMIT_DEPRECATED
95260   int size;
95261 #endif
95262   Table *pTab;
95263   Db *pDb;
95264   char const *azArg[4];
95265   int meta[5];
95266   InitData initData;
95267   char const *zMasterSchema;
95268   char const *zMasterName;
95269   int openedTransaction = 0;
95270
95271   /*
95272   ** The master database table has a structure like this
95273   */
95274   static const char master_schema[] =
95275      "CREATE TABLE sqlite_master(\n"
95276      "  type text,\n"
95277      "  name text,\n"
95278      "  tbl_name text,\n"
95279      "  rootpage integer,\n"
95280      "  sql text\n"
95281      ")"
95282   ;
95283 #ifndef SQLITE_OMIT_TEMPDB
95284   static const char temp_master_schema[] =
95285      "CREATE TEMP TABLE sqlite_temp_master(\n"
95286      "  type text,\n"
95287      "  name text,\n"
95288      "  tbl_name text,\n"
95289      "  rootpage integer,\n"
95290      "  sql text\n"
95291      ")"
95292   ;
95293 #else
95294   #define temp_master_schema 0
95295 #endif
95296
95297   assert( iDb>=0 && iDb<db->nDb );
95298   assert( db->aDb[iDb].pSchema );
95299   assert( sqlite3_mutex_held(db->mutex) );
95300   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
95301
95302   /* zMasterSchema and zInitScript are set to point at the master schema
95303   ** and initialisation script appropriate for the database being
95304   ** initialised. zMasterName is the name of the master table.
95305   */
95306   if( !OMIT_TEMPDB && iDb==1 ){
95307     zMasterSchema = temp_master_schema;
95308   }else{
95309     zMasterSchema = master_schema;
95310   }
95311   zMasterName = SCHEMA_TABLE(iDb);
95312
95313   /* Construct the schema tables.  */
95314   azArg[0] = zMasterName;
95315   azArg[1] = "1";
95316   azArg[2] = zMasterSchema;
95317   azArg[3] = 0;
95318   initData.db = db;
95319   initData.iDb = iDb;
95320   initData.rc = SQLITE_OK;
95321   initData.pzErrMsg = pzErrMsg;
95322   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
95323   if( initData.rc ){
95324     rc = initData.rc;
95325     goto error_out;
95326   }
95327   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
95328   if( ALWAYS(pTab) ){
95329     pTab->tabFlags |= TF_Readonly;
95330   }
95331
95332   /* Create a cursor to hold the database open
95333   */
95334   pDb = &db->aDb[iDb];
95335   if( pDb->pBt==0 ){
95336     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
95337       DbSetProperty(db, 1, DB_SchemaLoaded);
95338     }
95339     return SQLITE_OK;
95340   }
95341
95342   /* If there is not already a read-only (or read-write) transaction opened
95343   ** on the b-tree database, open one now. If a transaction is opened, it
95344   ** will be closed before this function returns.  */
95345   sqlite3BtreeEnter(pDb->pBt);
95346   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
95347     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
95348     if( rc!=SQLITE_OK ){
95349       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
95350       goto initone_error_out;
95351     }
95352     openedTransaction = 1;
95353   }
95354
95355   /* Get the database meta information.
95356   **
95357   ** Meta values are as follows:
95358   **    meta[0]   Schema cookie.  Changes with each schema change.
95359   **    meta[1]   File format of schema layer.
95360   **    meta[2]   Size of the page cache.
95361   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
95362   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
95363   **    meta[5]   User version
95364   **    meta[6]   Incremental vacuum mode
95365   **    meta[7]   unused
95366   **    meta[8]   unused
95367   **    meta[9]   unused
95368   **
95369   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
95370   ** the possible values of meta[4].
95371   */
95372   for(i=0; i<ArraySize(meta); i++){
95373     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
95374   }
95375   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
95376
95377   /* If opening a non-empty database, check the text encoding. For the
95378   ** main database, set sqlite3.enc to the encoding of the main database.
95379   ** For an attached db, it is an error if the encoding is not the same
95380   ** as sqlite3.enc.
95381   */
95382   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
95383     if( iDb==0 ){
95384       u8 encoding;
95385       /* If opening the main database, set ENC(db). */
95386       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
95387       if( encoding==0 ) encoding = SQLITE_UTF8;
95388       ENC(db) = encoding;
95389     }else{
95390       /* If opening an attached database, the encoding much match ENC(db) */
95391       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
95392         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
95393             " text encoding as main database");
95394         rc = SQLITE_ERROR;
95395         goto initone_error_out;
95396       }
95397     }
95398   }else{
95399     DbSetProperty(db, iDb, DB_Empty);
95400   }
95401   pDb->pSchema->enc = ENC(db);
95402
95403   if( pDb->pSchema->cache_size==0 ){
95404 #ifndef SQLITE_OMIT_DEPRECATED
95405     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
95406     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
95407     pDb->pSchema->cache_size = size;
95408 #else
95409     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
95410 #endif
95411     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
95412   }
95413
95414   /*
95415   ** file_format==1    Version 3.0.0.
95416   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
95417   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
95418   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
95419   */
95420   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
95421   if( pDb->pSchema->file_format==0 ){
95422     pDb->pSchema->file_format = 1;
95423   }
95424   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
95425     sqlite3SetString(pzErrMsg, db, "unsupported file format");
95426     rc = SQLITE_ERROR;
95427     goto initone_error_out;
95428   }
95429
95430   /* Ticket #2804:  When we open a database in the newer file format,
95431   ** clear the legacy_file_format pragma flag so that a VACUUM will
95432   ** not downgrade the database and thus invalidate any descending
95433   ** indices that the user might have created.
95434   */
95435   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
95436     db->flags &= ~SQLITE_LegacyFileFmt;
95437   }
95438
95439   /* Read the schema information out of the schema tables
95440   */
95441   assert( db->init.busy );
95442   {
95443     char *zSql;
95444     zSql = sqlite3MPrintf(db,
95445         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
95446         db->aDb[iDb].zName, zMasterName);
95447 #ifndef SQLITE_OMIT_AUTHORIZATION
95448     {
95449       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
95450       xAuth = db->xAuth;
95451       db->xAuth = 0;
95452 #endif
95453       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
95454 #ifndef SQLITE_OMIT_AUTHORIZATION
95455       db->xAuth = xAuth;
95456     }
95457 #endif
95458     if( rc==SQLITE_OK ) rc = initData.rc;
95459     sqlite3DbFree(db, zSql);
95460 #ifndef SQLITE_OMIT_ANALYZE
95461     if( rc==SQLITE_OK ){
95462       sqlite3AnalysisLoad(db, iDb);
95463     }
95464 #endif
95465   }
95466   if( db->mallocFailed ){
95467     rc = SQLITE_NOMEM;
95468     sqlite3ResetAllSchemasOfConnection(db);
95469   }
95470   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
95471     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
95472     ** the schema loaded, even if errors occurred. In this situation the
95473     ** current sqlite3_prepare() operation will fail, but the following one
95474     ** will attempt to compile the supplied statement against whatever subset
95475     ** of the schema was loaded before the error occurred. The primary
95476     ** purpose of this is to allow access to the sqlite_master table
95477     ** even when its contents have been corrupted.
95478     */
95479     DbSetProperty(db, iDb, DB_SchemaLoaded);
95480     rc = SQLITE_OK;
95481   }
95482
95483   /* Jump here for an error that occurs after successfully allocating
95484   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
95485   ** before that point, jump to error_out.
95486   */
95487 initone_error_out:
95488   if( openedTransaction ){
95489     sqlite3BtreeCommit(pDb->pBt);
95490   }
95491   sqlite3BtreeLeave(pDb->pBt);
95492
95493 error_out:
95494   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95495     db->mallocFailed = 1;
95496   }
95497   return rc;
95498 }
95499
95500 /*
95501 ** Initialize all database files - the main database file, the file
95502 ** used to store temporary tables, and any additional database files
95503 ** created using ATTACH statements.  Return a success code.  If an
95504 ** error occurs, write an error message into *pzErrMsg.
95505 **
95506 ** After a database is initialized, the DB_SchemaLoaded bit is set
95507 ** bit is set in the flags field of the Db structure. If the database
95508 ** file was of zero-length, then the DB_Empty flag is also set.
95509 */
95510 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
95511   int i, rc;
95512   int commit_internal = !(db->flags&SQLITE_InternChanges);
95513
95514   assert( sqlite3_mutex_held(db->mutex) );
95515   rc = SQLITE_OK;
95516   db->init.busy = 1;
95517   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
95518     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
95519     rc = sqlite3InitOne(db, i, pzErrMsg);
95520     if( rc ){
95521       sqlite3ResetOneSchema(db, i);
95522     }
95523   }
95524
95525   /* Once all the other databases have been initialised, load the schema
95526   ** for the TEMP database. This is loaded last, as the TEMP database
95527   ** schema may contain references to objects in other databases.
95528   */
95529 #ifndef SQLITE_OMIT_TEMPDB
95530   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
95531                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
95532     rc = sqlite3InitOne(db, 1, pzErrMsg);
95533     if( rc ){
95534       sqlite3ResetOneSchema(db, 1);
95535     }
95536   }
95537 #endif
95538
95539   db->init.busy = 0;
95540   if( rc==SQLITE_OK && commit_internal ){
95541     sqlite3CommitInternalChanges(db);
95542   }
95543
95544   return rc;
95545 }
95546
95547 /*
95548 ** This routine is a no-op if the database schema is already initialised.
95549 ** Otherwise, the schema is loaded. An error code is returned.
95550 */
95551 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
95552   int rc = SQLITE_OK;
95553   sqlite3 *db = pParse->db;
95554   assert( sqlite3_mutex_held(db->mutex) );
95555   if( !db->init.busy ){
95556     rc = sqlite3Init(db, &pParse->zErrMsg);
95557   }
95558   if( rc!=SQLITE_OK ){
95559     pParse->rc = rc;
95560     pParse->nErr++;
95561   }
95562   return rc;
95563 }
95564
95565
95566 /*
95567 ** Check schema cookies in all databases.  If any cookie is out
95568 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
95569 ** make no changes to pParse->rc.
95570 */
95571 static void schemaIsValid(Parse *pParse){
95572   sqlite3 *db = pParse->db;
95573   int iDb;
95574   int rc;
95575   int cookie;
95576
95577   assert( pParse->checkSchema );
95578   assert( sqlite3_mutex_held(db->mutex) );
95579   for(iDb=0; iDb<db->nDb; iDb++){
95580     int openedTransaction = 0;         /* True if a transaction is opened */
95581     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
95582     if( pBt==0 ) continue;
95583
95584     /* If there is not already a read-only (or read-write) transaction opened
95585     ** on the b-tree database, open one now. If a transaction is opened, it
95586     ** will be closed immediately after reading the meta-value. */
95587     if( !sqlite3BtreeIsInReadTrans(pBt) ){
95588       rc = sqlite3BtreeBeginTrans(pBt, 0);
95589       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95590         db->mallocFailed = 1;
95591       }
95592       if( rc!=SQLITE_OK ) return;
95593       openedTransaction = 1;
95594     }
95595
95596     /* Read the schema cookie from the database. If it does not match the
95597     ** value stored as part of the in-memory schema representation,
95598     ** set Parse.rc to SQLITE_SCHEMA. */
95599     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
95600     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95601     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
95602       sqlite3ResetOneSchema(db, iDb);
95603       pParse->rc = SQLITE_SCHEMA;
95604     }
95605
95606     /* Close the transaction, if one was opened. */
95607     if( openedTransaction ){
95608       sqlite3BtreeCommit(pBt);
95609     }
95610   }
95611 }
95612
95613 /*
95614 ** Convert a schema pointer into the iDb index that indicates
95615 ** which database file in db->aDb[] the schema refers to.
95616 **
95617 ** If the same database is attached more than once, the first
95618 ** attached database is returned.
95619 */
95620 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
95621   int i = -1000000;
95622
95623   /* If pSchema is NULL, then return -1000000. This happens when code in
95624   ** expr.c is trying to resolve a reference to a transient table (i.e. one
95625   ** created by a sub-select). In this case the return value of this
95626   ** function should never be used.
95627   **
95628   ** We return -1000000 instead of the more usual -1 simply because using
95629   ** -1000000 as the incorrect index into db->aDb[] is much
95630   ** more likely to cause a segfault than -1 (of course there are assert()
95631   ** statements too, but it never hurts to play the odds).
95632   */
95633   assert( sqlite3_mutex_held(db->mutex) );
95634   if( pSchema ){
95635     for(i=0; ALWAYS(i<db->nDb); i++){
95636       if( db->aDb[i].pSchema==pSchema ){
95637         break;
95638       }
95639     }
95640     assert( i>=0 && i<db->nDb );
95641   }
95642   return i;
95643 }
95644
95645 /*
95646 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
95647 */
95648 static int sqlite3Prepare(
95649   sqlite3 *db,              /* Database handle. */
95650   const char *zSql,         /* UTF-8 encoded SQL statement. */
95651   int nBytes,               /* Length of zSql in bytes. */
95652   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95653   Vdbe *pReprepare,         /* VM being reprepared */
95654   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95655   const char **pzTail       /* OUT: End of parsed string */
95656 ){
95657   Parse *pParse;            /* Parsing context */
95658   char *zErrMsg = 0;        /* Error message */
95659   int rc = SQLITE_OK;       /* Result code */
95660   int i;                    /* Loop counter */
95661
95662   /* Allocate the parsing context */
95663   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
95664   if( pParse==0 ){
95665     rc = SQLITE_NOMEM;
95666     goto end_prepare;
95667   }
95668   pParse->pReprepare = pReprepare;
95669   assert( ppStmt && *ppStmt==0 );
95670   assert( !db->mallocFailed );
95671   assert( sqlite3_mutex_held(db->mutex) );
95672
95673   /* Check to verify that it is possible to get a read lock on all
95674   ** database schemas.  The inability to get a read lock indicates that
95675   ** some other database connection is holding a write-lock, which in
95676   ** turn means that the other connection has made uncommitted changes
95677   ** to the schema.
95678   **
95679   ** Were we to proceed and prepare the statement against the uncommitted
95680   ** schema changes and if those schema changes are subsequently rolled
95681   ** back and different changes are made in their place, then when this
95682   ** prepared statement goes to run the schema cookie would fail to detect
95683   ** the schema change.  Disaster would follow.
95684   **
95685   ** This thread is currently holding mutexes on all Btrees (because
95686   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
95687   ** is not possible for another thread to start a new schema change
95688   ** while this routine is running.  Hence, we do not need to hold
95689   ** locks on the schema, we just need to make sure nobody else is
95690   ** holding them.
95691   **
95692   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
95693   ** but it does *not* override schema lock detection, so this all still
95694   ** works even if READ_UNCOMMITTED is set.
95695   */
95696   for(i=0; i<db->nDb; i++) {
95697     Btree *pBt = db->aDb[i].pBt;
95698     if( pBt ){
95699       assert( sqlite3BtreeHoldsMutex(pBt) );
95700       rc = sqlite3BtreeSchemaLocked(pBt);
95701       if( rc ){
95702         const char *zDb = db->aDb[i].zName;
95703         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
95704         testcase( db->flags & SQLITE_ReadUncommitted );
95705         goto end_prepare;
95706       }
95707     }
95708   }
95709
95710   sqlite3VtabUnlockList(db);
95711
95712   pParse->db = db;
95713   pParse->nQueryLoop = (double)1;
95714   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
95715     char *zSqlCopy;
95716     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95717     testcase( nBytes==mxLen );
95718     testcase( nBytes==mxLen+1 );
95719     if( nBytes>mxLen ){
95720       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
95721       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
95722       goto end_prepare;
95723     }
95724     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
95725     if( zSqlCopy ){
95726       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
95727       sqlite3DbFree(db, zSqlCopy);
95728       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
95729     }else{
95730       pParse->zTail = &zSql[nBytes];
95731     }
95732   }else{
95733     sqlite3RunParser(pParse, zSql, &zErrMsg);
95734   }
95735   assert( 1==(int)pParse->nQueryLoop );
95736
95737   if( db->mallocFailed ){
95738     pParse->rc = SQLITE_NOMEM;
95739   }
95740   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
95741   if( pParse->checkSchema ){
95742     schemaIsValid(pParse);
95743   }
95744   if( db->mallocFailed ){
95745     pParse->rc = SQLITE_NOMEM;
95746   }
95747   if( pzTail ){
95748     *pzTail = pParse->zTail;
95749   }
95750   rc = pParse->rc;
95751
95752 #ifndef SQLITE_OMIT_EXPLAIN
95753   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
95754     static const char * const azColName[] = {
95755        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
95756        "selectid", "order", "from", "detail"
95757     };
95758     int iFirst, mx;
95759     if( pParse->explain==2 ){
95760       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
95761       iFirst = 8;
95762       mx = 12;
95763     }else{
95764       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
95765       iFirst = 0;
95766       mx = 8;
95767     }
95768     for(i=iFirst; i<mx; i++){
95769       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
95770                             azColName[i], SQLITE_STATIC);
95771     }
95772   }
95773 #endif
95774
95775   assert( db->init.busy==0 || saveSqlFlag==0 );
95776   if( db->init.busy==0 ){
95777     Vdbe *pVdbe = pParse->pVdbe;
95778     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
95779   }
95780   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
95781     sqlite3VdbeFinalize(pParse->pVdbe);
95782     assert(!(*ppStmt));
95783   }else{
95784     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
95785   }
95786
95787   if( zErrMsg ){
95788     sqlite3Error(db, rc, "%s", zErrMsg);
95789     sqlite3DbFree(db, zErrMsg);
95790   }else{
95791     sqlite3Error(db, rc, 0);
95792   }
95793
95794   /* Delete any TriggerPrg structures allocated while parsing this statement. */
95795   while( pParse->pTriggerPrg ){
95796     TriggerPrg *pT = pParse->pTriggerPrg;
95797     pParse->pTriggerPrg = pT->pNext;
95798     sqlite3DbFree(db, pT);
95799   }
95800
95801 end_prepare:
95802
95803   sqlite3StackFree(db, pParse);
95804   rc = sqlite3ApiExit(db, rc);
95805   assert( (rc&db->errMask)==rc );
95806   return rc;
95807 }
95808 static int sqlite3LockAndPrepare(
95809   sqlite3 *db,              /* Database handle. */
95810   const char *zSql,         /* UTF-8 encoded SQL statement. */
95811   int nBytes,               /* Length of zSql in bytes. */
95812   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95813   Vdbe *pOld,               /* VM being reprepared */
95814   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95815   const char **pzTail       /* OUT: End of parsed string */
95816 ){
95817   int rc;
95818   assert( ppStmt!=0 );
95819   *ppStmt = 0;
95820   if( !sqlite3SafetyCheckOk(db) ){
95821     return SQLITE_MISUSE_BKPT;
95822   }
95823   sqlite3_mutex_enter(db->mutex);
95824   sqlite3BtreeEnterAll(db);
95825   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95826   if( rc==SQLITE_SCHEMA ){
95827     sqlite3_finalize(*ppStmt);
95828     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95829   }
95830   sqlite3BtreeLeaveAll(db);
95831   sqlite3_mutex_leave(db->mutex);
95832   assert( rc==SQLITE_OK || *ppStmt==0 );
95833   return rc;
95834 }
95835
95836 /*
95837 ** Rerun the compilation of a statement after a schema change.
95838 **
95839 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
95840 ** if the statement cannot be recompiled because another connection has
95841 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
95842 ** occurs, return SQLITE_SCHEMA.
95843 */
95844 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
95845   int rc;
95846   sqlite3_stmt *pNew;
95847   const char *zSql;
95848   sqlite3 *db;
95849
95850   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
95851   zSql = sqlite3_sql((sqlite3_stmt *)p);
95852   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
95853   db = sqlite3VdbeDb(p);
95854   assert( sqlite3_mutex_held(db->mutex) );
95855   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
95856   if( rc ){
95857     if( rc==SQLITE_NOMEM ){
95858       db->mallocFailed = 1;
95859     }
95860     assert( pNew==0 );
95861     return rc;
95862   }else{
95863     assert( pNew!=0 );
95864   }
95865   sqlite3VdbeSwap((Vdbe*)pNew, p);
95866   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
95867   sqlite3VdbeResetStepResult((Vdbe*)pNew);
95868   sqlite3VdbeFinalize((Vdbe*)pNew);
95869   return SQLITE_OK;
95870 }
95871
95872
95873 /*
95874 ** Two versions of the official API.  Legacy and new use.  In the legacy
95875 ** version, the original SQL text is not saved in the prepared statement
95876 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
95877 ** sqlite3_step().  In the new version, the original SQL text is retained
95878 ** and the statement is automatically recompiled if an schema change
95879 ** occurs.
95880 */
95881 SQLITE_API int sqlite3_prepare(
95882   sqlite3 *db,              /* Database handle. */
95883   const char *zSql,         /* UTF-8 encoded SQL statement. */
95884   int nBytes,               /* Length of zSql in bytes. */
95885   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95886   const char **pzTail       /* OUT: End of parsed string */
95887 ){
95888   int rc;
95889   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
95890   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95891   return rc;
95892 }
95893 SQLITE_API int sqlite3_prepare_v2(
95894   sqlite3 *db,              /* Database handle. */
95895   const char *zSql,         /* UTF-8 encoded SQL statement. */
95896   int nBytes,               /* Length of zSql in bytes. */
95897   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95898   const char **pzTail       /* OUT: End of parsed string */
95899 ){
95900   int rc;
95901   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
95902   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95903   return rc;
95904 }
95905
95906
95907 #ifndef SQLITE_OMIT_UTF16
95908 /*
95909 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
95910 */
95911 static int sqlite3Prepare16(
95912   sqlite3 *db,              /* Database handle. */
95913   const void *zSql,         /* UTF-16 encoded SQL statement. */
95914   int nBytes,               /* Length of zSql in bytes. */
95915   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
95916   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95917   const void **pzTail       /* OUT: End of parsed string */
95918 ){
95919   /* This function currently works by first transforming the UTF-16
95920   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
95921   ** tricky bit is figuring out the pointer to return in *pzTail.
95922   */
95923   char *zSql8;
95924   const char *zTail8 = 0;
95925   int rc = SQLITE_OK;
95926
95927   assert( ppStmt );
95928   *ppStmt = 0;
95929   if( !sqlite3SafetyCheckOk(db) ){
95930     return SQLITE_MISUSE_BKPT;
95931   }
95932   sqlite3_mutex_enter(db->mutex);
95933   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
95934   if( zSql8 ){
95935     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
95936   }
95937
95938   if( zTail8 && pzTail ){
95939     /* If sqlite3_prepare returns a tail pointer, we calculate the
95940     ** equivalent pointer into the UTF-16 string by counting the unicode
95941     ** characters between zSql8 and zTail8, and then returning a pointer
95942     ** the same number of characters into the UTF-16 string.
95943     */
95944     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
95945     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
95946   }
95947   sqlite3DbFree(db, zSql8);
95948   rc = sqlite3ApiExit(db, rc);
95949   sqlite3_mutex_leave(db->mutex);
95950   return rc;
95951 }
95952
95953 /*
95954 ** Two versions of the official API.  Legacy and new use.  In the legacy
95955 ** version, the original SQL text is not saved in the prepared statement
95956 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
95957 ** sqlite3_step().  In the new version, the original SQL text is retained
95958 ** and the statement is automatically recompiled if an schema change
95959 ** occurs.
95960 */
95961 SQLITE_API int sqlite3_prepare16(
95962   sqlite3 *db,              /* Database handle. */
95963   const void *zSql,         /* UTF-16 encoded SQL statement. */
95964   int nBytes,               /* Length of zSql in bytes. */
95965   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95966   const void **pzTail       /* OUT: End of parsed string */
95967 ){
95968   int rc;
95969   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
95970   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95971   return rc;
95972 }
95973 SQLITE_API int sqlite3_prepare16_v2(
95974   sqlite3 *db,              /* Database handle. */
95975   const void *zSql,         /* UTF-16 encoded SQL statement. */
95976   int nBytes,               /* Length of zSql in bytes. */
95977   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95978   const void **pzTail       /* OUT: End of parsed string */
95979 ){
95980   int rc;
95981   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
95982   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95983   return rc;
95984 }
95985
95986 #endif /* SQLITE_OMIT_UTF16 */
95987
95988 /************** End of prepare.c *********************************************/
95989 /************** Begin file select.c ******************************************/
95990 /*
95991 ** 2001 September 15
95992 **
95993 ** The author disclaims copyright to this source code.  In place of
95994 ** a legal notice, here is a blessing:
95995 **
95996 **    May you do good and not evil.
95997 **    May you find forgiveness for yourself and forgive others.
95998 **    May you share freely, never taking more than you give.
95999 **
96000 *************************************************************************
96001 ** This file contains C code routines that are called by the parser
96002 ** to handle SELECT statements in SQLite.
96003 */
96004
96005
96006 /*
96007 ** Delete all the content of a Select structure but do not deallocate
96008 ** the select structure itself.
96009 */
96010 static void clearSelect(sqlite3 *db, Select *p){
96011   sqlite3ExprListDelete(db, p->pEList);
96012   sqlite3SrcListDelete(db, p->pSrc);
96013   sqlite3ExprDelete(db, p->pWhere);
96014   sqlite3ExprListDelete(db, p->pGroupBy);
96015   sqlite3ExprDelete(db, p->pHaving);
96016   sqlite3ExprListDelete(db, p->pOrderBy);
96017   sqlite3SelectDelete(db, p->pPrior);
96018   sqlite3ExprDelete(db, p->pLimit);
96019   sqlite3ExprDelete(db, p->pOffset);
96020 }
96021
96022 /*
96023 ** Initialize a SelectDest structure.
96024 */
96025 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
96026   pDest->eDest = (u8)eDest;
96027   pDest->iSDParm = iParm;
96028   pDest->affSdst = 0;
96029   pDest->iSdst = 0;
96030   pDest->nSdst = 0;
96031 }
96032
96033
96034 /*
96035 ** Allocate a new Select structure and return a pointer to that
96036 ** structure.
96037 */
96038 SQLITE_PRIVATE Select *sqlite3SelectNew(
96039   Parse *pParse,        /* Parsing context */
96040   ExprList *pEList,     /* which columns to include in the result */
96041   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
96042   Expr *pWhere,         /* the WHERE clause */
96043   ExprList *pGroupBy,   /* the GROUP BY clause */
96044   Expr *pHaving,        /* the HAVING clause */
96045   ExprList *pOrderBy,   /* the ORDER BY clause */
96046   int isDistinct,       /* true if the DISTINCT keyword is present */
96047   Expr *pLimit,         /* LIMIT value.  NULL means not used */
96048   Expr *pOffset         /* OFFSET value.  NULL means no offset */
96049 ){
96050   Select *pNew;
96051   Select standin;
96052   sqlite3 *db = pParse->db;
96053   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
96054   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
96055   if( pNew==0 ){
96056     assert( db->mallocFailed );
96057     pNew = &standin;
96058     memset(pNew, 0, sizeof(*pNew));
96059   }
96060   if( pEList==0 ){
96061     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
96062   }
96063   pNew->pEList = pEList;
96064   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
96065   pNew->pSrc = pSrc;
96066   pNew->pWhere = pWhere;
96067   pNew->pGroupBy = pGroupBy;
96068   pNew->pHaving = pHaving;
96069   pNew->pOrderBy = pOrderBy;
96070   pNew->selFlags = isDistinct ? SF_Distinct : 0;
96071   pNew->op = TK_SELECT;
96072   pNew->pLimit = pLimit;
96073   pNew->pOffset = pOffset;
96074   assert( pOffset==0 || pLimit!=0 );
96075   pNew->addrOpenEphm[0] = -1;
96076   pNew->addrOpenEphm[1] = -1;
96077   pNew->addrOpenEphm[2] = -1;
96078   if( db->mallocFailed ) {
96079     clearSelect(db, pNew);
96080     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
96081     pNew = 0;
96082   }else{
96083     assert( pNew->pSrc!=0 || pParse->nErr>0 );
96084   }
96085   assert( pNew!=&standin );
96086   return pNew;
96087 }
96088
96089 /*
96090 ** Delete the given Select structure and all of its substructures.
96091 */
96092 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
96093   if( p ){
96094     clearSelect(db, p);
96095     sqlite3DbFree(db, p);
96096   }
96097 }
96098
96099 /*
96100 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
96101 ** type of join.  Return an integer constant that expresses that type
96102 ** in terms of the following bit values:
96103 **
96104 **     JT_INNER
96105 **     JT_CROSS
96106 **     JT_OUTER
96107 **     JT_NATURAL
96108 **     JT_LEFT
96109 **     JT_RIGHT
96110 **
96111 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
96112 **
96113 ** If an illegal or unsupported join type is seen, then still return
96114 ** a join type, but put an error in the pParse structure.
96115 */
96116 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
96117   int jointype = 0;
96118   Token *apAll[3];
96119   Token *p;
96120                              /*   0123456789 123456789 123456789 123 */
96121   static const char zKeyText[] = "naturaleftouterightfullinnercross";
96122   static const struct {
96123     u8 i;        /* Beginning of keyword text in zKeyText[] */
96124     u8 nChar;    /* Length of the keyword in characters */
96125     u8 code;     /* Join type mask */
96126   } aKeyword[] = {
96127     /* natural */ { 0,  7, JT_NATURAL                },
96128     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
96129     /* outer   */ { 10, 5, JT_OUTER                  },
96130     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
96131     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
96132     /* inner   */ { 23, 5, JT_INNER                  },
96133     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
96134   };
96135   int i, j;
96136   apAll[0] = pA;
96137   apAll[1] = pB;
96138   apAll[2] = pC;
96139   for(i=0; i<3 && apAll[i]; i++){
96140     p = apAll[i];
96141     for(j=0; j<ArraySize(aKeyword); j++){
96142       if( p->n==aKeyword[j].nChar
96143           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
96144         jointype |= aKeyword[j].code;
96145         break;
96146       }
96147     }
96148     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
96149     if( j>=ArraySize(aKeyword) ){
96150       jointype |= JT_ERROR;
96151       break;
96152     }
96153   }
96154   if(
96155      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
96156      (jointype & JT_ERROR)!=0
96157   ){
96158     const char *zSp = " ";
96159     assert( pB!=0 );
96160     if( pC==0 ){ zSp++; }
96161     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
96162        "%T %T%s%T", pA, pB, zSp, pC);
96163     jointype = JT_INNER;
96164   }else if( (jointype & JT_OUTER)!=0
96165          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
96166     sqlite3ErrorMsg(pParse,
96167       "RIGHT and FULL OUTER JOINs are not currently supported");
96168     jointype = JT_INNER;
96169   }
96170   return jointype;
96171 }
96172
96173 /*
96174 ** Return the index of a column in a table.  Return -1 if the column
96175 ** is not contained in the table.
96176 */
96177 static int columnIndex(Table *pTab, const char *zCol){
96178   int i;
96179   for(i=0; i<pTab->nCol; i++){
96180     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
96181   }
96182   return -1;
96183 }
96184
96185 /*
96186 ** Search the first N tables in pSrc, from left to right, looking for a
96187 ** table that has a column named zCol.
96188 **
96189 ** When found, set *piTab and *piCol to the table index and column index
96190 ** of the matching column and return TRUE.
96191 **
96192 ** If not found, return FALSE.
96193 */
96194 static int tableAndColumnIndex(
96195   SrcList *pSrc,       /* Array of tables to search */
96196   int N,               /* Number of tables in pSrc->a[] to search */
96197   const char *zCol,    /* Name of the column we are looking for */
96198   int *piTab,          /* Write index of pSrc->a[] here */
96199   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
96200 ){
96201   int i;               /* For looping over tables in pSrc */
96202   int iCol;            /* Index of column matching zCol */
96203
96204   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
96205   for(i=0; i<N; i++){
96206     iCol = columnIndex(pSrc->a[i].pTab, zCol);
96207     if( iCol>=0 ){
96208       if( piTab ){
96209         *piTab = i;
96210         *piCol = iCol;
96211       }
96212       return 1;
96213     }
96214   }
96215   return 0;
96216 }
96217
96218 /*
96219 ** This function is used to add terms implied by JOIN syntax to the
96220 ** WHERE clause expression of a SELECT statement. The new term, which
96221 ** is ANDed with the existing WHERE clause, is of the form:
96222 **
96223 **    (tab1.col1 = tab2.col2)
96224 **
96225 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
96226 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
96227 ** column iColRight of tab2.
96228 */
96229 static void addWhereTerm(
96230   Parse *pParse,                  /* Parsing context */
96231   SrcList *pSrc,                  /* List of tables in FROM clause */
96232   int iLeft,                      /* Index of first table to join in pSrc */
96233   int iColLeft,                   /* Index of column in first table */
96234   int iRight,                     /* Index of second table in pSrc */
96235   int iColRight,                  /* Index of column in second table */
96236   int isOuterJoin,                /* True if this is an OUTER join */
96237   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
96238 ){
96239   sqlite3 *db = pParse->db;
96240   Expr *pE1;
96241   Expr *pE2;
96242   Expr *pEq;
96243
96244   assert( iLeft<iRight );
96245   assert( pSrc->nSrc>iRight );
96246   assert( pSrc->a[iLeft].pTab );
96247   assert( pSrc->a[iRight].pTab );
96248
96249   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
96250   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
96251
96252   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
96253   if( pEq && isOuterJoin ){
96254     ExprSetProperty(pEq, EP_FromJoin);
96255     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
96256     ExprSetIrreducible(pEq);
96257     pEq->iRightJoinTable = (i16)pE2->iTable;
96258   }
96259   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
96260 }
96261
96262 /*
96263 ** Set the EP_FromJoin property on all terms of the given expression.
96264 ** And set the Expr.iRightJoinTable to iTable for every term in the
96265 ** expression.
96266 **
96267 ** The EP_FromJoin property is used on terms of an expression to tell
96268 ** the LEFT OUTER JOIN processing logic that this term is part of the
96269 ** join restriction specified in the ON or USING clause and not a part
96270 ** of the more general WHERE clause.  These terms are moved over to the
96271 ** WHERE clause during join processing but we need to remember that they
96272 ** originated in the ON or USING clause.
96273 **
96274 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
96275 ** expression depends on table iRightJoinTable even if that table is not
96276 ** explicitly mentioned in the expression.  That information is needed
96277 ** for cases like this:
96278 **
96279 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
96280 **
96281 ** The where clause needs to defer the handling of the t1.x=5
96282 ** term until after the t2 loop of the join.  In that way, a
96283 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
96284 ** defer the handling of t1.x=5, it will be processed immediately
96285 ** after the t1 loop and rows with t1.x!=5 will never appear in
96286 ** the output, which is incorrect.
96287 */
96288 static void setJoinExpr(Expr *p, int iTable){
96289   while( p ){
96290     ExprSetProperty(p, EP_FromJoin);
96291     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
96292     ExprSetIrreducible(p);
96293     p->iRightJoinTable = (i16)iTable;
96294     setJoinExpr(p->pLeft, iTable);
96295     p = p->pRight;
96296   }
96297 }
96298
96299 /*
96300 ** This routine processes the join information for a SELECT statement.
96301 ** ON and USING clauses are converted into extra terms of the WHERE clause.
96302 ** NATURAL joins also create extra WHERE clause terms.
96303 **
96304 ** The terms of a FROM clause are contained in the Select.pSrc structure.
96305 ** The left most table is the first entry in Select.pSrc.  The right-most
96306 ** table is the last entry.  The join operator is held in the entry to
96307 ** the left.  Thus entry 0 contains the join operator for the join between
96308 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
96309 ** also attached to the left entry.
96310 **
96311 ** This routine returns the number of errors encountered.
96312 */
96313 static int sqliteProcessJoin(Parse *pParse, Select *p){
96314   SrcList *pSrc;                  /* All tables in the FROM clause */
96315   int i, j;                       /* Loop counters */
96316   struct SrcList_item *pLeft;     /* Left table being joined */
96317   struct SrcList_item *pRight;    /* Right table being joined */
96318
96319   pSrc = p->pSrc;
96320   pLeft = &pSrc->a[0];
96321   pRight = &pLeft[1];
96322   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
96323     Table *pLeftTab = pLeft->pTab;
96324     Table *pRightTab = pRight->pTab;
96325     int isOuter;
96326
96327     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
96328     isOuter = (pRight->jointype & JT_OUTER)!=0;
96329
96330     /* When the NATURAL keyword is present, add WHERE clause terms for
96331     ** every column that the two tables have in common.
96332     */
96333     if( pRight->jointype & JT_NATURAL ){
96334       if( pRight->pOn || pRight->pUsing ){
96335         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
96336            "an ON or USING clause", 0);
96337         return 1;
96338       }
96339       for(j=0; j<pRightTab->nCol; j++){
96340         char *zName;   /* Name of column in the right table */
96341         int iLeft;     /* Matching left table */
96342         int iLeftCol;  /* Matching column in the left table */
96343
96344         zName = pRightTab->aCol[j].zName;
96345         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
96346           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
96347                        isOuter, &p->pWhere);
96348         }
96349       }
96350     }
96351
96352     /* Disallow both ON and USING clauses in the same join
96353     */
96354     if( pRight->pOn && pRight->pUsing ){
96355       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
96356         "clauses in the same join");
96357       return 1;
96358     }
96359
96360     /* Add the ON clause to the end of the WHERE clause, connected by
96361     ** an AND operator.
96362     */
96363     if( pRight->pOn ){
96364       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
96365       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
96366       pRight->pOn = 0;
96367     }
96368
96369     /* Create extra terms on the WHERE clause for each column named
96370     ** in the USING clause.  Example: If the two tables to be joined are
96371     ** A and B and the USING clause names X, Y, and Z, then add this
96372     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
96373     ** Report an error if any column mentioned in the USING clause is
96374     ** not contained in both tables to be joined.
96375     */
96376     if( pRight->pUsing ){
96377       IdList *pList = pRight->pUsing;
96378       for(j=0; j<pList->nId; j++){
96379         char *zName;     /* Name of the term in the USING clause */
96380         int iLeft;       /* Table on the left with matching column name */
96381         int iLeftCol;    /* Column number of matching column on the left */
96382         int iRightCol;   /* Column number of matching column on the right */
96383
96384         zName = pList->a[j].zName;
96385         iRightCol = columnIndex(pRightTab, zName);
96386         if( iRightCol<0
96387          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
96388         ){
96389           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
96390             "not present in both tables", zName);
96391           return 1;
96392         }
96393         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
96394                      isOuter, &p->pWhere);
96395       }
96396     }
96397   }
96398   return 0;
96399 }
96400
96401 /*
96402 ** Insert code into "v" that will push the record on the top of the
96403 ** stack into the sorter.
96404 */
96405 static void pushOntoSorter(
96406   Parse *pParse,         /* Parser context */
96407   ExprList *pOrderBy,    /* The ORDER BY clause */
96408   Select *pSelect,       /* The whole SELECT statement */
96409   int regData            /* Register holding data to be sorted */
96410 ){
96411   Vdbe *v = pParse->pVdbe;
96412   int nExpr = pOrderBy->nExpr;
96413   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
96414   int regRecord = sqlite3GetTempReg(pParse);
96415   int op;
96416   sqlite3ExprCacheClear(pParse);
96417   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
96418   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
96419   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
96420   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
96421   if( pSelect->selFlags & SF_UseSorter ){
96422     op = OP_SorterInsert;
96423   }else{
96424     op = OP_IdxInsert;
96425   }
96426   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
96427   sqlite3ReleaseTempReg(pParse, regRecord);
96428   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
96429   if( pSelect->iLimit ){
96430     int addr1, addr2;
96431     int iLimit;
96432     if( pSelect->iOffset ){
96433       iLimit = pSelect->iOffset+1;
96434     }else{
96435       iLimit = pSelect->iLimit;
96436     }
96437     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
96438     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
96439     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
96440     sqlite3VdbeJumpHere(v, addr1);
96441     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
96442     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
96443     sqlite3VdbeJumpHere(v, addr2);
96444   }
96445 }
96446
96447 /*
96448 ** Add code to implement the OFFSET
96449 */
96450 static void codeOffset(
96451   Vdbe *v,          /* Generate code into this VM */
96452   Select *p,        /* The SELECT statement being coded */
96453   int iContinue     /* Jump here to skip the current record */
96454 ){
96455   if( p->iOffset && iContinue!=0 ){
96456     int addr;
96457     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
96458     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
96459     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
96460     VdbeComment((v, "skip OFFSET records"));
96461     sqlite3VdbeJumpHere(v, addr);
96462   }
96463 }
96464
96465 /*
96466 ** Add code that will check to make sure the N registers starting at iMem
96467 ** form a distinct entry.  iTab is a sorting index that holds previously
96468 ** seen combinations of the N values.  A new entry is made in iTab
96469 ** if the current N values are new.
96470 **
96471 ** A jump to addrRepeat is made and the N+1 values are popped from the
96472 ** stack if the top N elements are not distinct.
96473 */
96474 static void codeDistinct(
96475   Parse *pParse,     /* Parsing and code generating context */
96476   int iTab,          /* A sorting index used to test for distinctness */
96477   int addrRepeat,    /* Jump to here if not distinct */
96478   int N,             /* Number of elements */
96479   int iMem           /* First element */
96480 ){
96481   Vdbe *v;
96482   int r1;
96483
96484   v = pParse->pVdbe;
96485   r1 = sqlite3GetTempReg(pParse);
96486   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
96487   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
96488   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
96489   sqlite3ReleaseTempReg(pParse, r1);
96490 }
96491
96492 #ifndef SQLITE_OMIT_SUBQUERY
96493 /*
96494 ** Generate an error message when a SELECT is used within a subexpression
96495 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
96496 ** column.  We do this in a subroutine because the error used to occur
96497 ** in multiple places.  (The error only occurs in one place now, but we
96498 ** retain the subroutine to minimize code disruption.)
96499 */
96500 static int checkForMultiColumnSelectError(
96501   Parse *pParse,       /* Parse context. */
96502   SelectDest *pDest,   /* Destination of SELECT results */
96503   int nExpr            /* Number of result columns returned by SELECT */
96504 ){
96505   int eDest = pDest->eDest;
96506   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
96507     sqlite3ErrorMsg(pParse, "only a single result allowed for "
96508        "a SELECT that is part of an expression");
96509     return 1;
96510   }else{
96511     return 0;
96512   }
96513 }
96514 #endif
96515
96516 /*
96517 ** An instance of the following object is used to record information about
96518 ** how to process the DISTINCT keyword, to simplify passing that information
96519 ** into the selectInnerLoop() routine.
96520 */
96521 typedef struct DistinctCtx DistinctCtx;
96522 struct DistinctCtx {
96523   u8 isTnct;      /* True if the DISTINCT keyword is present */
96524   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
96525   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
96526   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
96527 };
96528
96529 /*
96530 ** This routine generates the code for the inside of the inner loop
96531 ** of a SELECT.
96532 **
96533 ** If srcTab and nColumn are both zero, then the pEList expressions
96534 ** are evaluated in order to get the data for this row.  If nColumn>0
96535 ** then data is pulled from srcTab and pEList is used only to get the
96536 ** datatypes for each column.
96537 */
96538 static void selectInnerLoop(
96539   Parse *pParse,          /* The parser context */
96540   Select *p,              /* The complete select statement being coded */
96541   ExprList *pEList,       /* List of values being extracted */
96542   int srcTab,             /* Pull data from this table */
96543   int nColumn,            /* Number of columns in the source table */
96544   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
96545   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
96546   SelectDest *pDest,      /* How to dispose of the results */
96547   int iContinue,          /* Jump here to continue with next row */
96548   int iBreak              /* Jump here to break out of the inner loop */
96549 ){
96550   Vdbe *v = pParse->pVdbe;
96551   int i;
96552   int hasDistinct;        /* True if the DISTINCT keyword is present */
96553   int regResult;              /* Start of memory holding result set */
96554   int eDest = pDest->eDest;   /* How to dispose of results */
96555   int iParm = pDest->iSDParm; /* First argument to disposal method */
96556   int nResultCol;             /* Number of result columns */
96557
96558   assert( v );
96559   if( NEVER(v==0) ) return;
96560   assert( pEList!=0 );
96561   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
96562   if( pOrderBy==0 && !hasDistinct ){
96563     codeOffset(v, p, iContinue);
96564   }
96565
96566   /* Pull the requested columns.
96567   */
96568   if( nColumn>0 ){
96569     nResultCol = nColumn;
96570   }else{
96571     nResultCol = pEList->nExpr;
96572   }
96573   if( pDest->iSdst==0 ){
96574     pDest->iSdst = pParse->nMem+1;
96575     pDest->nSdst = nResultCol;
96576     pParse->nMem += nResultCol;
96577   }else{
96578     assert( pDest->nSdst==nResultCol );
96579   }
96580   regResult = pDest->iSdst;
96581   if( nColumn>0 ){
96582     for(i=0; i<nColumn; i++){
96583       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
96584     }
96585   }else if( eDest!=SRT_Exists ){
96586     /* If the destination is an EXISTS(...) expression, the actual
96587     ** values returned by the SELECT are not required.
96588     */
96589     sqlite3ExprCacheClear(pParse);
96590     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
96591   }
96592   nColumn = nResultCol;
96593
96594   /* If the DISTINCT keyword was present on the SELECT statement
96595   ** and this row has been seen before, then do not make this row
96596   ** part of the result.
96597   */
96598   if( hasDistinct ){
96599     assert( pEList!=0 );
96600     assert( pEList->nExpr==nColumn );
96601     switch( pDistinct->eTnctType ){
96602       case WHERE_DISTINCT_ORDERED: {
96603         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
96604         int iJump;              /* Jump destination */
96605         int regPrev;            /* Previous row content */
96606
96607         /* Allocate space for the previous row */
96608         regPrev = pParse->nMem+1;
96609         pParse->nMem += nColumn;
96610
96611         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
96612         ** sets the MEM_Cleared bit on the first register of the
96613         ** previous value.  This will cause the OP_Ne below to always
96614         ** fail on the first iteration of the loop even if the first
96615         ** row is all NULLs.
96616         */
96617         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
96618         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
96619         pOp->opcode = OP_Null;
96620         pOp->p1 = 1;
96621         pOp->p2 = regPrev;
96622
96623         iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
96624         for(i=0; i<nColumn; i++){
96625           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
96626           if( i<nColumn-1 ){
96627             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
96628           }else{
96629             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
96630           }
96631           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
96632           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
96633         }
96634         assert( sqlite3VdbeCurrentAddr(v)==iJump );
96635         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
96636         break;
96637       }
96638
96639       case WHERE_DISTINCT_UNIQUE: {
96640         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
96641         break;
96642       }
96643
96644       default: {
96645         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
96646         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
96647         break;
96648       }
96649     }
96650     if( pOrderBy==0 ){
96651       codeOffset(v, p, iContinue);
96652     }
96653   }
96654
96655   switch( eDest ){
96656     /* In this mode, write each query result to the key of the temporary
96657     ** table iParm.
96658     */
96659 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96660     case SRT_Union: {
96661       int r1;
96662       r1 = sqlite3GetTempReg(pParse);
96663       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96664       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96665       sqlite3ReleaseTempReg(pParse, r1);
96666       break;
96667     }
96668
96669     /* Construct a record from the query result, but instead of
96670     ** saving that record, use it as a key to delete elements from
96671     ** the temporary table iParm.
96672     */
96673     case SRT_Except: {
96674       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
96675       break;
96676     }
96677 #endif
96678
96679     /* Store the result as data using a unique key.
96680     */
96681     case SRT_Table:
96682     case SRT_EphemTab: {
96683       int r1 = sqlite3GetTempReg(pParse);
96684       testcase( eDest==SRT_Table );
96685       testcase( eDest==SRT_EphemTab );
96686       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96687       if( pOrderBy ){
96688         pushOntoSorter(pParse, pOrderBy, p, r1);
96689       }else{
96690         int r2 = sqlite3GetTempReg(pParse);
96691         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
96692         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
96693         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96694         sqlite3ReleaseTempReg(pParse, r2);
96695       }
96696       sqlite3ReleaseTempReg(pParse, r1);
96697       break;
96698     }
96699
96700 #ifndef SQLITE_OMIT_SUBQUERY
96701     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96702     ** then there should be a single item on the stack.  Write this
96703     ** item into the set table with bogus data.
96704     */
96705     case SRT_Set: {
96706       assert( nColumn==1 );
96707       pDest->affSdst =
96708                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
96709       if( pOrderBy ){
96710         /* At first glance you would think we could optimize out the
96711         ** ORDER BY in this case since the order of entries in the set
96712         ** does not matter.  But there might be a LIMIT clause, in which
96713         ** case the order does matter */
96714         pushOntoSorter(pParse, pOrderBy, p, regResult);
96715       }else{
96716         int r1 = sqlite3GetTempReg(pParse);
96717         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
96718         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
96719         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96720         sqlite3ReleaseTempReg(pParse, r1);
96721       }
96722       break;
96723     }
96724
96725     /* If any row exist in the result set, record that fact and abort.
96726     */
96727     case SRT_Exists: {
96728       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
96729       /* The LIMIT clause will terminate the loop for us */
96730       break;
96731     }
96732
96733     /* If this is a scalar select that is part of an expression, then
96734     ** store the results in the appropriate memory cell and break out
96735     ** of the scan loop.
96736     */
96737     case SRT_Mem: {
96738       assert( nColumn==1 );
96739       if( pOrderBy ){
96740         pushOntoSorter(pParse, pOrderBy, p, regResult);
96741       }else{
96742         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
96743         /* The LIMIT clause will jump out of the loop for us */
96744       }
96745       break;
96746     }
96747 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96748
96749     /* Send the data to the callback function or to a subroutine.  In the
96750     ** case of a subroutine, the subroutine itself is responsible for
96751     ** popping the data from the stack.
96752     */
96753     case SRT_Coroutine:
96754     case SRT_Output: {
96755       testcase( eDest==SRT_Coroutine );
96756       testcase( eDest==SRT_Output );
96757       if( pOrderBy ){
96758         int r1 = sqlite3GetTempReg(pParse);
96759         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96760         pushOntoSorter(pParse, pOrderBy, p, r1);
96761         sqlite3ReleaseTempReg(pParse, r1);
96762       }else if( eDest==SRT_Coroutine ){
96763         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
96764       }else{
96765         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
96766         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
96767       }
96768       break;
96769     }
96770
96771 #if !defined(SQLITE_OMIT_TRIGGER)
96772     /* Discard the results.  This is used for SELECT statements inside
96773     ** the body of a TRIGGER.  The purpose of such selects is to call
96774     ** user-defined functions that have side effects.  We do not care
96775     ** about the actual results of the select.
96776     */
96777     default: {
96778       assert( eDest==SRT_Discard );
96779       break;
96780     }
96781 #endif
96782   }
96783
96784   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
96785   ** there is a sorter, in which case the sorter has already limited
96786   ** the output for us.
96787   */
96788   if( pOrderBy==0 && p->iLimit ){
96789     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96790   }
96791 }
96792
96793 /*
96794 ** Given an expression list, generate a KeyInfo structure that records
96795 ** the collating sequence for each expression in that expression list.
96796 **
96797 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
96798 ** KeyInfo structure is appropriate for initializing a virtual index to
96799 ** implement that clause.  If the ExprList is the result set of a SELECT
96800 ** then the KeyInfo structure is appropriate for initializing a virtual
96801 ** index to implement a DISTINCT test.
96802 **
96803 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
96804 ** function is responsible for seeing that this structure is eventually
96805 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
96806 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
96807 */
96808 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
96809   sqlite3 *db = pParse->db;
96810   int nExpr;
96811   KeyInfo *pInfo;
96812   struct ExprList_item *pItem;
96813   int i;
96814
96815   nExpr = pList->nExpr;
96816   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
96817   if( pInfo ){
96818     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
96819     pInfo->nField = (u16)nExpr;
96820     pInfo->enc = ENC(db);
96821     pInfo->db = db;
96822     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
96823       CollSeq *pColl;
96824       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
96825       if( !pColl ){
96826         pColl = db->pDfltColl;
96827       }
96828       pInfo->aColl[i] = pColl;
96829       pInfo->aSortOrder[i] = pItem->sortOrder;
96830     }
96831   }
96832   return pInfo;
96833 }
96834
96835 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96836 /*
96837 ** Name of the connection operator, used for error messages.
96838 */
96839 static const char *selectOpName(int id){
96840   char *z;
96841   switch( id ){
96842     case TK_ALL:       z = "UNION ALL";   break;
96843     case TK_INTERSECT: z = "INTERSECT";   break;
96844     case TK_EXCEPT:    z = "EXCEPT";      break;
96845     default:           z = "UNION";       break;
96846   }
96847   return z;
96848 }
96849 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96850
96851 #ifndef SQLITE_OMIT_EXPLAIN
96852 /*
96853 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96854 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96855 ** where the caption is of the form:
96856 **
96857 **   "USE TEMP B-TREE FOR xxx"
96858 **
96859 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
96860 ** is determined by the zUsage argument.
96861 */
96862 static void explainTempTable(Parse *pParse, const char *zUsage){
96863   if( pParse->explain==2 ){
96864     Vdbe *v = pParse->pVdbe;
96865     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
96866     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
96867   }
96868 }
96869
96870 /*
96871 ** Assign expression b to lvalue a. A second, no-op, version of this macro
96872 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
96873 ** in sqlite3Select() to assign values to structure member variables that
96874 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
96875 ** code with #ifndef directives.
96876 */
96877 # define explainSetInteger(a, b) a = b
96878
96879 #else
96880 /* No-op versions of the explainXXX() functions and macros. */
96881 # define explainTempTable(y,z)
96882 # define explainSetInteger(y,z)
96883 #endif
96884
96885 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
96886 /*
96887 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96888 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96889 ** where the caption is of one of the two forms:
96890 **
96891 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
96892 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
96893 **
96894 ** where iSub1 and iSub2 are the integers passed as the corresponding
96895 ** function parameters, and op is the text representation of the parameter
96896 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
96897 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
96898 ** false, or the second form if it is true.
96899 */
96900 static void explainComposite(
96901   Parse *pParse,                  /* Parse context */
96902   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
96903   int iSub1,                      /* Subquery id 1 */
96904   int iSub2,                      /* Subquery id 2 */
96905   int bUseTmp                     /* True if a temp table was used */
96906 ){
96907   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
96908   if( pParse->explain==2 ){
96909     Vdbe *v = pParse->pVdbe;
96910     char *zMsg = sqlite3MPrintf(
96911         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
96912         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
96913     );
96914     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
96915   }
96916 }
96917 #else
96918 /* No-op versions of the explainXXX() functions and macros. */
96919 # define explainComposite(v,w,x,y,z)
96920 #endif
96921
96922 /*
96923 ** If the inner loop was generated using a non-null pOrderBy argument,
96924 ** then the results were placed in a sorter.  After the loop is terminated
96925 ** we need to run the sorter and output the results.  The following
96926 ** routine generates the code needed to do that.
96927 */
96928 static void generateSortTail(
96929   Parse *pParse,    /* Parsing context */
96930   Select *p,        /* The SELECT statement */
96931   Vdbe *v,          /* Generate code into this VDBE */
96932   int nColumn,      /* Number of columns of data */
96933   SelectDest *pDest /* Write the sorted results here */
96934 ){
96935   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
96936   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
96937   int addr;
96938   int iTab;
96939   int pseudoTab = 0;
96940   ExprList *pOrderBy = p->pOrderBy;
96941
96942   int eDest = pDest->eDest;
96943   int iParm = pDest->iSDParm;
96944
96945   int regRow;
96946   int regRowid;
96947
96948   iTab = pOrderBy->iECursor;
96949   regRow = sqlite3GetTempReg(pParse);
96950   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
96951     pseudoTab = pParse->nTab++;
96952     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
96953     regRowid = 0;
96954   }else{
96955     regRowid = sqlite3GetTempReg(pParse);
96956   }
96957   if( p->selFlags & SF_UseSorter ){
96958     int regSortOut = ++pParse->nMem;
96959     int ptab2 = pParse->nTab++;
96960     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
96961     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
96962     codeOffset(v, p, addrContinue);
96963     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
96964     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
96965     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
96966   }else{
96967     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
96968     codeOffset(v, p, addrContinue);
96969     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
96970   }
96971   switch( eDest ){
96972     case SRT_Table:
96973     case SRT_EphemTab: {
96974       testcase( eDest==SRT_Table );
96975       testcase( eDest==SRT_EphemTab );
96976       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
96977       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
96978       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96979       break;
96980     }
96981 #ifndef SQLITE_OMIT_SUBQUERY
96982     case SRT_Set: {
96983       assert( nColumn==1 );
96984       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
96985                         &pDest->affSdst, 1);
96986       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
96987       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
96988       break;
96989     }
96990     case SRT_Mem: {
96991       assert( nColumn==1 );
96992       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
96993       /* The LIMIT clause will terminate the loop for us */
96994       break;
96995     }
96996 #endif
96997     default: {
96998       int i;
96999       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
97000       testcase( eDest==SRT_Output );
97001       testcase( eDest==SRT_Coroutine );
97002       for(i=0; i<nColumn; i++){
97003         assert( regRow!=pDest->iSdst+i );
97004         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
97005         if( i==0 ){
97006           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97007         }
97008       }
97009       if( eDest==SRT_Output ){
97010         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
97011         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
97012       }else{
97013         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
97014       }
97015       break;
97016     }
97017   }
97018   sqlite3ReleaseTempReg(pParse, regRow);
97019   sqlite3ReleaseTempReg(pParse, regRowid);
97020
97021   /* The bottom of the loop
97022   */
97023   sqlite3VdbeResolveLabel(v, addrContinue);
97024   if( p->selFlags & SF_UseSorter ){
97025     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
97026   }else{
97027     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
97028   }
97029   sqlite3VdbeResolveLabel(v, addrBreak);
97030   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
97031     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
97032   }
97033 }
97034
97035 /*
97036 ** Return a pointer to a string containing the 'declaration type' of the
97037 ** expression pExpr. The string may be treated as static by the caller.
97038 **
97039 ** The declaration type is the exact datatype definition extracted from the
97040 ** original CREATE TABLE statement if the expression is a column. The
97041 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
97042 ** is considered a column can be complex in the presence of subqueries. The
97043 ** result-set expression in all of the following SELECT statements is
97044 ** considered a column by this function.
97045 **
97046 **   SELECT col FROM tbl;
97047 **   SELECT (SELECT col FROM tbl;
97048 **   SELECT (SELECT col FROM tbl);
97049 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
97050 **
97051 ** The declaration type for any expression other than a column is NULL.
97052 */
97053 static const char *columnType(
97054   NameContext *pNC,
97055   Expr *pExpr,
97056   const char **pzOriginDb,
97057   const char **pzOriginTab,
97058   const char **pzOriginCol
97059 ){
97060   char const *zType = 0;
97061   char const *zOriginDb = 0;
97062   char const *zOriginTab = 0;
97063   char const *zOriginCol = 0;
97064   int j;
97065   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
97066
97067   switch( pExpr->op ){
97068     case TK_AGG_COLUMN:
97069     case TK_COLUMN: {
97070       /* The expression is a column. Locate the table the column is being
97071       ** extracted from in NameContext.pSrcList. This table may be real
97072       ** database table or a subquery.
97073       */
97074       Table *pTab = 0;            /* Table structure column is extracted from */
97075       Select *pS = 0;             /* Select the column is extracted from */
97076       int iCol = pExpr->iColumn;  /* Index of column in pTab */
97077       testcase( pExpr->op==TK_AGG_COLUMN );
97078       testcase( pExpr->op==TK_COLUMN );
97079       while( pNC && !pTab ){
97080         SrcList *pTabList = pNC->pSrcList;
97081         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
97082         if( j<pTabList->nSrc ){
97083           pTab = pTabList->a[j].pTab;
97084           pS = pTabList->a[j].pSelect;
97085         }else{
97086           pNC = pNC->pNext;
97087         }
97088       }
97089
97090       if( pTab==0 ){
97091         /* At one time, code such as "SELECT new.x" within a trigger would
97092         ** cause this condition to run.  Since then, we have restructured how
97093         ** trigger code is generated and so this condition is no longer
97094         ** possible. However, it can still be true for statements like
97095         ** the following:
97096         **
97097         **   CREATE TABLE t1(col INTEGER);
97098         **   SELECT (SELECT t1.col) FROM FROM t1;
97099         **
97100         ** when columnType() is called on the expression "t1.col" in the
97101         ** sub-select. In this case, set the column type to NULL, even
97102         ** though it should really be "INTEGER".
97103         **
97104         ** This is not a problem, as the column type of "t1.col" is never
97105         ** used. When columnType() is called on the expression
97106         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
97107         ** branch below.  */
97108         break;
97109       }
97110
97111       assert( pTab && pExpr->pTab==pTab );
97112       if( pS ){
97113         /* The "table" is actually a sub-select or a view in the FROM clause
97114         ** of the SELECT statement. Return the declaration type and origin
97115         ** data for the result-set column of the sub-select.
97116         */
97117         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
97118           /* If iCol is less than zero, then the expression requests the
97119           ** rowid of the sub-select or view. This expression is legal (see
97120           ** test case misc2.2.2) - it always evaluates to NULL.
97121           */
97122           NameContext sNC;
97123           Expr *p = pS->pEList->a[iCol].pExpr;
97124           sNC.pSrcList = pS->pSrc;
97125           sNC.pNext = pNC;
97126           sNC.pParse = pNC->pParse;
97127           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
97128         }
97129       }else if( ALWAYS(pTab->pSchema) ){
97130         /* A real table */
97131         assert( !pS );
97132         if( iCol<0 ) iCol = pTab->iPKey;
97133         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97134         if( iCol<0 ){
97135           zType = "INTEGER";
97136           zOriginCol = "rowid";
97137         }else{
97138           zType = pTab->aCol[iCol].zType;
97139           zOriginCol = pTab->aCol[iCol].zName;
97140         }
97141         zOriginTab = pTab->zName;
97142         if( pNC->pParse ){
97143           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
97144           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
97145         }
97146       }
97147       break;
97148     }
97149 #ifndef SQLITE_OMIT_SUBQUERY
97150     case TK_SELECT: {
97151       /* The expression is a sub-select. Return the declaration type and
97152       ** origin info for the single column in the result set of the SELECT
97153       ** statement.
97154       */
97155       NameContext sNC;
97156       Select *pS = pExpr->x.pSelect;
97157       Expr *p = pS->pEList->a[0].pExpr;
97158       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
97159       sNC.pSrcList = pS->pSrc;
97160       sNC.pNext = pNC;
97161       sNC.pParse = pNC->pParse;
97162       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
97163       break;
97164     }
97165 #endif
97166   }
97167
97168   if( pzOriginDb ){
97169     assert( pzOriginTab && pzOriginCol );
97170     *pzOriginDb = zOriginDb;
97171     *pzOriginTab = zOriginTab;
97172     *pzOriginCol = zOriginCol;
97173   }
97174   return zType;
97175 }
97176
97177 /*
97178 ** Generate code that will tell the VDBE the declaration types of columns
97179 ** in the result set.
97180 */
97181 static void generateColumnTypes(
97182   Parse *pParse,      /* Parser context */
97183   SrcList *pTabList,  /* List of tables */
97184   ExprList *pEList    /* Expressions defining the result set */
97185 ){
97186 #ifndef SQLITE_OMIT_DECLTYPE
97187   Vdbe *v = pParse->pVdbe;
97188   int i;
97189   NameContext sNC;
97190   sNC.pSrcList = pTabList;
97191   sNC.pParse = pParse;
97192   for(i=0; i<pEList->nExpr; i++){
97193     Expr *p = pEList->a[i].pExpr;
97194     const char *zType;
97195 #ifdef SQLITE_ENABLE_COLUMN_METADATA
97196     const char *zOrigDb = 0;
97197     const char *zOrigTab = 0;
97198     const char *zOrigCol = 0;
97199     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
97200
97201     /* The vdbe must make its own copy of the column-type and other
97202     ** column specific strings, in case the schema is reset before this
97203     ** virtual machine is deleted.
97204     */
97205     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
97206     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
97207     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
97208 #else
97209     zType = columnType(&sNC, p, 0, 0, 0);
97210 #endif
97211     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
97212   }
97213 #endif /* SQLITE_OMIT_DECLTYPE */
97214 }
97215
97216 /*
97217 ** Generate code that will tell the VDBE the names of columns
97218 ** in the result set.  This information is used to provide the
97219 ** azCol[] values in the callback.
97220 */
97221 static void generateColumnNames(
97222   Parse *pParse,      /* Parser context */
97223   SrcList *pTabList,  /* List of tables */
97224   ExprList *pEList    /* Expressions defining the result set */
97225 ){
97226   Vdbe *v = pParse->pVdbe;
97227   int i, j;
97228   sqlite3 *db = pParse->db;
97229   int fullNames, shortNames;
97230
97231 #ifndef SQLITE_OMIT_EXPLAIN
97232   /* If this is an EXPLAIN, skip this step */
97233   if( pParse->explain ){
97234     return;
97235   }
97236 #endif
97237
97238   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
97239   pParse->colNamesSet = 1;
97240   fullNames = (db->flags & SQLITE_FullColNames)!=0;
97241   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
97242   sqlite3VdbeSetNumCols(v, pEList->nExpr);
97243   for(i=0; i<pEList->nExpr; i++){
97244     Expr *p;
97245     p = pEList->a[i].pExpr;
97246     if( NEVER(p==0) ) continue;
97247     if( pEList->a[i].zName ){
97248       char *zName = pEList->a[i].zName;
97249       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
97250     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
97251       Table *pTab;
97252       char *zCol;
97253       int iCol = p->iColumn;
97254       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
97255         if( pTabList->a[j].iCursor==p->iTable ) break;
97256       }
97257       assert( j<pTabList->nSrc );
97258       pTab = pTabList->a[j].pTab;
97259       if( iCol<0 ) iCol = pTab->iPKey;
97260       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97261       if( iCol<0 ){
97262         zCol = "rowid";
97263       }else{
97264         zCol = pTab->aCol[iCol].zName;
97265       }
97266       if( !shortNames && !fullNames ){
97267         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
97268             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97269       }else if( fullNames ){
97270         char *zName = 0;
97271         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
97272         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
97273       }else{
97274         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
97275       }
97276     }else{
97277       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
97278           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97279     }
97280   }
97281   generateColumnTypes(pParse, pTabList, pEList);
97282 }
97283
97284 /*
97285 ** Given a an expression list (which is really the list of expressions
97286 ** that form the result set of a SELECT statement) compute appropriate
97287 ** column names for a table that would hold the expression list.
97288 **
97289 ** All column names will be unique.
97290 **
97291 ** Only the column names are computed.  Column.zType, Column.zColl,
97292 ** and other fields of Column are zeroed.
97293 **
97294 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
97295 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
97296 */
97297 static int selectColumnsFromExprList(
97298   Parse *pParse,          /* Parsing context */
97299   ExprList *pEList,       /* Expr list from which to derive column names */
97300   i16 *pnCol,             /* Write the number of columns here */
97301   Column **paCol          /* Write the new column list here */
97302 ){
97303   sqlite3 *db = pParse->db;   /* Database connection */
97304   int i, j;                   /* Loop counters */
97305   int cnt;                    /* Index added to make the name unique */
97306   Column *aCol, *pCol;        /* For looping over result columns */
97307   int nCol;                   /* Number of columns in the result set */
97308   Expr *p;                    /* Expression for a single result column */
97309   char *zName;                /* Column name */
97310   int nName;                  /* Size of name in zName[] */
97311
97312   if( pEList ){
97313     nCol = pEList->nExpr;
97314     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
97315     testcase( aCol==0 );
97316   }else{
97317     nCol = 0;
97318     aCol = 0;
97319   }
97320   *pnCol = nCol;
97321   *paCol = aCol;
97322
97323   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97324     /* Get an appropriate name for the column
97325     */
97326     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
97327     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
97328                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
97329     if( (zName = pEList->a[i].zName)!=0 ){
97330       /* If the column contains an "AS <name>" phrase, use <name> as the name */
97331       zName = sqlite3DbStrDup(db, zName);
97332     }else{
97333       Expr *pColExpr = p;  /* The expression that is the result column name */
97334       Table *pTab;         /* Table associated with this expression */
97335       while( pColExpr->op==TK_DOT ){
97336         pColExpr = pColExpr->pRight;
97337         assert( pColExpr!=0 );
97338       }
97339       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
97340         /* For columns use the column name name */
97341         int iCol = pColExpr->iColumn;
97342         pTab = pColExpr->pTab;
97343         if( iCol<0 ) iCol = pTab->iPKey;
97344         zName = sqlite3MPrintf(db, "%s",
97345                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
97346       }else if( pColExpr->op==TK_ID ){
97347         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
97348         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
97349       }else{
97350         /* Use the original text of the column expression as its name */
97351         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
97352       }
97353     }
97354     if( db->mallocFailed ){
97355       sqlite3DbFree(db, zName);
97356       break;
97357     }
97358
97359     /* Make sure the column name is unique.  If the name is not unique,
97360     ** append a integer to the name so that it becomes unique.
97361     */
97362     nName = sqlite3Strlen30(zName);
97363     for(j=cnt=0; j<i; j++){
97364       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
97365         char *zNewName;
97366         zName[nName] = 0;
97367         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
97368         sqlite3DbFree(db, zName);
97369         zName = zNewName;
97370         j = -1;
97371         if( zName==0 ) break;
97372       }
97373     }
97374     pCol->zName = zName;
97375   }
97376   if( db->mallocFailed ){
97377     for(j=0; j<i; j++){
97378       sqlite3DbFree(db, aCol[j].zName);
97379     }
97380     sqlite3DbFree(db, aCol);
97381     *paCol = 0;
97382     *pnCol = 0;
97383     return SQLITE_NOMEM;
97384   }
97385   return SQLITE_OK;
97386 }
97387
97388 /*
97389 ** Add type and collation information to a column list based on
97390 ** a SELECT statement.
97391 **
97392 ** The column list presumably came from selectColumnNamesFromExprList().
97393 ** The column list has only names, not types or collations.  This
97394 ** routine goes through and adds the types and collations.
97395 **
97396 ** This routine requires that all identifiers in the SELECT
97397 ** statement be resolved.
97398 */
97399 static void selectAddColumnTypeAndCollation(
97400   Parse *pParse,        /* Parsing contexts */
97401   int nCol,             /* Number of columns */
97402   Column *aCol,         /* List of columns */
97403   Select *pSelect       /* SELECT used to determine types and collations */
97404 ){
97405   sqlite3 *db = pParse->db;
97406   NameContext sNC;
97407   Column *pCol;
97408   CollSeq *pColl;
97409   int i;
97410   Expr *p;
97411   struct ExprList_item *a;
97412
97413   assert( pSelect!=0 );
97414   assert( (pSelect->selFlags & SF_Resolved)!=0 );
97415   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
97416   if( db->mallocFailed ) return;
97417   memset(&sNC, 0, sizeof(sNC));
97418   sNC.pSrcList = pSelect->pSrc;
97419   a = pSelect->pEList->a;
97420   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97421     p = a[i].pExpr;
97422     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
97423     pCol->affinity = sqlite3ExprAffinity(p);
97424     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
97425     pColl = sqlite3ExprCollSeq(pParse, p);
97426     if( pColl ){
97427       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
97428     }
97429   }
97430 }
97431
97432 /*
97433 ** Given a SELECT statement, generate a Table structure that describes
97434 ** the result set of that SELECT.
97435 */
97436 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
97437   Table *pTab;
97438   sqlite3 *db = pParse->db;
97439   int savedFlags;
97440
97441   savedFlags = db->flags;
97442   db->flags &= ~SQLITE_FullColNames;
97443   db->flags |= SQLITE_ShortColNames;
97444   sqlite3SelectPrep(pParse, pSelect, 0);
97445   if( pParse->nErr ) return 0;
97446   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
97447   db->flags = savedFlags;
97448   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
97449   if( pTab==0 ){
97450     return 0;
97451   }
97452   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
97453   ** is disabled */
97454   assert( db->lookaside.bEnabled==0 );
97455   pTab->nRef = 1;
97456   pTab->zName = 0;
97457   pTab->nRowEst = 1000000;
97458   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
97459   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
97460   pTab->iPKey = -1;
97461   if( db->mallocFailed ){
97462     sqlite3DeleteTable(db, pTab);
97463     return 0;
97464   }
97465   return pTab;
97466 }
97467
97468 /*
97469 ** Get a VDBE for the given parser context.  Create a new one if necessary.
97470 ** If an error occurs, return NULL and leave a message in pParse.
97471 */
97472 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
97473   Vdbe *v = pParse->pVdbe;
97474   if( v==0 ){
97475     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
97476 #ifndef SQLITE_OMIT_TRACE
97477     if( v ){
97478       sqlite3VdbeAddOp0(v, OP_Trace);
97479     }
97480 #endif
97481   }
97482   return v;
97483 }
97484
97485
97486 /*
97487 ** Compute the iLimit and iOffset fields of the SELECT based on the
97488 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
97489 ** that appear in the original SQL statement after the LIMIT and OFFSET
97490 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
97491 ** are the integer memory register numbers for counters used to compute
97492 ** the limit and offset.  If there is no limit and/or offset, then
97493 ** iLimit and iOffset are negative.
97494 **
97495 ** This routine changes the values of iLimit and iOffset only if
97496 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
97497 ** iOffset should have been preset to appropriate default values
97498 ** (usually but not always -1) prior to calling this routine.
97499 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
97500 ** redefined.  The UNION ALL operator uses this property to force
97501 ** the reuse of the same limit and offset registers across multiple
97502 ** SELECT statements.
97503 */
97504 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
97505   Vdbe *v = 0;
97506   int iLimit = 0;
97507   int iOffset;
97508   int addr1, n;
97509   if( p->iLimit ) return;
97510
97511   /*
97512   ** "LIMIT -1" always shows all rows.  There is some
97513   ** contraversy about what the correct behavior should be.
97514   ** The current implementation interprets "LIMIT 0" to mean
97515   ** no rows.
97516   */
97517   sqlite3ExprCacheClear(pParse);
97518   assert( p->pOffset==0 || p->pLimit!=0 );
97519   if( p->pLimit ){
97520     p->iLimit = iLimit = ++pParse->nMem;
97521     v = sqlite3GetVdbe(pParse);
97522     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
97523     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97524       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
97525       VdbeComment((v, "LIMIT counter"));
97526       if( n==0 ){
97527         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97528       }else{
97529         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
97530       }
97531     }else{
97532       sqlite3ExprCode(pParse, p->pLimit, iLimit);
97533       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
97534       VdbeComment((v, "LIMIT counter"));
97535       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
97536     }
97537     if( p->pOffset ){
97538       p->iOffset = iOffset = ++pParse->nMem;
97539       pParse->nMem++;   /* Allocate an extra register for limit+offset */
97540       sqlite3ExprCode(pParse, p->pOffset, iOffset);
97541       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
97542       VdbeComment((v, "OFFSET counter"));
97543       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
97544       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
97545       sqlite3VdbeJumpHere(v, addr1);
97546       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
97547       VdbeComment((v, "LIMIT+OFFSET"));
97548       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
97549       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
97550       sqlite3VdbeJumpHere(v, addr1);
97551     }
97552   }
97553 }
97554
97555 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97556 /*
97557 ** Return the appropriate collating sequence for the iCol-th column of
97558 ** the result set for the compound-select statement "p".  Return NULL if
97559 ** the column has no default collating sequence.
97560 **
97561 ** The collating sequence for the compound select is taken from the
97562 ** left-most term of the select that has a collating sequence.
97563 */
97564 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
97565   CollSeq *pRet;
97566   if( p->pPrior ){
97567     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
97568   }else{
97569     pRet = 0;
97570   }
97571   assert( iCol>=0 );
97572   if( pRet==0 && iCol<p->pEList->nExpr ){
97573     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
97574   }
97575   return pRet;
97576 }
97577 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
97578
97579 /* Forward reference */
97580 static int multiSelectOrderBy(
97581   Parse *pParse,        /* Parsing context */
97582   Select *p,            /* The right-most of SELECTs to be coded */
97583   SelectDest *pDest     /* What to do with query results */
97584 );
97585
97586
97587 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97588 /*
97589 ** This routine is called to process a compound query form from
97590 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
97591 ** INTERSECT
97592 **
97593 ** "p" points to the right-most of the two queries.  the query on the
97594 ** left is p->pPrior.  The left query could also be a compound query
97595 ** in which case this routine will be called recursively.
97596 **
97597 ** The results of the total query are to be written into a destination
97598 ** of type eDest with parameter iParm.
97599 **
97600 ** Example 1:  Consider a three-way compound SQL statement.
97601 **
97602 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
97603 **
97604 ** This statement is parsed up as follows:
97605 **
97606 **     SELECT c FROM t3
97607 **      |
97608 **      `----->  SELECT b FROM t2
97609 **                |
97610 **                `------>  SELECT a FROM t1
97611 **
97612 ** The arrows in the diagram above represent the Select.pPrior pointer.
97613 ** So if this routine is called with p equal to the t3 query, then
97614 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
97615 **
97616 ** Notice that because of the way SQLite parses compound SELECTs, the
97617 ** individual selects always group from left to right.
97618 */
97619 static int multiSelect(
97620   Parse *pParse,        /* Parsing context */
97621   Select *p,            /* The right-most of SELECTs to be coded */
97622   SelectDest *pDest     /* What to do with query results */
97623 ){
97624   int rc = SQLITE_OK;   /* Success code from a subroutine */
97625   Select *pPrior;       /* Another SELECT immediately to our left */
97626   Vdbe *v;              /* Generate code to this VDBE */
97627   SelectDest dest;      /* Alternative data destination */
97628   Select *pDelete = 0;  /* Chain of simple selects to delete */
97629   sqlite3 *db;          /* Database connection */
97630 #ifndef SQLITE_OMIT_EXPLAIN
97631   int iSub1;            /* EQP id of left-hand query */
97632   int iSub2;            /* EQP id of right-hand query */
97633 #endif
97634
97635   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
97636   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
97637   */
97638   assert( p && p->pPrior );  /* Calling function guarantees this much */
97639   db = pParse->db;
97640   pPrior = p->pPrior;
97641   assert( pPrior->pRightmost!=pPrior );
97642   assert( pPrior->pRightmost==p->pRightmost );
97643   dest = *pDest;
97644   if( pPrior->pOrderBy ){
97645     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
97646       selectOpName(p->op));
97647     rc = 1;
97648     goto multi_select_end;
97649   }
97650   if( pPrior->pLimit ){
97651     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
97652       selectOpName(p->op));
97653     rc = 1;
97654     goto multi_select_end;
97655   }
97656
97657   v = sqlite3GetVdbe(pParse);
97658   assert( v!=0 );  /* The VDBE already created by calling function */
97659
97660   /* Create the destination temporary table if necessary
97661   */
97662   if( dest.eDest==SRT_EphemTab ){
97663     assert( p->pEList );
97664     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
97665     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
97666     dest.eDest = SRT_Table;
97667   }
97668
97669   /* Make sure all SELECTs in the statement have the same number of elements
97670   ** in their result sets.
97671   */
97672   assert( p->pEList && pPrior->pEList );
97673   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
97674     if( p->selFlags & SF_Values ){
97675       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
97676     }else{
97677       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
97678         " do not have the same number of result columns", selectOpName(p->op));
97679     }
97680     rc = 1;
97681     goto multi_select_end;
97682   }
97683
97684   /* Compound SELECTs that have an ORDER BY clause are handled separately.
97685   */
97686   if( p->pOrderBy ){
97687     return multiSelectOrderBy(pParse, p, pDest);
97688   }
97689
97690   /* Generate code for the left and right SELECT statements.
97691   */
97692   switch( p->op ){
97693     case TK_ALL: {
97694       int addr = 0;
97695       int nLimit;
97696       assert( !pPrior->pLimit );
97697       pPrior->pLimit = p->pLimit;
97698       pPrior->pOffset = p->pOffset;
97699       explainSetInteger(iSub1, pParse->iNextSelectId);
97700       rc = sqlite3Select(pParse, pPrior, &dest);
97701       p->pLimit = 0;
97702       p->pOffset = 0;
97703       if( rc ){
97704         goto multi_select_end;
97705       }
97706       p->pPrior = 0;
97707       p->iLimit = pPrior->iLimit;
97708       p->iOffset = pPrior->iOffset;
97709       if( p->iLimit ){
97710         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
97711         VdbeComment((v, "Jump ahead if LIMIT reached"));
97712       }
97713       explainSetInteger(iSub2, pParse->iNextSelectId);
97714       rc = sqlite3Select(pParse, p, &dest);
97715       testcase( rc!=SQLITE_OK );
97716       pDelete = p->pPrior;
97717       p->pPrior = pPrior;
97718       p->nSelectRow += pPrior->nSelectRow;
97719       if( pPrior->pLimit
97720        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97721        && p->nSelectRow > (double)nLimit
97722       ){
97723         p->nSelectRow = (double)nLimit;
97724       }
97725       if( addr ){
97726         sqlite3VdbeJumpHere(v, addr);
97727       }
97728       break;
97729     }
97730     case TK_EXCEPT:
97731     case TK_UNION: {
97732       int unionTab;    /* Cursor number of the temporary table holding result */
97733       u8 op = 0;       /* One of the SRT_ operations to apply to self */
97734       int priorOp;     /* The SRT_ operation to apply to prior selects */
97735       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
97736       int addr;
97737       SelectDest uniondest;
97738
97739       testcase( p->op==TK_EXCEPT );
97740       testcase( p->op==TK_UNION );
97741       priorOp = SRT_Union;
97742       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
97743         /* We can reuse a temporary table generated by a SELECT to our
97744         ** right.
97745         */
97746         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
97747                                      ** of a 3-way or more compound */
97748         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
97749         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
97750         unionTab = dest.iSDParm;
97751       }else{
97752         /* We will need to create our own temporary table to hold the
97753         ** intermediate results.
97754         */
97755         unionTab = pParse->nTab++;
97756         assert( p->pOrderBy==0 );
97757         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
97758         assert( p->addrOpenEphm[0] == -1 );
97759         p->addrOpenEphm[0] = addr;
97760         p->pRightmost->selFlags |= SF_UsesEphemeral;
97761         assert( p->pEList );
97762       }
97763
97764       /* Code the SELECT statements to our left
97765       */
97766       assert( !pPrior->pOrderBy );
97767       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
97768       explainSetInteger(iSub1, pParse->iNextSelectId);
97769       rc = sqlite3Select(pParse, pPrior, &uniondest);
97770       if( rc ){
97771         goto multi_select_end;
97772       }
97773
97774       /* Code the current SELECT statement
97775       */
97776       if( p->op==TK_EXCEPT ){
97777         op = SRT_Except;
97778       }else{
97779         assert( p->op==TK_UNION );
97780         op = SRT_Union;
97781       }
97782       p->pPrior = 0;
97783       pLimit = p->pLimit;
97784       p->pLimit = 0;
97785       pOffset = p->pOffset;
97786       p->pOffset = 0;
97787       uniondest.eDest = op;
97788       explainSetInteger(iSub2, pParse->iNextSelectId);
97789       rc = sqlite3Select(pParse, p, &uniondest);
97790       testcase( rc!=SQLITE_OK );
97791       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
97792       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
97793       sqlite3ExprListDelete(db, p->pOrderBy);
97794       pDelete = p->pPrior;
97795       p->pPrior = pPrior;
97796       p->pOrderBy = 0;
97797       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
97798       sqlite3ExprDelete(db, p->pLimit);
97799       p->pLimit = pLimit;
97800       p->pOffset = pOffset;
97801       p->iLimit = 0;
97802       p->iOffset = 0;
97803
97804       /* Convert the data in the temporary table into whatever form
97805       ** it is that we currently need.
97806       */
97807       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
97808       if( dest.eDest!=priorOp ){
97809         int iCont, iBreak, iStart;
97810         assert( p->pEList );
97811         if( dest.eDest==SRT_Output ){
97812           Select *pFirst = p;
97813           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97814           generateColumnNames(pParse, 0, pFirst->pEList);
97815         }
97816         iBreak = sqlite3VdbeMakeLabel(v);
97817         iCont = sqlite3VdbeMakeLabel(v);
97818         computeLimitRegisters(pParse, p, iBreak);
97819         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
97820         iStart = sqlite3VdbeCurrentAddr(v);
97821         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
97822                         0, 0, &dest, iCont, iBreak);
97823         sqlite3VdbeResolveLabel(v, iCont);
97824         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
97825         sqlite3VdbeResolveLabel(v, iBreak);
97826         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
97827       }
97828       break;
97829     }
97830     default: assert( p->op==TK_INTERSECT ); {
97831       int tab1, tab2;
97832       int iCont, iBreak, iStart;
97833       Expr *pLimit, *pOffset;
97834       int addr;
97835       SelectDest intersectdest;
97836       int r1;
97837
97838       /* INTERSECT is different from the others since it requires
97839       ** two temporary tables.  Hence it has its own case.  Begin
97840       ** by allocating the tables we will need.
97841       */
97842       tab1 = pParse->nTab++;
97843       tab2 = pParse->nTab++;
97844       assert( p->pOrderBy==0 );
97845
97846       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
97847       assert( p->addrOpenEphm[0] == -1 );
97848       p->addrOpenEphm[0] = addr;
97849       p->pRightmost->selFlags |= SF_UsesEphemeral;
97850       assert( p->pEList );
97851
97852       /* Code the SELECTs to our left into temporary table "tab1".
97853       */
97854       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
97855       explainSetInteger(iSub1, pParse->iNextSelectId);
97856       rc = sqlite3Select(pParse, pPrior, &intersectdest);
97857       if( rc ){
97858         goto multi_select_end;
97859       }
97860
97861       /* Code the current SELECT into temporary table "tab2"
97862       */
97863       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
97864       assert( p->addrOpenEphm[1] == -1 );
97865       p->addrOpenEphm[1] = addr;
97866       p->pPrior = 0;
97867       pLimit = p->pLimit;
97868       p->pLimit = 0;
97869       pOffset = p->pOffset;
97870       p->pOffset = 0;
97871       intersectdest.iSDParm = tab2;
97872       explainSetInteger(iSub2, pParse->iNextSelectId);
97873       rc = sqlite3Select(pParse, p, &intersectdest);
97874       testcase( rc!=SQLITE_OK );
97875       pDelete = p->pPrior;
97876       p->pPrior = pPrior;
97877       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
97878       sqlite3ExprDelete(db, p->pLimit);
97879       p->pLimit = pLimit;
97880       p->pOffset = pOffset;
97881
97882       /* Generate code to take the intersection of the two temporary
97883       ** tables.
97884       */
97885       assert( p->pEList );
97886       if( dest.eDest==SRT_Output ){
97887         Select *pFirst = p;
97888         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97889         generateColumnNames(pParse, 0, pFirst->pEList);
97890       }
97891       iBreak = sqlite3VdbeMakeLabel(v);
97892       iCont = sqlite3VdbeMakeLabel(v);
97893       computeLimitRegisters(pParse, p, iBreak);
97894       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
97895       r1 = sqlite3GetTempReg(pParse);
97896       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
97897       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
97898       sqlite3ReleaseTempReg(pParse, r1);
97899       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
97900                       0, 0, &dest, iCont, iBreak);
97901       sqlite3VdbeResolveLabel(v, iCont);
97902       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
97903       sqlite3VdbeResolveLabel(v, iBreak);
97904       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
97905       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
97906       break;
97907     }
97908   }
97909
97910   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
97911
97912   /* Compute collating sequences used by
97913   ** temporary tables needed to implement the compound select.
97914   ** Attach the KeyInfo structure to all temporary tables.
97915   **
97916   ** This section is run by the right-most SELECT statement only.
97917   ** SELECT statements to the left always skip this part.  The right-most
97918   ** SELECT might also skip this part if it has no ORDER BY clause and
97919   ** no temp tables are required.
97920   */
97921   if( p->selFlags & SF_UsesEphemeral ){
97922     int i;                        /* Loop counter */
97923     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
97924     Select *pLoop;                /* For looping through SELECT statements */
97925     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
97926     int nCol;                     /* Number of columns in result set */
97927
97928     assert( p->pRightmost==p );
97929     nCol = p->pEList->nExpr;
97930     pKeyInfo = sqlite3DbMallocZero(db,
97931                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
97932     if( !pKeyInfo ){
97933       rc = SQLITE_NOMEM;
97934       goto multi_select_end;
97935     }
97936
97937     pKeyInfo->enc = ENC(db);
97938     pKeyInfo->nField = (u16)nCol;
97939
97940     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
97941       *apColl = multiSelectCollSeq(pParse, p, i);
97942       if( 0==*apColl ){
97943         *apColl = db->pDfltColl;
97944       }
97945     }
97946     pKeyInfo->aSortOrder = (u8*)apColl;
97947
97948     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
97949       for(i=0; i<2; i++){
97950         int addr = pLoop->addrOpenEphm[i];
97951         if( addr<0 ){
97952           /* If [0] is unused then [1] is also unused.  So we can
97953           ** always safely abort as soon as the first unused slot is found */
97954           assert( pLoop->addrOpenEphm[1]<0 );
97955           break;
97956         }
97957         sqlite3VdbeChangeP2(v, addr, nCol);
97958         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
97959         pLoop->addrOpenEphm[i] = -1;
97960       }
97961     }
97962     sqlite3DbFree(db, pKeyInfo);
97963   }
97964
97965 multi_select_end:
97966   pDest->iSdst = dest.iSdst;
97967   pDest->nSdst = dest.nSdst;
97968   sqlite3SelectDelete(db, pDelete);
97969   return rc;
97970 }
97971 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
97972
97973 /*
97974 ** Code an output subroutine for a coroutine implementation of a
97975 ** SELECT statment.
97976 **
97977 ** The data to be output is contained in pIn->iSdst.  There are
97978 ** pIn->nSdst columns to be output.  pDest is where the output should
97979 ** be sent.
97980 **
97981 ** regReturn is the number of the register holding the subroutine
97982 ** return address.
97983 **
97984 ** If regPrev>0 then it is the first register in a vector that
97985 ** records the previous output.  mem[regPrev] is a flag that is false
97986 ** if there has been no previous output.  If regPrev>0 then code is
97987 ** generated to suppress duplicates.  pKeyInfo is used for comparing
97988 ** keys.
97989 **
97990 ** If the LIMIT found in p->iLimit is reached, jump immediately to
97991 ** iBreak.
97992 */
97993 static int generateOutputSubroutine(
97994   Parse *pParse,          /* Parsing context */
97995   Select *p,              /* The SELECT statement */
97996   SelectDest *pIn,        /* Coroutine supplying data */
97997   SelectDest *pDest,      /* Where to send the data */
97998   int regReturn,          /* The return address register */
97999   int regPrev,            /* Previous result register.  No uniqueness if 0 */
98000   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
98001   int p4type,             /* The p4 type for pKeyInfo */
98002   int iBreak              /* Jump here if we hit the LIMIT */
98003 ){
98004   Vdbe *v = pParse->pVdbe;
98005   int iContinue;
98006   int addr;
98007
98008   addr = sqlite3VdbeCurrentAddr(v);
98009   iContinue = sqlite3VdbeMakeLabel(v);
98010
98011   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
98012   */
98013   if( regPrev ){
98014     int j1, j2;
98015     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
98016     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
98017                               (char*)pKeyInfo, p4type);
98018     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
98019     sqlite3VdbeJumpHere(v, j1);
98020     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
98021     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
98022   }
98023   if( pParse->db->mallocFailed ) return 0;
98024
98025   /* Suppress the first OFFSET entries if there is an OFFSET clause
98026   */
98027   codeOffset(v, p, iContinue);
98028
98029   switch( pDest->eDest ){
98030     /* Store the result as data using a unique key.
98031     */
98032     case SRT_Table:
98033     case SRT_EphemTab: {
98034       int r1 = sqlite3GetTempReg(pParse);
98035       int r2 = sqlite3GetTempReg(pParse);
98036       testcase( pDest->eDest==SRT_Table );
98037       testcase( pDest->eDest==SRT_EphemTab );
98038       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
98039       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
98040       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
98041       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98042       sqlite3ReleaseTempReg(pParse, r2);
98043       sqlite3ReleaseTempReg(pParse, r1);
98044       break;
98045     }
98046
98047 #ifndef SQLITE_OMIT_SUBQUERY
98048     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
98049     ** then there should be a single item on the stack.  Write this
98050     ** item into the set table with bogus data.
98051     */
98052     case SRT_Set: {
98053       int r1;
98054       assert( pIn->nSdst==1 );
98055       pDest->affSdst =
98056          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
98057       r1 = sqlite3GetTempReg(pParse);
98058       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
98059       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
98060       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
98061       sqlite3ReleaseTempReg(pParse, r1);
98062       break;
98063     }
98064
98065 #if 0  /* Never occurs on an ORDER BY query */
98066     /* If any row exist in the result set, record that fact and abort.
98067     */
98068     case SRT_Exists: {
98069       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
98070       /* The LIMIT clause will terminate the loop for us */
98071       break;
98072     }
98073 #endif
98074
98075     /* If this is a scalar select that is part of an expression, then
98076     ** store the results in the appropriate memory cell and break out
98077     ** of the scan loop.
98078     */
98079     case SRT_Mem: {
98080       assert( pIn->nSdst==1 );
98081       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
98082       /* The LIMIT clause will jump out of the loop for us */
98083       break;
98084     }
98085 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
98086
98087     /* The results are stored in a sequence of registers
98088     ** starting at pDest->iSdst.  Then the co-routine yields.
98089     */
98090     case SRT_Coroutine: {
98091       if( pDest->iSdst==0 ){
98092         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
98093         pDest->nSdst = pIn->nSdst;
98094       }
98095       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
98096       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
98097       break;
98098     }
98099
98100     /* If none of the above, then the result destination must be
98101     ** SRT_Output.  This routine is never called with any other
98102     ** destination other than the ones handled above or SRT_Output.
98103     **
98104     ** For SRT_Output, results are stored in a sequence of registers.
98105     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
98106     ** return the next row of result.
98107     */
98108     default: {
98109       assert( pDest->eDest==SRT_Output );
98110       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
98111       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
98112       break;
98113     }
98114   }
98115
98116   /* Jump to the end of the loop if the LIMIT is reached.
98117   */
98118   if( p->iLimit ){
98119     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
98120   }
98121
98122   /* Generate the subroutine return
98123   */
98124   sqlite3VdbeResolveLabel(v, iContinue);
98125   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
98126
98127   return addr;
98128 }
98129
98130 /*
98131 ** Alternative compound select code generator for cases when there
98132 ** is an ORDER BY clause.
98133 **
98134 ** We assume a query of the following form:
98135 **
98136 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
98137 **
98138 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
98139 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
98140 ** co-routines.  Then run the co-routines in parallel and merge the results
98141 ** into the output.  In addition to the two coroutines (called selectA and
98142 ** selectB) there are 7 subroutines:
98143 **
98144 **    outA:    Move the output of the selectA coroutine into the output
98145 **             of the compound query.
98146 **
98147 **    outB:    Move the output of the selectB coroutine into the output
98148 **             of the compound query.  (Only generated for UNION and
98149 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
98150 **             appears only in B.)
98151 **
98152 **    AltB:    Called when there is data from both coroutines and A<B.
98153 **
98154 **    AeqB:    Called when there is data from both coroutines and A==B.
98155 **
98156 **    AgtB:    Called when there is data from both coroutines and A>B.
98157 **
98158 **    EofA:    Called when data is exhausted from selectA.
98159 **
98160 **    EofB:    Called when data is exhausted from selectB.
98161 **
98162 ** The implementation of the latter five subroutines depend on which
98163 ** <operator> is used:
98164 **
98165 **
98166 **             UNION ALL         UNION            EXCEPT          INTERSECT
98167 **          -------------  -----------------  --------------  -----------------
98168 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
98169 **
98170 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
98171 **
98172 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
98173 **
98174 **   EofA:   outB, nextB      outB, nextB          halt             halt
98175 **
98176 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
98177 **
98178 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
98179 ** causes an immediate jump to EofA and an EOF on B following nextB causes
98180 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
98181 ** following nextX causes a jump to the end of the select processing.
98182 **
98183 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
98184 ** within the output subroutine.  The regPrev register set holds the previously
98185 ** output value.  A comparison is made against this value and the output
98186 ** is skipped if the next results would be the same as the previous.
98187 **
98188 ** The implementation plan is to implement the two coroutines and seven
98189 ** subroutines first, then put the control logic at the bottom.  Like this:
98190 **
98191 **          goto Init
98192 **     coA: coroutine for left query (A)
98193 **     coB: coroutine for right query (B)
98194 **    outA: output one row of A
98195 **    outB: output one row of B (UNION and UNION ALL only)
98196 **    EofA: ...
98197 **    EofB: ...
98198 **    AltB: ...
98199 **    AeqB: ...
98200 **    AgtB: ...
98201 **    Init: initialize coroutine registers
98202 **          yield coA
98203 **          if eof(A) goto EofA
98204 **          yield coB
98205 **          if eof(B) goto EofB
98206 **    Cmpr: Compare A, B
98207 **          Jump AltB, AeqB, AgtB
98208 **     End: ...
98209 **
98210 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
98211 ** actually called using Gosub and they do not Return.  EofA and EofB loop
98212 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
98213 ** and AgtB jump to either L2 or to one of EofA or EofB.
98214 */
98215 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98216 static int multiSelectOrderBy(
98217   Parse *pParse,        /* Parsing context */
98218   Select *p,            /* The right-most of SELECTs to be coded */
98219   SelectDest *pDest     /* What to do with query results */
98220 ){
98221   int i, j;             /* Loop counters */
98222   Select *pPrior;       /* Another SELECT immediately to our left */
98223   Vdbe *v;              /* Generate code to this VDBE */
98224   SelectDest destA;     /* Destination for coroutine A */
98225   SelectDest destB;     /* Destination for coroutine B */
98226   int regAddrA;         /* Address register for select-A coroutine */
98227   int regEofA;          /* Flag to indicate when select-A is complete */
98228   int regAddrB;         /* Address register for select-B coroutine */
98229   int regEofB;          /* Flag to indicate when select-B is complete */
98230   int addrSelectA;      /* Address of the select-A coroutine */
98231   int addrSelectB;      /* Address of the select-B coroutine */
98232   int regOutA;          /* Address register for the output-A subroutine */
98233   int regOutB;          /* Address register for the output-B subroutine */
98234   int addrOutA;         /* Address of the output-A subroutine */
98235   int addrOutB = 0;     /* Address of the output-B subroutine */
98236   int addrEofA;         /* Address of the select-A-exhausted subroutine */
98237   int addrEofB;         /* Address of the select-B-exhausted subroutine */
98238   int addrAltB;         /* Address of the A<B subroutine */
98239   int addrAeqB;         /* Address of the A==B subroutine */
98240   int addrAgtB;         /* Address of the A>B subroutine */
98241   int regLimitA;        /* Limit register for select-A */
98242   int regLimitB;        /* Limit register for select-A */
98243   int regPrev;          /* A range of registers to hold previous output */
98244   int savedLimit;       /* Saved value of p->iLimit */
98245   int savedOffset;      /* Saved value of p->iOffset */
98246   int labelCmpr;        /* Label for the start of the merge algorithm */
98247   int labelEnd;         /* Label for the end of the overall SELECT stmt */
98248   int j1;               /* Jump instructions that get retargetted */
98249   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
98250   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
98251   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
98252   sqlite3 *db;          /* Database connection */
98253   ExprList *pOrderBy;   /* The ORDER BY clause */
98254   int nOrderBy;         /* Number of terms in the ORDER BY clause */
98255   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
98256 #ifndef SQLITE_OMIT_EXPLAIN
98257   int iSub1;            /* EQP id of left-hand query */
98258   int iSub2;            /* EQP id of right-hand query */
98259 #endif
98260
98261   assert( p->pOrderBy!=0 );
98262   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
98263   db = pParse->db;
98264   v = pParse->pVdbe;
98265   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
98266   labelEnd = sqlite3VdbeMakeLabel(v);
98267   labelCmpr = sqlite3VdbeMakeLabel(v);
98268
98269
98270   /* Patch up the ORDER BY clause
98271   */
98272   op = p->op;
98273   pPrior = p->pPrior;
98274   assert( pPrior->pOrderBy==0 );
98275   pOrderBy = p->pOrderBy;
98276   assert( pOrderBy );
98277   nOrderBy = pOrderBy->nExpr;
98278
98279   /* For operators other than UNION ALL we have to make sure that
98280   ** the ORDER BY clause covers every term of the result set.  Add
98281   ** terms to the ORDER BY clause as necessary.
98282   */
98283   if( op!=TK_ALL ){
98284     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
98285       struct ExprList_item *pItem;
98286       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
98287         assert( pItem->iOrderByCol>0 );
98288         if( pItem->iOrderByCol==i ) break;
98289       }
98290       if( j==nOrderBy ){
98291         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
98292         if( pNew==0 ) return SQLITE_NOMEM;
98293         pNew->flags |= EP_IntValue;
98294         pNew->u.iValue = i;
98295         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
98296         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
98297       }
98298     }
98299   }
98300
98301   /* Compute the comparison permutation and keyinfo that is used with
98302   ** the permutation used to determine if the next
98303   ** row of results comes from selectA or selectB.  Also add explicit
98304   ** collations to the ORDER BY clause terms so that when the subqueries
98305   ** to the right and the left are evaluated, they use the correct
98306   ** collation.
98307   */
98308   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
98309   if( aPermute ){
98310     struct ExprList_item *pItem;
98311     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
98312       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
98313       aPermute[i] = pItem->iOrderByCol - 1;
98314     }
98315     pKeyMerge =
98316       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
98317     if( pKeyMerge ){
98318       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
98319       pKeyMerge->nField = (u16)nOrderBy;
98320       pKeyMerge->enc = ENC(db);
98321       for(i=0; i<nOrderBy; i++){
98322         CollSeq *pColl;
98323         Expr *pTerm = pOrderBy->a[i].pExpr;
98324         if( pTerm->flags & EP_Collate ){
98325           pColl = sqlite3ExprCollSeq(pParse, pTerm);
98326         }else{
98327           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
98328           if( pColl==0 ) pColl = db->pDfltColl;
98329           pOrderBy->a[i].pExpr =
98330              sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
98331         }
98332         pKeyMerge->aColl[i] = pColl;
98333         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
98334       }
98335     }
98336   }else{
98337     pKeyMerge = 0;
98338   }
98339
98340   /* Reattach the ORDER BY clause to the query.
98341   */
98342   p->pOrderBy = pOrderBy;
98343   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
98344
98345   /* Allocate a range of temporary registers and the KeyInfo needed
98346   ** for the logic that removes duplicate result rows when the
98347   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
98348   */
98349   if( op==TK_ALL ){
98350     regPrev = 0;
98351   }else{
98352     int nExpr = p->pEList->nExpr;
98353     assert( nOrderBy>=nExpr || db->mallocFailed );
98354     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
98355     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
98356     pKeyDup = sqlite3DbMallocZero(db,
98357                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
98358     if( pKeyDup ){
98359       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
98360       pKeyDup->nField = (u16)nExpr;
98361       pKeyDup->enc = ENC(db);
98362       for(i=0; i<nExpr; i++){
98363         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
98364         pKeyDup->aSortOrder[i] = 0;
98365       }
98366     }
98367   }
98368
98369   /* Separate the left and the right query from one another
98370   */
98371   p->pPrior = 0;
98372   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
98373   if( pPrior->pPrior==0 ){
98374     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
98375   }
98376
98377   /* Compute the limit registers */
98378   computeLimitRegisters(pParse, p, labelEnd);
98379   if( p->iLimit && op==TK_ALL ){
98380     regLimitA = ++pParse->nMem;
98381     regLimitB = ++pParse->nMem;
98382     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
98383                                   regLimitA);
98384     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
98385   }else{
98386     regLimitA = regLimitB = 0;
98387   }
98388   sqlite3ExprDelete(db, p->pLimit);
98389   p->pLimit = 0;
98390   sqlite3ExprDelete(db, p->pOffset);
98391   p->pOffset = 0;
98392
98393   regAddrA = ++pParse->nMem;
98394   regEofA = ++pParse->nMem;
98395   regAddrB = ++pParse->nMem;
98396   regEofB = ++pParse->nMem;
98397   regOutA = ++pParse->nMem;
98398   regOutB = ++pParse->nMem;
98399   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
98400   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
98401
98402   /* Jump past the various subroutines and coroutines to the main
98403   ** merge loop
98404   */
98405   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
98406   addrSelectA = sqlite3VdbeCurrentAddr(v);
98407
98408
98409   /* Generate a coroutine to evaluate the SELECT statement to the
98410   ** left of the compound operator - the "A" select.
98411   */
98412   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
98413   pPrior->iLimit = regLimitA;
98414   explainSetInteger(iSub1, pParse->iNextSelectId);
98415   sqlite3Select(pParse, pPrior, &destA);
98416   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
98417   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98418   VdbeNoopComment((v, "End coroutine for left SELECT"));
98419
98420   /* Generate a coroutine to evaluate the SELECT statement on
98421   ** the right - the "B" select
98422   */
98423   addrSelectB = sqlite3VdbeCurrentAddr(v);
98424   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
98425   savedLimit = p->iLimit;
98426   savedOffset = p->iOffset;
98427   p->iLimit = regLimitB;
98428   p->iOffset = 0;
98429   explainSetInteger(iSub2, pParse->iNextSelectId);
98430   sqlite3Select(pParse, p, &destB);
98431   p->iLimit = savedLimit;
98432   p->iOffset = savedOffset;
98433   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
98434   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98435   VdbeNoopComment((v, "End coroutine for right SELECT"));
98436
98437   /* Generate a subroutine that outputs the current row of the A
98438   ** select as the next output row of the compound select.
98439   */
98440   VdbeNoopComment((v, "Output routine for A"));
98441   addrOutA = generateOutputSubroutine(pParse,
98442                  p, &destA, pDest, regOutA,
98443                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
98444
98445   /* Generate a subroutine that outputs the current row of the B
98446   ** select as the next output row of the compound select.
98447   */
98448   if( op==TK_ALL || op==TK_UNION ){
98449     VdbeNoopComment((v, "Output routine for B"));
98450     addrOutB = generateOutputSubroutine(pParse,
98451                  p, &destB, pDest, regOutB,
98452                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
98453   }
98454
98455   /* Generate a subroutine to run when the results from select A
98456   ** are exhausted and only data in select B remains.
98457   */
98458   VdbeNoopComment((v, "eof-A subroutine"));
98459   if( op==TK_EXCEPT || op==TK_INTERSECT ){
98460     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
98461   }else{
98462     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
98463     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98464     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98465     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
98466     p->nSelectRow += pPrior->nSelectRow;
98467   }
98468
98469   /* Generate a subroutine to run when the results from select B
98470   ** are exhausted and only data in select A remains.
98471   */
98472   if( op==TK_INTERSECT ){
98473     addrEofB = addrEofA;
98474     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
98475   }else{
98476     VdbeNoopComment((v, "eof-B subroutine"));
98477     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
98478     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98479     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98480     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
98481   }
98482
98483   /* Generate code to handle the case of A<B
98484   */
98485   VdbeNoopComment((v, "A-lt-B subroutine"));
98486   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98487   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98488   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98489   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98490
98491   /* Generate code to handle the case of A==B
98492   */
98493   if( op==TK_ALL ){
98494     addrAeqB = addrAltB;
98495   }else if( op==TK_INTERSECT ){
98496     addrAeqB = addrAltB;
98497     addrAltB++;
98498   }else{
98499     VdbeNoopComment((v, "A-eq-B subroutine"));
98500     addrAeqB =
98501     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98502     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98503     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98504   }
98505
98506   /* Generate code to handle the case of A>B
98507   */
98508   VdbeNoopComment((v, "A-gt-B subroutine"));
98509   addrAgtB = sqlite3VdbeCurrentAddr(v);
98510   if( op==TK_ALL || op==TK_UNION ){
98511     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98512   }
98513   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98514   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98515   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98516
98517   /* This code runs once to initialize everything.
98518   */
98519   sqlite3VdbeJumpHere(v, j1);
98520   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
98521   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
98522   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
98523   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
98524   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98525   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98526
98527   /* Implement the main merge loop
98528   */
98529   sqlite3VdbeResolveLabel(v, labelCmpr);
98530   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
98531   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
98532                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
98533   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
98534   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
98535
98536   /* Release temporary registers
98537   */
98538   if( regPrev ){
98539     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
98540   }
98541
98542   /* Jump to the this point in order to terminate the query.
98543   */
98544   sqlite3VdbeResolveLabel(v, labelEnd);
98545
98546   /* Set the number of output columns
98547   */
98548   if( pDest->eDest==SRT_Output ){
98549     Select *pFirst = pPrior;
98550     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
98551     generateColumnNames(pParse, 0, pFirst->pEList);
98552   }
98553
98554   /* Reassembly the compound query so that it will be freed correctly
98555   ** by the calling function */
98556   if( p->pPrior ){
98557     sqlite3SelectDelete(db, p->pPrior);
98558   }
98559   p->pPrior = pPrior;
98560
98561   /*** TBD:  Insert subroutine calls to close cursors on incomplete
98562   **** subqueries ****/
98563   explainComposite(pParse, p->op, iSub1, iSub2, 0);
98564   return SQLITE_OK;
98565 }
98566 #endif
98567
98568 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98569 /* Forward Declarations */
98570 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
98571 static void substSelect(sqlite3*, Select *, int, ExprList *);
98572
98573 /*
98574 ** Scan through the expression pExpr.  Replace every reference to
98575 ** a column in table number iTable with a copy of the iColumn-th
98576 ** entry in pEList.  (But leave references to the ROWID column
98577 ** unchanged.)
98578 **
98579 ** This routine is part of the flattening procedure.  A subquery
98580 ** whose result set is defined by pEList appears as entry in the
98581 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
98582 ** FORM clause entry is iTable.  This routine make the necessary
98583 ** changes to pExpr so that it refers directly to the source table
98584 ** of the subquery rather the result set of the subquery.
98585 */
98586 static Expr *substExpr(
98587   sqlite3 *db,        /* Report malloc errors to this connection */
98588   Expr *pExpr,        /* Expr in which substitution occurs */
98589   int iTable,         /* Table to be substituted */
98590   ExprList *pEList    /* Substitute expressions */
98591 ){
98592   if( pExpr==0 ) return 0;
98593   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
98594     if( pExpr->iColumn<0 ){
98595       pExpr->op = TK_NULL;
98596     }else{
98597       Expr *pNew;
98598       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
98599       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
98600       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
98601       sqlite3ExprDelete(db, pExpr);
98602       pExpr = pNew;
98603     }
98604   }else{
98605     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
98606     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
98607     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98608       substSelect(db, pExpr->x.pSelect, iTable, pEList);
98609     }else{
98610       substExprList(db, pExpr->x.pList, iTable, pEList);
98611     }
98612   }
98613   return pExpr;
98614 }
98615 static void substExprList(
98616   sqlite3 *db,         /* Report malloc errors here */
98617   ExprList *pList,     /* List to scan and in which to make substitutes */
98618   int iTable,          /* Table to be substituted */
98619   ExprList *pEList     /* Substitute values */
98620 ){
98621   int i;
98622   if( pList==0 ) return;
98623   for(i=0; i<pList->nExpr; i++){
98624     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
98625   }
98626 }
98627 static void substSelect(
98628   sqlite3 *db,         /* Report malloc errors here */
98629   Select *p,           /* SELECT statement in which to make substitutions */
98630   int iTable,          /* Table to be replaced */
98631   ExprList *pEList     /* Substitute values */
98632 ){
98633   SrcList *pSrc;
98634   struct SrcList_item *pItem;
98635   int i;
98636   if( !p ) return;
98637   substExprList(db, p->pEList, iTable, pEList);
98638   substExprList(db, p->pGroupBy, iTable, pEList);
98639   substExprList(db, p->pOrderBy, iTable, pEList);
98640   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
98641   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
98642   substSelect(db, p->pPrior, iTable, pEList);
98643   pSrc = p->pSrc;
98644   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
98645   if( ALWAYS(pSrc) ){
98646     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
98647       substSelect(db, pItem->pSelect, iTable, pEList);
98648     }
98649   }
98650 }
98651 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
98652
98653 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98654 /*
98655 ** This routine attempts to flatten subqueries as a performance optimization.
98656 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
98657 **
98658 ** To understand the concept of flattening, consider the following
98659 ** query:
98660 **
98661 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
98662 **
98663 ** The default way of implementing this query is to execute the
98664 ** subquery first and store the results in a temporary table, then
98665 ** run the outer query on that temporary table.  This requires two
98666 ** passes over the data.  Furthermore, because the temporary table
98667 ** has no indices, the WHERE clause on the outer query cannot be
98668 ** optimized.
98669 **
98670 ** This routine attempts to rewrite queries such as the above into
98671 ** a single flat select, like this:
98672 **
98673 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
98674 **
98675 ** The code generated for this simpification gives the same result
98676 ** but only has to scan the data once.  And because indices might
98677 ** exist on the table t1, a complete scan of the data might be
98678 ** avoided.
98679 **
98680 ** Flattening is only attempted if all of the following are true:
98681 **
98682 **   (1)  The subquery and the outer query do not both use aggregates.
98683 **
98684 **   (2)  The subquery is not an aggregate or the outer query is not a join.
98685 **
98686 **   (3)  The subquery is not the right operand of a left outer join
98687 **        (Originally ticket #306.  Strengthened by ticket #3300)
98688 **
98689 **   (4)  The subquery is not DISTINCT.
98690 **
98691 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
98692 **        sub-queries that were excluded from this optimization. Restriction
98693 **        (4) has since been expanded to exclude all DISTINCT subqueries.
98694 **
98695 **   (6)  The subquery does not use aggregates or the outer query is not
98696 **        DISTINCT.
98697 **
98698 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
98699 **        A FROM clause, consider adding a FROM close with the special
98700 **        table sqlite_once that consists of a single row containing a
98701 **        single NULL.
98702 **
98703 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
98704 **
98705 **   (9)  The subquery does not use LIMIT or the outer query does not use
98706 **        aggregates.
98707 **
98708 **  (10)  The subquery does not use aggregates or the outer query does not
98709 **        use LIMIT.
98710 **
98711 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
98712 **
98713 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
98714 **        a separate restriction deriving from ticket #350.
98715 **
98716 **  (13)  The subquery and outer query do not both use LIMIT.
98717 **
98718 **  (14)  The subquery does not use OFFSET.
98719 **
98720 **  (15)  The outer query is not part of a compound select or the
98721 **        subquery does not have a LIMIT clause.
98722 **        (See ticket #2339 and ticket [02a8e81d44]).
98723 **
98724 **  (16)  The outer query is not an aggregate or the subquery does
98725 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
98726 **        until we introduced the group_concat() function.
98727 **
98728 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
98729 **        compound clause made up entirely of non-aggregate queries, and
98730 **        the parent query:
98731 **
98732 **          * is not itself part of a compound select,
98733 **          * is not an aggregate or DISTINCT query, and
98734 **          * is not a join
98735 **
98736 **        The parent and sub-query may contain WHERE clauses. Subject to
98737 **        rules (11), (13) and (14), they may also contain ORDER BY,
98738 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
98739 **        operator other than UNION ALL because all the other compound
98740 **        operators have an implied DISTINCT which is disallowed by
98741 **        restriction (4).
98742 **
98743 **        Also, each component of the sub-query must return the same number
98744 **        of result columns. This is actually a requirement for any compound
98745 **        SELECT statement, but all the code here does is make sure that no
98746 **        such (illegal) sub-query is flattened. The caller will detect the
98747 **        syntax error and return a detailed message.
98748 **
98749 **  (18)  If the sub-query is a compound select, then all terms of the
98750 **        ORDER by clause of the parent must be simple references to
98751 **        columns of the sub-query.
98752 **
98753 **  (19)  The subquery does not use LIMIT or the outer query does not
98754 **        have a WHERE clause.
98755 **
98756 **  (20)  If the sub-query is a compound select, then it must not use
98757 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
98758 **        somewhat by saying that the terms of the ORDER BY clause must
98759 **        appear as unmodified result columns in the outer query.  But we
98760 **        have other optimizations in mind to deal with that case.
98761 **
98762 **  (21)  The subquery does not use LIMIT or the outer query is not
98763 **        DISTINCT.  (See ticket [752e1646fc]).
98764 **
98765 ** In this routine, the "p" parameter is a pointer to the outer query.
98766 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
98767 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
98768 **
98769 ** If flattening is not attempted, this routine is a no-op and returns 0.
98770 ** If flattening is attempted this routine returns 1.
98771 **
98772 ** All of the expression analysis must occur on both the outer query and
98773 ** the subquery before this routine runs.
98774 */
98775 static int flattenSubquery(
98776   Parse *pParse,       /* Parsing context */
98777   Select *p,           /* The parent or outer SELECT statement */
98778   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
98779   int isAgg,           /* True if outer SELECT uses aggregate functions */
98780   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
98781 ){
98782   const char *zSavedAuthContext = pParse->zAuthContext;
98783   Select *pParent;
98784   Select *pSub;       /* The inner query or "subquery" */
98785   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
98786   SrcList *pSrc;      /* The FROM clause of the outer query */
98787   SrcList *pSubSrc;   /* The FROM clause of the subquery */
98788   ExprList *pList;    /* The result set of the outer query */
98789   int iParent;        /* VDBE cursor number of the pSub result set temp table */
98790   int i;              /* Loop counter */
98791   Expr *pWhere;                    /* The WHERE clause */
98792   struct SrcList_item *pSubitem;   /* The subquery */
98793   sqlite3 *db = pParse->db;
98794
98795   /* Check to see if flattening is permitted.  Return 0 if not.
98796   */
98797   assert( p!=0 );
98798   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
98799   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
98800   pSrc = p->pSrc;
98801   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
98802   pSubitem = &pSrc->a[iFrom];
98803   iParent = pSubitem->iCursor;
98804   pSub = pSubitem->pSelect;
98805   assert( pSub!=0 );
98806   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
98807   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
98808   pSubSrc = pSub->pSrc;
98809   assert( pSubSrc );
98810   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
98811   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
98812   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
98813   ** became arbitrary expressions, we were forced to add restrictions (13)
98814   ** and (14). */
98815   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
98816   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
98817   if( p->pRightmost && pSub->pLimit ){
98818     return 0;                                            /* Restriction (15) */
98819   }
98820   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
98821   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
98822   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
98823      return 0;         /* Restrictions (8)(9) */
98824   }
98825   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
98826      return 0;         /* Restriction (6)  */
98827   }
98828   if( p->pOrderBy && pSub->pOrderBy ){
98829      return 0;                                           /* Restriction (11) */
98830   }
98831   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
98832   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
98833   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
98834      return 0;         /* Restriction (21) */
98835   }
98836
98837   /* OBSOLETE COMMENT 1:
98838   ** Restriction 3:  If the subquery is a join, make sure the subquery is
98839   ** not used as the right operand of an outer join.  Examples of why this
98840   ** is not allowed:
98841   **
98842   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
98843   **
98844   ** If we flatten the above, we would get
98845   **
98846   **         (t1 LEFT OUTER JOIN t2) JOIN t3
98847   **
98848   ** which is not at all the same thing.
98849   **
98850   ** OBSOLETE COMMENT 2:
98851   ** Restriction 12:  If the subquery is the right operand of a left outer
98852   ** join, make sure the subquery has no WHERE clause.
98853   ** An examples of why this is not allowed:
98854   **
98855   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
98856   **
98857   ** If we flatten the above, we would get
98858   **
98859   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
98860   **
98861   ** But the t2.x>0 test will always fail on a NULL row of t2, which
98862   ** effectively converts the OUTER JOIN into an INNER JOIN.
98863   **
98864   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
98865   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
98866   ** is fraught with danger.  Best to avoid the whole thing.  If the
98867   ** subquery is the right term of a LEFT JOIN, then do not flatten.
98868   */
98869   if( (pSubitem->jointype & JT_OUTER)!=0 ){
98870     return 0;
98871   }
98872
98873   /* Restriction 17: If the sub-query is a compound SELECT, then it must
98874   ** use only the UNION ALL operator. And none of the simple select queries
98875   ** that make up the compound SELECT are allowed to be aggregate or distinct
98876   ** queries.
98877   */
98878   if( pSub->pPrior ){
98879     if( pSub->pOrderBy ){
98880       return 0;  /* Restriction 20 */
98881     }
98882     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
98883       return 0;
98884     }
98885     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
98886       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
98887       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
98888       assert( pSub->pSrc!=0 );
98889       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
98890        || (pSub1->pPrior && pSub1->op!=TK_ALL)
98891        || pSub1->pSrc->nSrc<1
98892        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
98893       ){
98894         return 0;
98895       }
98896       testcase( pSub1->pSrc->nSrc>1 );
98897     }
98898
98899     /* Restriction 18. */
98900     if( p->pOrderBy ){
98901       int ii;
98902       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
98903         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
98904       }
98905     }
98906   }
98907
98908   /***** If we reach this point, flattening is permitted. *****/
98909
98910   /* Authorize the subquery */
98911   pParse->zAuthContext = pSubitem->zName;
98912   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
98913   testcase( i==SQLITE_DENY );
98914   pParse->zAuthContext = zSavedAuthContext;
98915
98916   /* If the sub-query is a compound SELECT statement, then (by restrictions
98917   ** 17 and 18 above) it must be a UNION ALL and the parent query must
98918   ** be of the form:
98919   **
98920   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
98921   **
98922   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
98923   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
98924   ** OFFSET clauses and joins them to the left-hand-side of the original
98925   ** using UNION ALL operators. In this case N is the number of simple
98926   ** select statements in the compound sub-query.
98927   **
98928   ** Example:
98929   **
98930   **     SELECT a+1 FROM (
98931   **        SELECT x FROM tab
98932   **        UNION ALL
98933   **        SELECT y FROM tab
98934   **        UNION ALL
98935   **        SELECT abs(z*2) FROM tab2
98936   **     ) WHERE a!=5 ORDER BY 1
98937   **
98938   ** Transformed into:
98939   **
98940   **     SELECT x+1 FROM tab WHERE x+1!=5
98941   **     UNION ALL
98942   **     SELECT y+1 FROM tab WHERE y+1!=5
98943   **     UNION ALL
98944   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
98945   **     ORDER BY 1
98946   **
98947   ** We call this the "compound-subquery flattening".
98948   */
98949   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
98950     Select *pNew;
98951     ExprList *pOrderBy = p->pOrderBy;
98952     Expr *pLimit = p->pLimit;
98953     Select *pPrior = p->pPrior;
98954     p->pOrderBy = 0;
98955     p->pSrc = 0;
98956     p->pPrior = 0;
98957     p->pLimit = 0;
98958     pNew = sqlite3SelectDup(db, p, 0);
98959     p->pLimit = pLimit;
98960     p->pOrderBy = pOrderBy;
98961     p->pSrc = pSrc;
98962     p->op = TK_ALL;
98963     p->pRightmost = 0;
98964     if( pNew==0 ){
98965       pNew = pPrior;
98966     }else{
98967       pNew->pPrior = pPrior;
98968       pNew->pRightmost = 0;
98969     }
98970     p->pPrior = pNew;
98971     if( db->mallocFailed ) return 1;
98972   }
98973
98974   /* Begin flattening the iFrom-th entry of the FROM clause
98975   ** in the outer query.
98976   */
98977   pSub = pSub1 = pSubitem->pSelect;
98978
98979   /* Delete the transient table structure associated with the
98980   ** subquery
98981   */
98982   sqlite3DbFree(db, pSubitem->zDatabase);
98983   sqlite3DbFree(db, pSubitem->zName);
98984   sqlite3DbFree(db, pSubitem->zAlias);
98985   pSubitem->zDatabase = 0;
98986   pSubitem->zName = 0;
98987   pSubitem->zAlias = 0;
98988   pSubitem->pSelect = 0;
98989
98990   /* Defer deleting the Table object associated with the
98991   ** subquery until code generation is
98992   ** complete, since there may still exist Expr.pTab entries that
98993   ** refer to the subquery even after flattening.  Ticket #3346.
98994   **
98995   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
98996   */
98997   if( ALWAYS(pSubitem->pTab!=0) ){
98998     Table *pTabToDel = pSubitem->pTab;
98999     if( pTabToDel->nRef==1 ){
99000       Parse *pToplevel = sqlite3ParseToplevel(pParse);
99001       pTabToDel->pNextZombie = pToplevel->pZombieTab;
99002       pToplevel->pZombieTab = pTabToDel;
99003     }else{
99004       pTabToDel->nRef--;
99005     }
99006     pSubitem->pTab = 0;
99007   }
99008
99009   /* The following loop runs once for each term in a compound-subquery
99010   ** flattening (as described above).  If we are doing a different kind
99011   ** of flattening - a flattening other than a compound-subquery flattening -
99012   ** then this loop only runs once.
99013   **
99014   ** This loop moves all of the FROM elements of the subquery into the
99015   ** the FROM clause of the outer query.  Before doing this, remember
99016   ** the cursor number for the original outer query FROM element in
99017   ** iParent.  The iParent cursor will never be used.  Subsequent code
99018   ** will scan expressions looking for iParent references and replace
99019   ** those references with expressions that resolve to the subquery FROM
99020   ** elements we are now copying in.
99021   */
99022   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
99023     int nSubSrc;
99024     u8 jointype = 0;
99025     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
99026     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
99027     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
99028
99029     if( pSrc ){
99030       assert( pParent==p );  /* First time through the loop */
99031       jointype = pSubitem->jointype;
99032     }else{
99033       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
99034       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
99035       if( pSrc==0 ){
99036         assert( db->mallocFailed );
99037         break;
99038       }
99039     }
99040
99041     /* The subquery uses a single slot of the FROM clause of the outer
99042     ** query.  If the subquery has more than one element in its FROM clause,
99043     ** then expand the outer query to make space for it to hold all elements
99044     ** of the subquery.
99045     **
99046     ** Example:
99047     **
99048     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
99049     **
99050     ** The outer query has 3 slots in its FROM clause.  One slot of the
99051     ** outer query (the middle slot) is used by the subquery.  The next
99052     ** block of code will expand the out query to 4 slots.  The middle
99053     ** slot is expanded to two slots in order to make space for the
99054     ** two elements in the FROM clause of the subquery.
99055     */
99056     if( nSubSrc>1 ){
99057       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
99058       if( db->mallocFailed ){
99059         break;
99060       }
99061     }
99062
99063     /* Transfer the FROM clause terms from the subquery into the
99064     ** outer query.
99065     */
99066     for(i=0; i<nSubSrc; i++){
99067       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
99068       pSrc->a[i+iFrom] = pSubSrc->a[i];
99069       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
99070     }
99071     pSrc->a[iFrom].jointype = jointype;
99072
99073     /* Now begin substituting subquery result set expressions for
99074     ** references to the iParent in the outer query.
99075     **
99076     ** Example:
99077     **
99078     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
99079     **   \                     \_____________ subquery __________/          /
99080     **    \_____________________ outer query ______________________________/
99081     **
99082     ** We look at every expression in the outer query and every place we see
99083     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
99084     */
99085     pList = pParent->pEList;
99086     for(i=0; i<pList->nExpr; i++){
99087       if( pList->a[i].zName==0 ){
99088         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
99089         sqlite3Dequote(zName);
99090         pList->a[i].zName = zName;
99091       }
99092     }
99093     substExprList(db, pParent->pEList, iParent, pSub->pEList);
99094     if( isAgg ){
99095       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
99096       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99097     }
99098     if( pSub->pOrderBy ){
99099       assert( pParent->pOrderBy==0 );
99100       pParent->pOrderBy = pSub->pOrderBy;
99101       pSub->pOrderBy = 0;
99102     }else if( pParent->pOrderBy ){
99103       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
99104     }
99105     if( pSub->pWhere ){
99106       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
99107     }else{
99108       pWhere = 0;
99109     }
99110     if( subqueryIsAgg ){
99111       assert( pParent->pHaving==0 );
99112       pParent->pHaving = pParent->pWhere;
99113       pParent->pWhere = pWhere;
99114       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99115       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
99116                                   sqlite3ExprDup(db, pSub->pHaving, 0));
99117       assert( pParent->pGroupBy==0 );
99118       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
99119     }else{
99120       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
99121       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
99122     }
99123
99124     /* The flattened query is distinct if either the inner or the
99125     ** outer query is distinct.
99126     */
99127     pParent->selFlags |= pSub->selFlags & SF_Distinct;
99128
99129     /*
99130     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
99131     **
99132     ** One is tempted to try to add a and b to combine the limits.  But this
99133     ** does not work if either limit is negative.
99134     */
99135     if( pSub->pLimit ){
99136       pParent->pLimit = pSub->pLimit;
99137       pSub->pLimit = 0;
99138     }
99139   }
99140
99141   /* Finially, delete what is left of the subquery and return
99142   ** success.
99143   */
99144   sqlite3SelectDelete(db, pSub1);
99145
99146   return 1;
99147 }
99148 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
99149
99150 /*
99151 ** Analyze the SELECT statement passed as an argument to see if it
99152 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
99153 ** it is, or 0 otherwise. At present, a query is considered to be
99154 ** a min()/max() query if:
99155 **
99156 **   1. There is a single object in the FROM clause.
99157 **
99158 **   2. There is a single expression in the result set, and it is
99159 **      either min(x) or max(x), where x is a column reference.
99160 */
99161 static u8 minMaxQuery(Select *p){
99162   Expr *pExpr;
99163   ExprList *pEList = p->pEList;
99164
99165   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
99166   pExpr = pEList->a[0].pExpr;
99167   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
99168   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
99169   pEList = pExpr->x.pList;
99170   if( pEList==0 || pEList->nExpr!=1 ) return 0;
99171   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
99172   assert( !ExprHasProperty(pExpr, EP_IntValue) );
99173   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
99174     return WHERE_ORDERBY_MIN;
99175   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
99176     return WHERE_ORDERBY_MAX;
99177   }
99178   return WHERE_ORDERBY_NORMAL;
99179 }
99180
99181 /*
99182 ** The select statement passed as the first argument is an aggregate query.
99183 ** The second argment is the associated aggregate-info object. This
99184 ** function tests if the SELECT is of the form:
99185 **
99186 **   SELECT count(*) FROM <tbl>
99187 **
99188 ** where table is a database table, not a sub-select or view. If the query
99189 ** does match this pattern, then a pointer to the Table object representing
99190 ** <tbl> is returned. Otherwise, 0 is returned.
99191 */
99192 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
99193   Table *pTab;
99194   Expr *pExpr;
99195
99196   assert( !p->pGroupBy );
99197
99198   if( p->pWhere || p->pEList->nExpr!=1
99199    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
99200   ){
99201     return 0;
99202   }
99203   pTab = p->pSrc->a[0].pTab;
99204   pExpr = p->pEList->a[0].pExpr;
99205   assert( pTab && !pTab->pSelect && pExpr );
99206
99207   if( IsVirtual(pTab) ) return 0;
99208   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
99209   if( NEVER(pAggInfo->nFunc==0) ) return 0;
99210   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
99211   if( pExpr->flags&EP_Distinct ) return 0;
99212
99213   return pTab;
99214 }
99215
99216 /*
99217 ** If the source-list item passed as an argument was augmented with an
99218 ** INDEXED BY clause, then try to locate the specified index. If there
99219 ** was such a clause and the named index cannot be found, return
99220 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
99221 ** pFrom->pIndex and return SQLITE_OK.
99222 */
99223 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
99224   if( pFrom->pTab && pFrom->zIndex ){
99225     Table *pTab = pFrom->pTab;
99226     char *zIndex = pFrom->zIndex;
99227     Index *pIdx;
99228     for(pIdx=pTab->pIndex;
99229         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
99230         pIdx=pIdx->pNext
99231     );
99232     if( !pIdx ){
99233       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
99234       pParse->checkSchema = 1;
99235       return SQLITE_ERROR;
99236     }
99237     pFrom->pIndex = pIdx;
99238   }
99239   return SQLITE_OK;
99240 }
99241
99242 /*
99243 ** This routine is a Walker callback for "expanding" a SELECT statement.
99244 ** "Expanding" means to do the following:
99245 **
99246 **    (1)  Make sure VDBE cursor numbers have been assigned to every
99247 **         element of the FROM clause.
99248 **
99249 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
99250 **         defines FROM clause.  When views appear in the FROM clause,
99251 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
99252 **         that implements the view.  A copy is made of the view's SELECT
99253 **         statement so that we can freely modify or delete that statement
99254 **         without worrying about messing up the presistent representation
99255 **         of the view.
99256 **
99257 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
99258 **         on joins and the ON and USING clause of joins.
99259 **
99260 **    (4)  Scan the list of columns in the result set (pEList) looking
99261 **         for instances of the "*" operator or the TABLE.* operator.
99262 **         If found, expand each "*" to be every column in every table
99263 **         and TABLE.* to be every column in TABLE.
99264 **
99265 */
99266 static int selectExpander(Walker *pWalker, Select *p){
99267   Parse *pParse = pWalker->pParse;
99268   int i, j, k;
99269   SrcList *pTabList;
99270   ExprList *pEList;
99271   struct SrcList_item *pFrom;
99272   sqlite3 *db = pParse->db;
99273
99274   if( db->mallocFailed  ){
99275     return WRC_Abort;
99276   }
99277   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
99278     return WRC_Prune;
99279   }
99280   p->selFlags |= SF_Expanded;
99281   pTabList = p->pSrc;
99282   pEList = p->pEList;
99283
99284   /* Make sure cursor numbers have been assigned to all entries in
99285   ** the FROM clause of the SELECT statement.
99286   */
99287   sqlite3SrcListAssignCursors(pParse, pTabList);
99288
99289   /* Look up every table named in the FROM clause of the select.  If
99290   ** an entry of the FROM clause is a subquery instead of a table or view,
99291   ** then create a transient table structure to describe the subquery.
99292   */
99293   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99294     Table *pTab;
99295     if( pFrom->pTab!=0 ){
99296       /* This statement has already been prepared.  There is no need
99297       ** to go further. */
99298       assert( i==0 );
99299       return WRC_Prune;
99300     }
99301     if( pFrom->zName==0 ){
99302 #ifndef SQLITE_OMIT_SUBQUERY
99303       Select *pSel = pFrom->pSelect;
99304       /* A sub-query in the FROM clause of a SELECT */
99305       assert( pSel!=0 );
99306       assert( pFrom->pTab==0 );
99307       sqlite3WalkSelect(pWalker, pSel);
99308       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
99309       if( pTab==0 ) return WRC_Abort;
99310       pTab->nRef = 1;
99311       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
99312       while( pSel->pPrior ){ pSel = pSel->pPrior; }
99313       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
99314       pTab->iPKey = -1;
99315       pTab->nRowEst = 1000000;
99316       pTab->tabFlags |= TF_Ephemeral;
99317 #endif
99318     }else{
99319       /* An ordinary table or view name in the FROM clause */
99320       assert( pFrom->pTab==0 );
99321       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
99322       if( pTab==0 ) return WRC_Abort;
99323       pTab->nRef++;
99324 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
99325       if( pTab->pSelect || IsVirtual(pTab) ){
99326         /* We reach here if the named table is a really a view */
99327         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
99328         assert( pFrom->pSelect==0 );
99329         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
99330         sqlite3WalkSelect(pWalker, pFrom->pSelect);
99331       }
99332 #endif
99333     }
99334
99335     /* Locate the index named by the INDEXED BY clause, if any. */
99336     if( sqlite3IndexedByLookup(pParse, pFrom) ){
99337       return WRC_Abort;
99338     }
99339   }
99340
99341   /* Process NATURAL keywords, and ON and USING clauses of joins.
99342   */
99343   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
99344     return WRC_Abort;
99345   }
99346
99347   /* For every "*" that occurs in the column list, insert the names of
99348   ** all columns in all tables.  And for every TABLE.* insert the names
99349   ** of all columns in TABLE.  The parser inserted a special expression
99350   ** with the TK_ALL operator for each "*" that it found in the column list.
99351   ** The following code just has to locate the TK_ALL expressions and expand
99352   ** each one to the list of all columns in all tables.
99353   **
99354   ** The first loop just checks to see if there are any "*" operators
99355   ** that need expanding.
99356   */
99357   for(k=0; k<pEList->nExpr; k++){
99358     Expr *pE = pEList->a[k].pExpr;
99359     if( pE->op==TK_ALL ) break;
99360     assert( pE->op!=TK_DOT || pE->pRight!=0 );
99361     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
99362     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
99363   }
99364   if( k<pEList->nExpr ){
99365     /*
99366     ** If we get here it means the result set contains one or more "*"
99367     ** operators that need to be expanded.  Loop through each expression
99368     ** in the result set and expand them one by one.
99369     */
99370     struct ExprList_item *a = pEList->a;
99371     ExprList *pNew = 0;
99372     int flags = pParse->db->flags;
99373     int longNames = (flags & SQLITE_FullColNames)!=0
99374                       && (flags & SQLITE_ShortColNames)==0;
99375
99376     for(k=0; k<pEList->nExpr; k++){
99377       Expr *pE = a[k].pExpr;
99378       assert( pE->op!=TK_DOT || pE->pRight!=0 );
99379       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
99380         /* This particular expression does not need to be expanded.
99381         */
99382         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
99383         if( pNew ){
99384           pNew->a[pNew->nExpr-1].zName = a[k].zName;
99385           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
99386           a[k].zName = 0;
99387           a[k].zSpan = 0;
99388         }
99389         a[k].pExpr = 0;
99390       }else{
99391         /* This expression is a "*" or a "TABLE.*" and needs to be
99392         ** expanded. */
99393         int tableSeen = 0;      /* Set to 1 when TABLE matches */
99394         char *zTName;            /* text of name of TABLE */
99395         if( pE->op==TK_DOT ){
99396           assert( pE->pLeft!=0 );
99397           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
99398           zTName = pE->pLeft->u.zToken;
99399         }else{
99400           zTName = 0;
99401         }
99402         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99403           Table *pTab = pFrom->pTab;
99404           char *zTabName = pFrom->zAlias;
99405           if( zTabName==0 ){
99406             zTabName = pTab->zName;
99407           }
99408           if( db->mallocFailed ) break;
99409           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
99410             continue;
99411           }
99412           tableSeen = 1;
99413           for(j=0; j<pTab->nCol; j++){
99414             Expr *pExpr, *pRight;
99415             char *zName = pTab->aCol[j].zName;
99416             char *zColname;  /* The computed column name */
99417             char *zToFree;   /* Malloced string that needs to be freed */
99418             Token sColname;  /* Computed column name as a token */
99419
99420             /* If a column is marked as 'hidden' (currently only possible
99421             ** for virtual tables), do not include it in the expanded
99422             ** result-set list.
99423             */
99424             if( IsHiddenColumn(&pTab->aCol[j]) ){
99425               assert(IsVirtual(pTab));
99426               continue;
99427             }
99428
99429             if( i>0 && zTName==0 ){
99430               if( (pFrom->jointype & JT_NATURAL)!=0
99431                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
99432               ){
99433                 /* In a NATURAL join, omit the join columns from the
99434                 ** table to the right of the join */
99435                 continue;
99436               }
99437               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
99438                 /* In a join with a USING clause, omit columns in the
99439                 ** using clause from the table on the right. */
99440                 continue;
99441               }
99442             }
99443             pRight = sqlite3Expr(db, TK_ID, zName);
99444             zColname = zName;
99445             zToFree = 0;
99446             if( longNames || pTabList->nSrc>1 ){
99447               Expr *pLeft;
99448               pLeft = sqlite3Expr(db, TK_ID, zTabName);
99449               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
99450               if( longNames ){
99451                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
99452                 zToFree = zColname;
99453               }
99454             }else{
99455               pExpr = pRight;
99456             }
99457             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
99458             sColname.z = zColname;
99459             sColname.n = sqlite3Strlen30(zColname);
99460             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
99461             sqlite3DbFree(db, zToFree);
99462           }
99463         }
99464         if( !tableSeen ){
99465           if( zTName ){
99466             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
99467           }else{
99468             sqlite3ErrorMsg(pParse, "no tables specified");
99469           }
99470         }
99471       }
99472     }
99473     sqlite3ExprListDelete(db, pEList);
99474     p->pEList = pNew;
99475   }
99476 #if SQLITE_MAX_COLUMN
99477   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
99478     sqlite3ErrorMsg(pParse, "too many columns in result set");
99479   }
99480 #endif
99481   return WRC_Continue;
99482 }
99483
99484 /*
99485 ** No-op routine for the parse-tree walker.
99486 **
99487 ** When this routine is the Walker.xExprCallback then expression trees
99488 ** are walked without any actions being taken at each node.  Presumably,
99489 ** when this routine is used for Walker.xExprCallback then
99490 ** Walker.xSelectCallback is set to do something useful for every
99491 ** subquery in the parser tree.
99492 */
99493 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
99494   UNUSED_PARAMETER2(NotUsed, NotUsed2);
99495   return WRC_Continue;
99496 }
99497
99498 /*
99499 ** This routine "expands" a SELECT statement and all of its subqueries.
99500 ** For additional information on what it means to "expand" a SELECT
99501 ** statement, see the comment on the selectExpand worker callback above.
99502 **
99503 ** Expanding a SELECT statement is the first step in processing a
99504 ** SELECT statement.  The SELECT statement must be expanded before
99505 ** name resolution is performed.
99506 **
99507 ** If anything goes wrong, an error message is written into pParse.
99508 ** The calling function can detect the problem by looking at pParse->nErr
99509 ** and/or pParse->db->mallocFailed.
99510 */
99511 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
99512   Walker w;
99513   w.xSelectCallback = selectExpander;
99514   w.xExprCallback = exprWalkNoop;
99515   w.pParse = pParse;
99516   sqlite3WalkSelect(&w, pSelect);
99517 }
99518
99519
99520 #ifndef SQLITE_OMIT_SUBQUERY
99521 /*
99522 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
99523 ** interface.
99524 **
99525 ** For each FROM-clause subquery, add Column.zType and Column.zColl
99526 ** information to the Table structure that represents the result set
99527 ** of that subquery.
99528 **
99529 ** The Table structure that represents the result set was constructed
99530 ** by selectExpander() but the type and collation information was omitted
99531 ** at that point because identifiers had not yet been resolved.  This
99532 ** routine is called after identifier resolution.
99533 */
99534 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
99535   Parse *pParse;
99536   int i;
99537   SrcList *pTabList;
99538   struct SrcList_item *pFrom;
99539
99540   assert( p->selFlags & SF_Resolved );
99541   if( (p->selFlags & SF_HasTypeInfo)==0 ){
99542     p->selFlags |= SF_HasTypeInfo;
99543     pParse = pWalker->pParse;
99544     pTabList = p->pSrc;
99545     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99546       Table *pTab = pFrom->pTab;
99547       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
99548         /* A sub-query in the FROM clause of a SELECT */
99549         Select *pSel = pFrom->pSelect;
99550         assert( pSel );
99551         while( pSel->pPrior ) pSel = pSel->pPrior;
99552         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
99553       }
99554     }
99555   }
99556   return WRC_Continue;
99557 }
99558 #endif
99559
99560
99561 /*
99562 ** This routine adds datatype and collating sequence information to
99563 ** the Table structures of all FROM-clause subqueries in a
99564 ** SELECT statement.
99565 **
99566 ** Use this routine after name resolution.
99567 */
99568 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
99569 #ifndef SQLITE_OMIT_SUBQUERY
99570   Walker w;
99571   w.xSelectCallback = selectAddSubqueryTypeInfo;
99572   w.xExprCallback = exprWalkNoop;
99573   w.pParse = pParse;
99574   sqlite3WalkSelect(&w, pSelect);
99575 #endif
99576 }
99577
99578
99579 /*
99580 ** This routine sets up a SELECT statement for processing.  The
99581 ** following is accomplished:
99582 **
99583 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
99584 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
99585 **     *  ON and USING clauses are shifted into WHERE statements
99586 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
99587 **     *  Identifiers in expression are matched to tables.
99588 **
99589 ** This routine acts recursively on all subqueries within the SELECT.
99590 */
99591 SQLITE_PRIVATE void sqlite3SelectPrep(
99592   Parse *pParse,         /* The parser context */
99593   Select *p,             /* The SELECT statement being coded. */
99594   NameContext *pOuterNC  /* Name context for container */
99595 ){
99596   sqlite3 *db;
99597   if( NEVER(p==0) ) return;
99598   db = pParse->db;
99599   if( p->selFlags & SF_HasTypeInfo ) return;
99600   sqlite3SelectExpand(pParse, p);
99601   if( pParse->nErr || db->mallocFailed ) return;
99602   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
99603   if( pParse->nErr || db->mallocFailed ) return;
99604   sqlite3SelectAddTypeInfo(pParse, p);
99605 }
99606
99607 /*
99608 ** Reset the aggregate accumulator.
99609 **
99610 ** The aggregate accumulator is a set of memory cells that hold
99611 ** intermediate results while calculating an aggregate.  This
99612 ** routine generates code that stores NULLs in all of those memory
99613 ** cells.
99614 */
99615 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
99616   Vdbe *v = pParse->pVdbe;
99617   int i;
99618   struct AggInfo_func *pFunc;
99619   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
99620     return;
99621   }
99622   for(i=0; i<pAggInfo->nColumn; i++){
99623     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
99624   }
99625   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
99626     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
99627     if( pFunc->iDistinct>=0 ){
99628       Expr *pE = pFunc->pExpr;
99629       assert( !ExprHasProperty(pE, EP_xIsSelect) );
99630       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
99631         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
99632            "argument");
99633         pFunc->iDistinct = -1;
99634       }else{
99635         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
99636         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
99637                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99638       }
99639     }
99640   }
99641 }
99642
99643 /*
99644 ** Invoke the OP_AggFinalize opcode for every aggregate function
99645 ** in the AggInfo structure.
99646 */
99647 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
99648   Vdbe *v = pParse->pVdbe;
99649   int i;
99650   struct AggInfo_func *pF;
99651   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99652     ExprList *pList = pF->pExpr->x.pList;
99653     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99654     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
99655                       (void*)pF->pFunc, P4_FUNCDEF);
99656   }
99657 }
99658
99659 /*
99660 ** Update the accumulator memory cells for an aggregate based on
99661 ** the current cursor position.
99662 */
99663 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
99664   Vdbe *v = pParse->pVdbe;
99665   int i;
99666   int regHit = 0;
99667   int addrHitTest = 0;
99668   struct AggInfo_func *pF;
99669   struct AggInfo_col *pC;
99670
99671   pAggInfo->directMode = 1;
99672   sqlite3ExprCacheClear(pParse);
99673   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99674     int nArg;
99675     int addrNext = 0;
99676     int regAgg;
99677     ExprList *pList = pF->pExpr->x.pList;
99678     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99679     if( pList ){
99680       nArg = pList->nExpr;
99681       regAgg = sqlite3GetTempRange(pParse, nArg);
99682       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
99683     }else{
99684       nArg = 0;
99685       regAgg = 0;
99686     }
99687     if( pF->iDistinct>=0 ){
99688       addrNext = sqlite3VdbeMakeLabel(v);
99689       assert( nArg==1 );
99690       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
99691     }
99692     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
99693       CollSeq *pColl = 0;
99694       struct ExprList_item *pItem;
99695       int j;
99696       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
99697       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
99698         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
99699       }
99700       if( !pColl ){
99701         pColl = pParse->db->pDfltColl;
99702       }
99703       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
99704       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
99705     }
99706     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
99707                       (void*)pF->pFunc, P4_FUNCDEF);
99708     sqlite3VdbeChangeP5(v, (u8)nArg);
99709     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
99710     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
99711     if( addrNext ){
99712       sqlite3VdbeResolveLabel(v, addrNext);
99713       sqlite3ExprCacheClear(pParse);
99714     }
99715   }
99716
99717   /* Before populating the accumulator registers, clear the column cache.
99718   ** Otherwise, if any of the required column values are already present
99719   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
99720   ** to pC->iMem. But by the time the value is used, the original register
99721   ** may have been used, invalidating the underlying buffer holding the
99722   ** text or blob value. See ticket [883034dcb5].
99723   **
99724   ** Another solution would be to change the OP_SCopy used to copy cached
99725   ** values to an OP_Copy.
99726   */
99727   if( regHit ){
99728     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
99729   }
99730   sqlite3ExprCacheClear(pParse);
99731   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
99732     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
99733   }
99734   pAggInfo->directMode = 0;
99735   sqlite3ExprCacheClear(pParse);
99736   if( addrHitTest ){
99737     sqlite3VdbeJumpHere(v, addrHitTest);
99738   }
99739 }
99740
99741 /*
99742 ** Add a single OP_Explain instruction to the VDBE to explain a simple
99743 ** count(*) query ("SELECT count(*) FROM pTab").
99744 */
99745 #ifndef SQLITE_OMIT_EXPLAIN
99746 static void explainSimpleCount(
99747   Parse *pParse,                  /* Parse context */
99748   Table *pTab,                    /* Table being queried */
99749   Index *pIdx                     /* Index used to optimize scan, or NULL */
99750 ){
99751   if( pParse->explain==2 ){
99752     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
99753         pTab->zName,
99754         pIdx ? "USING COVERING INDEX " : "",
99755         pIdx ? pIdx->zName : "",
99756         pTab->nRowEst
99757     );
99758     sqlite3VdbeAddOp4(
99759         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
99760     );
99761   }
99762 }
99763 #else
99764 # define explainSimpleCount(a,b,c)
99765 #endif
99766
99767 /*
99768 ** Generate code for the SELECT statement given in the p argument.
99769 **
99770 ** The results are distributed in various ways depending on the
99771 ** contents of the SelectDest structure pointed to by argument pDest
99772 ** as follows:
99773 **
99774 **     pDest->eDest    Result
99775 **     ------------    -------------------------------------------
99776 **     SRT_Output      Generate a row of output (using the OP_ResultRow
99777 **                     opcode) for each row in the result set.
99778 **
99779 **     SRT_Mem         Only valid if the result is a single column.
99780 **                     Store the first column of the first result row
99781 **                     in register pDest->iSDParm then abandon the rest
99782 **                     of the query.  This destination implies "LIMIT 1".
99783 **
99784 **     SRT_Set         The result must be a single column.  Store each
99785 **                     row of result as the key in table pDest->iSDParm.
99786 **                     Apply the affinity pDest->affSdst before storing
99787 **                     results.  Used to implement "IN (SELECT ...)".
99788 **
99789 **     SRT_Union       Store results as a key in a temporary table
99790 **                     identified by pDest->iSDParm.
99791 **
99792 **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
99793 **
99794 **     SRT_Table       Store results in temporary table pDest->iSDParm.
99795 **                     This is like SRT_EphemTab except that the table
99796 **                     is assumed to already be open.
99797 **
99798 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
99799 **                     the result there. The cursor is left open after
99800 **                     returning.  This is like SRT_Table except that
99801 **                     this destination uses OP_OpenEphemeral to create
99802 **                     the table first.
99803 **
99804 **     SRT_Coroutine   Generate a co-routine that returns a new row of
99805 **                     results each time it is invoked.  The entry point
99806 **                     of the co-routine is stored in register pDest->iSDParm.
99807 **
99808 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
99809 **                     set is not empty.
99810 **
99811 **     SRT_Discard     Throw the results away.  This is used by SELECT
99812 **                     statements within triggers whose only purpose is
99813 **                     the side-effects of functions.
99814 **
99815 ** This routine returns the number of errors.  If any errors are
99816 ** encountered, then an appropriate error message is left in
99817 ** pParse->zErrMsg.
99818 **
99819 ** This routine does NOT free the Select structure passed in.  The
99820 ** calling function needs to do that.
99821 */
99822 SQLITE_PRIVATE int sqlite3Select(
99823   Parse *pParse,         /* The parser context */
99824   Select *p,             /* The SELECT statement being coded. */
99825   SelectDest *pDest      /* What to do with the query results */
99826 ){
99827   int i, j;              /* Loop counters */
99828   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
99829   Vdbe *v;               /* The virtual machine under construction */
99830   int isAgg;             /* True for select lists like "count(*)" */
99831   ExprList *pEList;      /* List of columns to extract. */
99832   SrcList *pTabList;     /* List of tables to select from */
99833   Expr *pWhere;          /* The WHERE clause.  May be NULL */
99834   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
99835   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
99836   Expr *pHaving;         /* The HAVING clause.  May be NULL */
99837   int rc = 1;            /* Value to return from this function */
99838   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
99839   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
99840   AggInfo sAggInfo;      /* Information used by aggregate queries */
99841   int iEnd;              /* Address of the end of the query */
99842   sqlite3 *db;           /* The database connection */
99843
99844 #ifndef SQLITE_OMIT_EXPLAIN
99845   int iRestoreSelectId = pParse->iSelectId;
99846   pParse->iSelectId = pParse->iNextSelectId++;
99847 #endif
99848
99849   db = pParse->db;
99850   if( p==0 || db->mallocFailed || pParse->nErr ){
99851     return 1;
99852   }
99853   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
99854   memset(&sAggInfo, 0, sizeof(sAggInfo));
99855
99856   if( IgnorableOrderby(pDest) ){
99857     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
99858            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
99859     /* If ORDER BY makes no difference in the output then neither does
99860     ** DISTINCT so it can be removed too. */
99861     sqlite3ExprListDelete(db, p->pOrderBy);
99862     p->pOrderBy = 0;
99863     p->selFlags &= ~SF_Distinct;
99864   }
99865   sqlite3SelectPrep(pParse, p, 0);
99866   pOrderBy = p->pOrderBy;
99867   pTabList = p->pSrc;
99868   pEList = p->pEList;
99869   if( pParse->nErr || db->mallocFailed ){
99870     goto select_end;
99871   }
99872   isAgg = (p->selFlags & SF_Aggregate)!=0;
99873   assert( pEList!=0 );
99874
99875   /* Begin generating code.
99876   */
99877   v = sqlite3GetVdbe(pParse);
99878   if( v==0 ) goto select_end;
99879
99880   /* If writing to memory or generating a set
99881   ** only a single column may be output.
99882   */
99883 #ifndef SQLITE_OMIT_SUBQUERY
99884   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
99885     goto select_end;
99886   }
99887 #endif
99888
99889   /* Generate code for all sub-queries in the FROM clause
99890   */
99891 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
99892   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
99893     struct SrcList_item *pItem = &pTabList->a[i];
99894     SelectDest dest;
99895     Select *pSub = pItem->pSelect;
99896     int isAggSub;
99897
99898     if( pSub==0 ) continue;
99899
99900     /* Sometimes the code for a subquery will be generated more than
99901     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
99902     ** for example.  In that case, do not regenerate the code to manifest
99903     ** a view or the co-routine to implement a view.  The first instance
99904     ** is sufficient, though the subroutine to manifest the view does need
99905     ** to be invoked again. */
99906     if( pItem->addrFillSub ){
99907       if( pItem->viaCoroutine==0 ){
99908         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
99909       }
99910       continue;
99911     }
99912
99913     /* Increment Parse.nHeight by the height of the largest expression
99914     ** tree refered to by this, the parent select. The child select
99915     ** may contain expression trees of at most
99916     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
99917     ** more conservative than necessary, but much easier than enforcing
99918     ** an exact limit.
99919     */
99920     pParse->nHeight += sqlite3SelectExprHeight(p);
99921
99922     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
99923     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
99924       /* This subquery can be absorbed into its parent. */
99925       if( isAggSub ){
99926         isAgg = 1;
99927         p->selFlags |= SF_Aggregate;
99928       }
99929       i = -1;
99930     }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
99931       && OptimizationEnabled(db, SQLITE_SubqCoroutine)
99932     ){
99933       /* Implement a co-routine that will return a single row of the result
99934       ** set on each invocation.
99935       */
99936       int addrTop;
99937       int addrEof;
99938       pItem->regReturn = ++pParse->nMem;
99939       addrEof = ++pParse->nMem;
99940       /* Before coding the OP_Goto to jump to the start of the main routine,
99941       ** ensure that the jump to the verify-schema routine has already
99942       ** been coded. Otherwise, the verify-schema would likely be coded as
99943       ** part of the co-routine. If the main routine then accessed the
99944       ** database before invoking the co-routine for the first time (for
99945       ** example to initialize a LIMIT register from a sub-select), it would
99946       ** be doing so without having verified the schema version and obtained
99947       ** the required db locks. See ticket d6b36be38.  */
99948       sqlite3CodeVerifySchema(pParse, -1);
99949       sqlite3VdbeAddOp0(v, OP_Goto);
99950       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
99951       sqlite3VdbeChangeP5(v, 1);
99952       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
99953       pItem->addrFillSub = addrTop;
99954       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
99955       sqlite3VdbeChangeP5(v, 1);
99956       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
99957       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
99958       sqlite3Select(pParse, pSub, &dest);
99959       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
99960       pItem->viaCoroutine = 1;
99961       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
99962       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
99963       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
99964       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
99965       VdbeComment((v, "end %s", pItem->pTab->zName));
99966       sqlite3VdbeJumpHere(v, addrTop-1);
99967       sqlite3ClearTempRegCache(pParse);
99968     }else{
99969       /* Generate a subroutine that will fill an ephemeral table with
99970       ** the content of this subquery.  pItem->addrFillSub will point
99971       ** to the address of the generated subroutine.  pItem->regReturn
99972       ** is a register allocated to hold the subroutine return address
99973       */
99974       int topAddr;
99975       int onceAddr = 0;
99976       int retAddr;
99977       assert( pItem->addrFillSub==0 );
99978       pItem->regReturn = ++pParse->nMem;
99979       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
99980       pItem->addrFillSub = topAddr+1;
99981       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
99982       if( pItem->isCorrelated==0 ){
99983         /* If the subquery is no correlated and if we are not inside of
99984         ** a trigger, then we only need to compute the value of the subquery
99985         ** once. */
99986         onceAddr = sqlite3CodeOnce(pParse);
99987       }
99988       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
99989       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
99990       sqlite3Select(pParse, pSub, &dest);
99991       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
99992       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
99993       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
99994       VdbeComment((v, "end %s", pItem->pTab->zName));
99995       sqlite3VdbeChangeP1(v, topAddr, retAddr);
99996       sqlite3ClearTempRegCache(pParse);
99997     }
99998     if( /*pParse->nErr ||*/ db->mallocFailed ){
99999       goto select_end;
100000     }
100001     pParse->nHeight -= sqlite3SelectExprHeight(p);
100002     pTabList = p->pSrc;
100003     if( !IgnorableOrderby(pDest) ){
100004       pOrderBy = p->pOrderBy;
100005     }
100006   }
100007   pEList = p->pEList;
100008 #endif
100009   pWhere = p->pWhere;
100010   pGroupBy = p->pGroupBy;
100011   pHaving = p->pHaving;
100012   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
100013
100014 #ifndef SQLITE_OMIT_COMPOUND_SELECT
100015   /* If there is are a sequence of queries, do the earlier ones first.
100016   */
100017   if( p->pPrior ){
100018     if( p->pRightmost==0 ){
100019       Select *pLoop, *pRight = 0;
100020       int cnt = 0;
100021       int mxSelect;
100022       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
100023         pLoop->pRightmost = p;
100024         pLoop->pNext = pRight;
100025         pRight = pLoop;
100026       }
100027       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
100028       if( mxSelect && cnt>mxSelect ){
100029         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
100030         goto select_end;
100031       }
100032     }
100033     rc = multiSelect(pParse, p, pDest);
100034     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100035     return rc;
100036   }
100037 #endif
100038
100039   /* If there is both a GROUP BY and an ORDER BY clause and they are
100040   ** identical, then disable the ORDER BY clause since the GROUP BY
100041   ** will cause elements to come out in the correct order.  This is
100042   ** an optimization - the correct answer should result regardless.
100043   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
100044   ** to disable this optimization for testing purposes.
100045   */
100046   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
100047          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
100048     pOrderBy = 0;
100049   }
100050
100051   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
100052   ** if the select-list is the same as the ORDER BY list, then this query
100053   ** can be rewritten as a GROUP BY. In other words, this:
100054   **
100055   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
100056   **
100057   ** is transformed to:
100058   **
100059   **     SELECT xyz FROM ... GROUP BY xyz
100060   **
100061   ** The second form is preferred as a single index (or temp-table) may be
100062   ** used for both the ORDER BY and DISTINCT processing. As originally
100063   ** written the query must use a temp-table for at least one of the ORDER
100064   ** BY and DISTINCT, and an index or separate temp-table for the other.
100065   */
100066   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
100067    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
100068   ){
100069     p->selFlags &= ~SF_Distinct;
100070     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
100071     pGroupBy = p->pGroupBy;
100072     pOrderBy = 0;
100073     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
100074     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
100075     ** original setting of the SF_Distinct flag, not the current setting */
100076     assert( sDistinct.isTnct );
100077   }
100078
100079   /* If there is an ORDER BY clause, then this sorting
100080   ** index might end up being unused if the data can be
100081   ** extracted in pre-sorted order.  If that is the case, then the
100082   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
100083   ** we figure out that the sorting index is not needed.  The addrSortIndex
100084   ** variable is used to facilitate that change.
100085   */
100086   if( pOrderBy ){
100087     KeyInfo *pKeyInfo;
100088     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
100089     pOrderBy->iECursor = pParse->nTab++;
100090     p->addrOpenEphm[2] = addrSortIndex =
100091       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100092                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
100093                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100094   }else{
100095     addrSortIndex = -1;
100096   }
100097
100098   /* If the output is destined for a temporary table, open that table.
100099   */
100100   if( pDest->eDest==SRT_EphemTab ){
100101     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
100102   }
100103
100104   /* Set the limiter.
100105   */
100106   iEnd = sqlite3VdbeMakeLabel(v);
100107   p->nSelectRow = (double)LARGEST_INT64;
100108   computeLimitRegisters(pParse, p, iEnd);
100109   if( p->iLimit==0 && addrSortIndex>=0 ){
100110     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100111     p->selFlags |= SF_UseSorter;
100112   }
100113
100114   /* Open a virtual index to use for the distinct set.
100115   */
100116   if( p->selFlags & SF_Distinct ){
100117     sDistinct.tabTnct = pParse->nTab++;
100118     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100119                                 sDistinct.tabTnct, 0, 0,
100120                                 (char*)keyInfoFromExprList(pParse, p->pEList),
100121                                 P4_KEYINFO_HANDOFF);
100122     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
100123     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
100124   }else{
100125     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
100126   }
100127
100128   if( !isAgg && pGroupBy==0 ){
100129     /* No aggregate functions and no GROUP BY clause */
100130     ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100131
100132     /* Begin the database scan. */
100133     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100134     if( pWInfo==0 ) goto select_end;
100135     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
100136     if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
100137     if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
100138
100139     /* If sorting index that was created by a prior OP_OpenEphemeral
100140     ** instruction ended up not being needed, then change the OP_OpenEphemeral
100141     ** into an OP_Noop.
100142     */
100143     if( addrSortIndex>=0 && pOrderBy==0 ){
100144       sqlite3VdbeChangeToNoop(v, addrSortIndex);
100145       p->addrOpenEphm[2] = -1;
100146     }
100147
100148     /* Use the standard inner loop. */
100149     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100150                     pWInfo->iContinue, pWInfo->iBreak);
100151
100152     /* End the database scan loop.
100153     */
100154     sqlite3WhereEnd(pWInfo);
100155   }else{
100156     /* This case when there exist aggregate functions or a GROUP BY clause
100157     ** or both */
100158     NameContext sNC;    /* Name context for processing aggregate information */
100159     int iAMem;          /* First Mem address for storing current GROUP BY */
100160     int iBMem;          /* First Mem address for previous GROUP BY */
100161     int iUseFlag;       /* Mem address holding flag indicating that at least
100162                         ** one row of the input to the aggregator has been
100163                         ** processed */
100164     int iAbortFlag;     /* Mem address which causes query abort if positive */
100165     int groupBySort;    /* Rows come from source in GROUP BY order */
100166     int addrEnd;        /* End of processing for this SELECT */
100167     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
100168     int sortOut = 0;    /* Output register from the sorter */
100169
100170     /* Remove any and all aliases between the result set and the
100171     ** GROUP BY clause.
100172     */
100173     if( pGroupBy ){
100174       int k;                        /* Loop counter */
100175       struct ExprList_item *pItem;  /* For looping over expression in a list */
100176
100177       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
100178         pItem->iAlias = 0;
100179       }
100180       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100181         pItem->iAlias = 0;
100182       }
100183       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
100184     }else{
100185       p->nSelectRow = (double)1;
100186     }
100187
100188
100189     /* Create a label to jump to when we want to abort the query */
100190     addrEnd = sqlite3VdbeMakeLabel(v);
100191
100192     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
100193     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
100194     ** SELECT statement.
100195     */
100196     memset(&sNC, 0, sizeof(sNC));
100197     sNC.pParse = pParse;
100198     sNC.pSrcList = pTabList;
100199     sNC.pAggInfo = &sAggInfo;
100200     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
100201     sAggInfo.pGroupBy = pGroupBy;
100202     sqlite3ExprAnalyzeAggList(&sNC, pEList);
100203     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
100204     if( pHaving ){
100205       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
100206     }
100207     sAggInfo.nAccumulator = sAggInfo.nColumn;
100208     for(i=0; i<sAggInfo.nFunc; i++){
100209       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
100210       sNC.ncFlags |= NC_InAggFunc;
100211       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
100212       sNC.ncFlags &= ~NC_InAggFunc;
100213     }
100214     if( db->mallocFailed ) goto select_end;
100215
100216     /* Processing for aggregates with GROUP BY is very different and
100217     ** much more complex than aggregates without a GROUP BY.
100218     */
100219     if( pGroupBy ){
100220       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
100221       int j1;             /* A-vs-B comparision jump */
100222       int addrOutputRow;  /* Start of subroutine that outputs a result row */
100223       int regOutputRow;   /* Return address register for output subroutine */
100224       int addrSetAbort;   /* Set the abort flag and return */
100225       int addrTopOfLoop;  /* Top of the input loop */
100226       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
100227       int addrReset;      /* Subroutine for resetting the accumulator */
100228       int regReset;       /* Return address register for reset subroutine */
100229
100230       /* If there is a GROUP BY clause we might need a sorting index to
100231       ** implement it.  Allocate that sorting index now.  If it turns out
100232       ** that we do not need it after all, the OP_SorterOpen instruction
100233       ** will be converted into a Noop.
100234       */
100235       sAggInfo.sortingIdx = pParse->nTab++;
100236       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
100237       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
100238           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
100239           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100240
100241       /* Initialize memory locations used by GROUP BY aggregate processing
100242       */
100243       iUseFlag = ++pParse->nMem;
100244       iAbortFlag = ++pParse->nMem;
100245       regOutputRow = ++pParse->nMem;
100246       addrOutputRow = sqlite3VdbeMakeLabel(v);
100247       regReset = ++pParse->nMem;
100248       addrReset = sqlite3VdbeMakeLabel(v);
100249       iAMem = pParse->nMem + 1;
100250       pParse->nMem += pGroupBy->nExpr;
100251       iBMem = pParse->nMem + 1;
100252       pParse->nMem += pGroupBy->nExpr;
100253       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
100254       VdbeComment((v, "clear abort flag"));
100255       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
100256       VdbeComment((v, "indicate accumulator empty"));
100257       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
100258
100259       /* Begin a loop that will extract all source rows in GROUP BY order.
100260       ** This might involve two separate loops with an OP_Sort in between, or
100261       ** it might be a single loop that uses an index to extract information
100262       ** in the right order to begin with.
100263       */
100264       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100265       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
100266       if( pWInfo==0 ) goto select_end;
100267       if( pWInfo->nOBSat==pGroupBy->nExpr ){
100268         /* The optimizer is able to deliver rows in group by order so
100269         ** we do not have to sort.  The OP_OpenEphemeral table will be
100270         ** cancelled later because we still need to use the pKeyInfo
100271         */
100272         groupBySort = 0;
100273       }else{
100274         /* Rows are coming out in undetermined order.  We have to push
100275         ** each row into a sorting index, terminate the first loop,
100276         ** then loop over the sorting index in order to get the output
100277         ** in sorted order
100278         */
100279         int regBase;
100280         int regRecord;
100281         int nCol;
100282         int nGroupBy;
100283
100284         explainTempTable(pParse,
100285             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
100286                     "DISTINCT" : "GROUP BY");
100287
100288         groupBySort = 1;
100289         nGroupBy = pGroupBy->nExpr;
100290         nCol = nGroupBy + 1;
100291         j = nGroupBy+1;
100292         for(i=0; i<sAggInfo.nColumn; i++){
100293           if( sAggInfo.aCol[i].iSorterColumn>=j ){
100294             nCol++;
100295             j++;
100296           }
100297         }
100298         regBase = sqlite3GetTempRange(pParse, nCol);
100299         sqlite3ExprCacheClear(pParse);
100300         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
100301         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
100302         j = nGroupBy+1;
100303         for(i=0; i<sAggInfo.nColumn; i++){
100304           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
100305           if( pCol->iSorterColumn>=j ){
100306             int r1 = j + regBase;
100307             int r2;
100308
100309             r2 = sqlite3ExprCodeGetColumn(pParse,
100310                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
100311             if( r1!=r2 ){
100312               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
100313             }
100314             j++;
100315           }
100316         }
100317         regRecord = sqlite3GetTempReg(pParse);
100318         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
100319         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
100320         sqlite3ReleaseTempReg(pParse, regRecord);
100321         sqlite3ReleaseTempRange(pParse, regBase, nCol);
100322         sqlite3WhereEnd(pWInfo);
100323         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
100324         sortOut = sqlite3GetTempReg(pParse);
100325         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
100326         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
100327         VdbeComment((v, "GROUP BY sort"));
100328         sAggInfo.useSortingIdx = 1;
100329         sqlite3ExprCacheClear(pParse);
100330       }
100331
100332       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
100333       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
100334       ** Then compare the current GROUP BY terms against the GROUP BY terms
100335       ** from the previous row currently stored in a0, a1, a2...
100336       */
100337       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
100338       sqlite3ExprCacheClear(pParse);
100339       if( groupBySort ){
100340         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
100341       }
100342       for(j=0; j<pGroupBy->nExpr; j++){
100343         if( groupBySort ){
100344           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
100345           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
100346         }else{
100347           sAggInfo.directMode = 1;
100348           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
100349         }
100350       }
100351       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
100352                           (char*)pKeyInfo, P4_KEYINFO);
100353       j1 = sqlite3VdbeCurrentAddr(v);
100354       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
100355
100356       /* Generate code that runs whenever the GROUP BY changes.
100357       ** Changes in the GROUP BY are detected by the previous code
100358       ** block.  If there were no changes, this block is skipped.
100359       **
100360       ** This code copies current group by terms in b0,b1,b2,...
100361       ** over to a0,a1,a2.  It then calls the output subroutine
100362       ** and resets the aggregate accumulator registers in preparation
100363       ** for the next GROUP BY batch.
100364       */
100365       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
100366       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100367       VdbeComment((v, "output one row"));
100368       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
100369       VdbeComment((v, "check abort flag"));
100370       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100371       VdbeComment((v, "reset accumulator"));
100372
100373       /* Update the aggregate accumulators based on the content of
100374       ** the current row
100375       */
100376       sqlite3VdbeJumpHere(v, j1);
100377       updateAccumulator(pParse, &sAggInfo);
100378       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
100379       VdbeComment((v, "indicate data in accumulator"));
100380
100381       /* End of the loop
100382       */
100383       if( groupBySort ){
100384         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
100385       }else{
100386         sqlite3WhereEnd(pWInfo);
100387         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
100388       }
100389
100390       /* Output the final row of result
100391       */
100392       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100393       VdbeComment((v, "output final row"));
100394
100395       /* Jump over the subroutines
100396       */
100397       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
100398
100399       /* Generate a subroutine that outputs a single row of the result
100400       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
100401       ** is less than or equal to zero, the subroutine is a no-op.  If
100402       ** the processing calls for the query to abort, this subroutine
100403       ** increments the iAbortFlag memory location before returning in
100404       ** order to signal the caller to abort.
100405       */
100406       addrSetAbort = sqlite3VdbeCurrentAddr(v);
100407       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
100408       VdbeComment((v, "set abort flag"));
100409       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100410       sqlite3VdbeResolveLabel(v, addrOutputRow);
100411       addrOutputRow = sqlite3VdbeCurrentAddr(v);
100412       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
100413       VdbeComment((v, "Groupby result generator entry point"));
100414       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100415       finalizeAggFunctions(pParse, &sAggInfo);
100416       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
100417       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
100418                       &sDistinct, pDest,
100419                       addrOutputRow+1, addrSetAbort);
100420       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100421       VdbeComment((v, "end groupby result generator"));
100422
100423       /* Generate a subroutine that will reset the group-by accumulator
100424       */
100425       sqlite3VdbeResolveLabel(v, addrReset);
100426       resetAccumulator(pParse, &sAggInfo);
100427       sqlite3VdbeAddOp1(v, OP_Return, regReset);
100428
100429     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
100430     else {
100431       ExprList *pDel = 0;
100432 #ifndef SQLITE_OMIT_BTREECOUNT
100433       Table *pTab;
100434       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
100435         /* If isSimpleCount() returns a pointer to a Table structure, then
100436         ** the SQL statement is of the form:
100437         **
100438         **   SELECT count(*) FROM <tbl>
100439         **
100440         ** where the Table structure returned represents table <tbl>.
100441         **
100442         ** This statement is so common that it is optimized specially. The
100443         ** OP_Count instruction is executed either on the intkey table that
100444         ** contains the data for table <tbl> or on one of its indexes. It
100445         ** is better to execute the op on an index, as indexes are almost
100446         ** always spread across less pages than their corresponding tables.
100447         */
100448         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100449         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
100450         Index *pIdx;                         /* Iterator variable */
100451         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
100452         Index *pBest = 0;                    /* Best index found so far */
100453         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
100454
100455         sqlite3CodeVerifySchema(pParse, iDb);
100456         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
100457
100458         /* Search for the index that has the least amount of columns. If
100459         ** there is such an index, and it has less columns than the table
100460         ** does, then we can assume that it consumes less space on disk and
100461         ** will therefore be cheaper to scan to determine the query result.
100462         ** In this case set iRoot to the root page number of the index b-tree
100463         ** and pKeyInfo to the KeyInfo structure required to navigate the
100464         ** index.
100465         **
100466         ** (2011-04-15) Do not do a full scan of an unordered index.
100467         **
100468         ** In practice the KeyInfo structure will not be used. It is only
100469         ** passed to keep OP_OpenRead happy.
100470         */
100471         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100472           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
100473             pBest = pIdx;
100474           }
100475         }
100476         if( pBest && pBest->nColumn<pTab->nCol ){
100477           iRoot = pBest->tnum;
100478           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
100479         }
100480
100481         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
100482         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
100483         if( pKeyInfo ){
100484           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
100485         }
100486         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
100487         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
100488         explainSimpleCount(pParse, pTab, pBest);
100489       }else
100490 #endif /* SQLITE_OMIT_BTREECOUNT */
100491       {
100492         /* Check if the query is of one of the following forms:
100493         **
100494         **   SELECT min(x) FROM ...
100495         **   SELECT max(x) FROM ...
100496         **
100497         ** If it is, then ask the code in where.c to attempt to sort results
100498         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
100499         ** If where.c is able to produce results sorted in this order, then
100500         ** add vdbe code to break out of the processing loop after the
100501         ** first iteration (since the first iteration of the loop is
100502         ** guaranteed to operate on the row with the minimum or maximum
100503         ** value of x, the only row required).
100504         **
100505         ** A special flag must be passed to sqlite3WhereBegin() to slightly
100506         ** modify behaviour as follows:
100507         **
100508         **   + If the query is a "SELECT min(x)", then the loop coded by
100509         **     where.c should not iterate over any values with a NULL value
100510         **     for x.
100511         **
100512         **   + The optimizer code in where.c (the thing that decides which
100513         **     index or indices to use) should place a different priority on
100514         **     satisfying the 'ORDER BY' clause than it does in other cases.
100515         **     Refer to code and comments in where.c for details.
100516         */
100517         ExprList *pMinMax = 0;
100518         u8 flag = minMaxQuery(p);
100519         if( flag ){
100520           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
100521           assert( p->pEList->a[0].pExpr->x.pList->nExpr==1 );
100522           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
100523           pDel = pMinMax;
100524           if( pMinMax && !db->mallocFailed ){
100525             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
100526             pMinMax->a[0].pExpr->op = TK_COLUMN;
100527           }
100528         }
100529
100530         /* This case runs if the aggregate has no GROUP BY clause.  The
100531         ** processing is much simpler since there is only a single row
100532         ** of output.
100533         */
100534         resetAccumulator(pParse, &sAggInfo);
100535         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
100536         if( pWInfo==0 ){
100537           sqlite3ExprListDelete(db, pDel);
100538           goto select_end;
100539         }
100540         updateAccumulator(pParse, &sAggInfo);
100541         assert( pMinMax==0 || pMinMax->nExpr==1 );
100542         if( pWInfo->nOBSat>0 ){
100543           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
100544           VdbeComment((v, "%s() by index",
100545                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
100546         }
100547         sqlite3WhereEnd(pWInfo);
100548         finalizeAggFunctions(pParse, &sAggInfo);
100549       }
100550
100551       pOrderBy = 0;
100552       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
100553       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
100554                       pDest, addrEnd, addrEnd);
100555       sqlite3ExprListDelete(db, pDel);
100556     }
100557     sqlite3VdbeResolveLabel(v, addrEnd);
100558
100559   } /* endif aggregate query */
100560
100561   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
100562     explainTempTable(pParse, "DISTINCT");
100563   }
100564
100565   /* If there is an ORDER BY clause, then we need to sort the results
100566   ** and send them to the callback one by one.
100567   */
100568   if( pOrderBy ){
100569     explainTempTable(pParse, "ORDER BY");
100570     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
100571   }
100572
100573   /* Jump here to skip this query
100574   */
100575   sqlite3VdbeResolveLabel(v, iEnd);
100576
100577   /* The SELECT was successfully coded.   Set the return code to 0
100578   ** to indicate no errors.
100579   */
100580   rc = 0;
100581
100582   /* Control jumps to here if an error is encountered above, or upon
100583   ** successful coding of the SELECT.
100584   */
100585 select_end:
100586   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100587
100588   /* Identify column names if results of the SELECT are to be output.
100589   */
100590   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
100591     generateColumnNames(pParse, pTabList, pEList);
100592   }
100593
100594   sqlite3DbFree(db, sAggInfo.aCol);
100595   sqlite3DbFree(db, sAggInfo.aFunc);
100596   return rc;
100597 }
100598
100599 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
100600 /*
100601 ** Generate a human-readable description of a the Select object.
100602 */
100603 static void explainOneSelect(Vdbe *pVdbe, Select *p){
100604   sqlite3ExplainPrintf(pVdbe, "SELECT ");
100605   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
100606     if( p->selFlags & SF_Distinct ){
100607       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
100608     }
100609     if( p->selFlags & SF_Aggregate ){
100610       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
100611     }
100612     sqlite3ExplainNL(pVdbe);
100613     sqlite3ExplainPrintf(pVdbe, "   ");
100614   }
100615   sqlite3ExplainExprList(pVdbe, p->pEList);
100616   sqlite3ExplainNL(pVdbe);
100617   if( p->pSrc && p->pSrc->nSrc ){
100618     int i;
100619     sqlite3ExplainPrintf(pVdbe, "FROM ");
100620     sqlite3ExplainPush(pVdbe);
100621     for(i=0; i<p->pSrc->nSrc; i++){
100622       struct SrcList_item *pItem = &p->pSrc->a[i];
100623       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
100624       if( pItem->pSelect ){
100625         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
100626         if( pItem->pTab ){
100627           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
100628         }
100629       }else if( pItem->zName ){
100630         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
100631       }
100632       if( pItem->zAlias ){
100633         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
100634       }
100635       if( pItem->jointype & JT_LEFT ){
100636         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
100637       }
100638       sqlite3ExplainNL(pVdbe);
100639     }
100640     sqlite3ExplainPop(pVdbe);
100641   }
100642   if( p->pWhere ){
100643     sqlite3ExplainPrintf(pVdbe, "WHERE ");
100644     sqlite3ExplainExpr(pVdbe, p->pWhere);
100645     sqlite3ExplainNL(pVdbe);
100646   }
100647   if( p->pGroupBy ){
100648     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
100649     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
100650     sqlite3ExplainNL(pVdbe);
100651   }
100652   if( p->pHaving ){
100653     sqlite3ExplainPrintf(pVdbe, "HAVING ");
100654     sqlite3ExplainExpr(pVdbe, p->pHaving);
100655     sqlite3ExplainNL(pVdbe);
100656   }
100657   if( p->pOrderBy ){
100658     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
100659     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
100660     sqlite3ExplainNL(pVdbe);
100661   }
100662   if( p->pLimit ){
100663     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
100664     sqlite3ExplainExpr(pVdbe, p->pLimit);
100665     sqlite3ExplainNL(pVdbe);
100666   }
100667   if( p->pOffset ){
100668     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
100669     sqlite3ExplainExpr(pVdbe, p->pOffset);
100670     sqlite3ExplainNL(pVdbe);
100671   }
100672 }
100673 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
100674   if( p==0 ){
100675     sqlite3ExplainPrintf(pVdbe, "(null-select)");
100676     return;
100677   }
100678   while( p->pPrior ) p = p->pPrior;
100679   sqlite3ExplainPush(pVdbe);
100680   while( p ){
100681     explainOneSelect(pVdbe, p);
100682     p = p->pNext;
100683     if( p==0 ) break;
100684     sqlite3ExplainNL(pVdbe);
100685     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
100686   }
100687   sqlite3ExplainPrintf(pVdbe, "END");
100688   sqlite3ExplainPop(pVdbe);
100689 }
100690
100691 /* End of the structure debug printing code
100692 *****************************************************************************/
100693 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
100694
100695 /************** End of select.c **********************************************/
100696 /************** Begin file table.c *******************************************/
100697 /*
100698 ** 2001 September 15
100699 **
100700 ** The author disclaims copyright to this source code.  In place of
100701 ** a legal notice, here is a blessing:
100702 **
100703 **    May you do good and not evil.
100704 **    May you find forgiveness for yourself and forgive others.
100705 **    May you share freely, never taking more than you give.
100706 **
100707 *************************************************************************
100708 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
100709 ** interface routines.  These are just wrappers around the main
100710 ** interface routine of sqlite3_exec().
100711 **
100712 ** These routines are in a separate files so that they will not be linked
100713 ** if they are not used.
100714 */
100715 /* #include <stdlib.h> */
100716 /* #include <string.h> */
100717
100718 #ifndef SQLITE_OMIT_GET_TABLE
100719
100720 /*
100721 ** This structure is used to pass data from sqlite3_get_table() through
100722 ** to the callback function is uses to build the result.
100723 */
100724 typedef struct TabResult {
100725   char **azResult;   /* Accumulated output */
100726   char *zErrMsg;     /* Error message text, if an error occurs */
100727   int nAlloc;        /* Slots allocated for azResult[] */
100728   int nRow;          /* Number of rows in the result */
100729   int nColumn;       /* Number of columns in the result */
100730   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
100731   int rc;            /* Return code from sqlite3_exec() */
100732 } TabResult;
100733
100734 /*
100735 ** This routine is called once for each row in the result table.  Its job
100736 ** is to fill in the TabResult structure appropriately, allocating new
100737 ** memory as necessary.
100738 */
100739 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
100740   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
100741   int need;                         /* Slots needed in p->azResult[] */
100742   int i;                            /* Loop counter */
100743   char *z;                          /* A single column of result */
100744
100745   /* Make sure there is enough space in p->azResult to hold everything
100746   ** we need to remember from this invocation of the callback.
100747   */
100748   if( p->nRow==0 && argv!=0 ){
100749     need = nCol*2;
100750   }else{
100751     need = nCol;
100752   }
100753   if( p->nData + need > p->nAlloc ){
100754     char **azNew;
100755     p->nAlloc = p->nAlloc*2 + need;
100756     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
100757     if( azNew==0 ) goto malloc_failed;
100758     p->azResult = azNew;
100759   }
100760
100761   /* If this is the first row, then generate an extra row containing
100762   ** the names of all columns.
100763   */
100764   if( p->nRow==0 ){
100765     p->nColumn = nCol;
100766     for(i=0; i<nCol; i++){
100767       z = sqlite3_mprintf("%s", colv[i]);
100768       if( z==0 ) goto malloc_failed;
100769       p->azResult[p->nData++] = z;
100770     }
100771   }else if( p->nColumn!=nCol ){
100772     sqlite3_free(p->zErrMsg);
100773     p->zErrMsg = sqlite3_mprintf(
100774        "sqlite3_get_table() called with two or more incompatible queries"
100775     );
100776     p->rc = SQLITE_ERROR;
100777     return 1;
100778   }
100779
100780   /* Copy over the row data
100781   */
100782   if( argv!=0 ){
100783     for(i=0; i<nCol; i++){
100784       if( argv[i]==0 ){
100785         z = 0;
100786       }else{
100787         int n = sqlite3Strlen30(argv[i])+1;
100788         z = sqlite3_malloc( n );
100789         if( z==0 ) goto malloc_failed;
100790         memcpy(z, argv[i], n);
100791       }
100792       p->azResult[p->nData++] = z;
100793     }
100794     p->nRow++;
100795   }
100796   return 0;
100797
100798 malloc_failed:
100799   p->rc = SQLITE_NOMEM;
100800   return 1;
100801 }
100802
100803 /*
100804 ** Query the database.  But instead of invoking a callback for each row,
100805 ** malloc() for space to hold the result and return the entire results
100806 ** at the conclusion of the call.
100807 **
100808 ** The result that is written to ***pazResult is held in memory obtained
100809 ** from malloc().  But the caller cannot free this memory directly.
100810 ** Instead, the entire table should be passed to sqlite3_free_table() when
100811 ** the calling procedure is finished using it.
100812 */
100813 SQLITE_API int sqlite3_get_table(
100814   sqlite3 *db,                /* The database on which the SQL executes */
100815   const char *zSql,           /* The SQL to be executed */
100816   char ***pazResult,          /* Write the result table here */
100817   int *pnRow,                 /* Write the number of rows in the result here */
100818   int *pnColumn,              /* Write the number of columns of result here */
100819   char **pzErrMsg             /* Write error messages here */
100820 ){
100821   int rc;
100822   TabResult res;
100823
100824   *pazResult = 0;
100825   if( pnColumn ) *pnColumn = 0;
100826   if( pnRow ) *pnRow = 0;
100827   if( pzErrMsg ) *pzErrMsg = 0;
100828   res.zErrMsg = 0;
100829   res.nRow = 0;
100830   res.nColumn = 0;
100831   res.nData = 1;
100832   res.nAlloc = 20;
100833   res.rc = SQLITE_OK;
100834   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
100835   if( res.azResult==0 ){
100836      db->errCode = SQLITE_NOMEM;
100837      return SQLITE_NOMEM;
100838   }
100839   res.azResult[0] = 0;
100840   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
100841   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
100842   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
100843   if( (rc&0xff)==SQLITE_ABORT ){
100844     sqlite3_free_table(&res.azResult[1]);
100845     if( res.zErrMsg ){
100846       if( pzErrMsg ){
100847         sqlite3_free(*pzErrMsg);
100848         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
100849       }
100850       sqlite3_free(res.zErrMsg);
100851     }
100852     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
100853     return res.rc;
100854   }
100855   sqlite3_free(res.zErrMsg);
100856   if( rc!=SQLITE_OK ){
100857     sqlite3_free_table(&res.azResult[1]);
100858     return rc;
100859   }
100860   if( res.nAlloc>res.nData ){
100861     char **azNew;
100862     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
100863     if( azNew==0 ){
100864       sqlite3_free_table(&res.azResult[1]);
100865       db->errCode = SQLITE_NOMEM;
100866       return SQLITE_NOMEM;
100867     }
100868     res.azResult = azNew;
100869   }
100870   *pazResult = &res.azResult[1];
100871   if( pnColumn ) *pnColumn = res.nColumn;
100872   if( pnRow ) *pnRow = res.nRow;
100873   return rc;
100874 }
100875
100876 /*
100877 ** This routine frees the space the sqlite3_get_table() malloced.
100878 */
100879 SQLITE_API void sqlite3_free_table(
100880   char **azResult            /* Result returned from from sqlite3_get_table() */
100881 ){
100882   if( azResult ){
100883     int i, n;
100884     azResult--;
100885     assert( azResult!=0 );
100886     n = SQLITE_PTR_TO_INT(azResult[0]);
100887     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
100888     sqlite3_free(azResult);
100889   }
100890 }
100891
100892 #endif /* SQLITE_OMIT_GET_TABLE */
100893
100894 /************** End of table.c ***********************************************/
100895 /************** Begin file trigger.c *****************************************/
100896 /*
100897 **
100898 ** The author disclaims copyright to this source code.  In place of
100899 ** a legal notice, here is a blessing:
100900 **
100901 **    May you do good and not evil.
100902 **    May you find forgiveness for yourself and forgive others.
100903 **    May you share freely, never taking more than you give.
100904 **
100905 *************************************************************************
100906 ** This file contains the implementation for TRIGGERs
100907 */
100908
100909 #ifndef SQLITE_OMIT_TRIGGER
100910 /*
100911 ** Delete a linked list of TriggerStep structures.
100912 */
100913 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
100914   while( pTriggerStep ){
100915     TriggerStep * pTmp = pTriggerStep;
100916     pTriggerStep = pTriggerStep->pNext;
100917
100918     sqlite3ExprDelete(db, pTmp->pWhere);
100919     sqlite3ExprListDelete(db, pTmp->pExprList);
100920     sqlite3SelectDelete(db, pTmp->pSelect);
100921     sqlite3IdListDelete(db, pTmp->pIdList);
100922
100923     sqlite3DbFree(db, pTmp);
100924   }
100925 }
100926
100927 /*
100928 ** Given table pTab, return a list of all the triggers attached to
100929 ** the table. The list is connected by Trigger.pNext pointers.
100930 **
100931 ** All of the triggers on pTab that are in the same database as pTab
100932 ** are already attached to pTab->pTrigger.  But there might be additional
100933 ** triggers on pTab in the TEMP schema.  This routine prepends all
100934 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
100935 ** and returns the combined list.
100936 **
100937 ** To state it another way:  This routine returns a list of all triggers
100938 ** that fire off of pTab.  The list will include any TEMP triggers on
100939 ** pTab as well as the triggers lised in pTab->pTrigger.
100940 */
100941 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
100942   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
100943   Trigger *pList = 0;                  /* List of triggers to return */
100944
100945   if( pParse->disableTriggers ){
100946     return 0;
100947   }
100948
100949   if( pTmpSchema!=pTab->pSchema ){
100950     HashElem *p;
100951     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
100952     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
100953       Trigger *pTrig = (Trigger *)sqliteHashData(p);
100954       if( pTrig->pTabSchema==pTab->pSchema
100955        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
100956       ){
100957         pTrig->pNext = (pList ? pList : pTab->pTrigger);
100958         pList = pTrig;
100959       }
100960     }
100961   }
100962
100963   return (pList ? pList : pTab->pTrigger);
100964 }
100965
100966 /*
100967 ** This is called by the parser when it sees a CREATE TRIGGER statement
100968 ** up to the point of the BEGIN before the trigger actions.  A Trigger
100969 ** structure is generated based on the information available and stored
100970 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
100971 ** sqlite3FinishTrigger() function is called to complete the trigger
100972 ** construction process.
100973 */
100974 SQLITE_PRIVATE void sqlite3BeginTrigger(
100975   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
100976   Token *pName1,      /* The name of the trigger */
100977   Token *pName2,      /* The name of the trigger */
100978   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
100979   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
100980   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
100981   SrcList *pTableName,/* The name of the table/view the trigger applies to */
100982   Expr *pWhen,        /* WHEN clause */
100983   int isTemp,         /* True if the TEMPORARY keyword is present */
100984   int noErr           /* Suppress errors if the trigger already exists */
100985 ){
100986   Trigger *pTrigger = 0;  /* The new trigger */
100987   Table *pTab;            /* Table that the trigger fires off of */
100988   char *zName = 0;        /* Name of the trigger */
100989   sqlite3 *db = pParse->db;  /* The database connection */
100990   int iDb;                /* The database to store the trigger in */
100991   Token *pName;           /* The unqualified db name */
100992   DbFixer sFix;           /* State vector for the DB fixer */
100993   int iTabDb;             /* Index of the database holding pTab */
100994
100995   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
100996   assert( pName2!=0 );
100997   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
100998   assert( op>0 && op<0xff );
100999   if( isTemp ){
101000     /* If TEMP was specified, then the trigger name may not be qualified. */
101001     if( pName2->n>0 ){
101002       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
101003       goto trigger_cleanup;
101004     }
101005     iDb = 1;
101006     pName = pName1;
101007   }else{
101008     /* Figure out the db that the trigger will be created in */
101009     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101010     if( iDb<0 ){
101011       goto trigger_cleanup;
101012     }
101013   }
101014   if( !pTableName || db->mallocFailed ){
101015     goto trigger_cleanup;
101016   }
101017
101018   /* A long-standing parser bug is that this syntax was allowed:
101019   **
101020   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
101021   **                                                 ^^^^^^^^
101022   **
101023   ** To maintain backwards compatibility, ignore the database
101024   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
101025   */
101026   if( db->init.busy && iDb!=1 ){
101027     sqlite3DbFree(db, pTableName->a[0].zDatabase);
101028     pTableName->a[0].zDatabase = 0;
101029   }
101030
101031   /* If the trigger name was unqualified, and the table is a temp table,
101032   ** then set iDb to 1 to create the trigger in the temporary database.
101033   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
101034   ** exist, the error is caught by the block below.
101035   */
101036   pTab = sqlite3SrcListLookup(pParse, pTableName);
101037   if( db->init.busy==0 && pName2->n==0 && pTab
101038         && pTab->pSchema==db->aDb[1].pSchema ){
101039     iDb = 1;
101040   }
101041
101042   /* Ensure the table name matches database name and that the table exists */
101043   if( db->mallocFailed ) goto trigger_cleanup;
101044   assert( pTableName->nSrc==1 );
101045   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
101046       sqlite3FixSrcList(&sFix, pTableName) ){
101047     goto trigger_cleanup;
101048   }
101049   pTab = sqlite3SrcListLookup(pParse, pTableName);
101050   if( !pTab ){
101051     /* The table does not exist. */
101052     if( db->init.iDb==1 ){
101053       /* Ticket #3810.
101054       ** Normally, whenever a table is dropped, all associated triggers are
101055       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
101056       ** and the table is dropped by a different database connection, the
101057       ** trigger is not visible to the database connection that does the
101058       ** drop so the trigger cannot be dropped.  This results in an
101059       ** "orphaned trigger" - a trigger whose associated table is missing.
101060       */
101061       db->init.orphanTrigger = 1;
101062     }
101063     goto trigger_cleanup;
101064   }
101065   if( IsVirtual(pTab) ){
101066     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
101067     goto trigger_cleanup;
101068   }
101069
101070   /* Check that the trigger name is not reserved and that no trigger of the
101071   ** specified name exists */
101072   zName = sqlite3NameFromToken(db, pName);
101073   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101074     goto trigger_cleanup;
101075   }
101076   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101077   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
101078                       zName, sqlite3Strlen30(zName)) ){
101079     if( !noErr ){
101080       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
101081     }else{
101082       assert( !db->init.busy );
101083       sqlite3CodeVerifySchema(pParse, iDb);
101084     }
101085     goto trigger_cleanup;
101086   }
101087
101088   /* Do not create a trigger on a system table */
101089   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
101090     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
101091     pParse->nErr++;
101092     goto trigger_cleanup;
101093   }
101094
101095   /* INSTEAD of triggers are only for views and views only support INSTEAD
101096   ** of triggers.
101097   */
101098   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
101099     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
101100         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
101101     goto trigger_cleanup;
101102   }
101103   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
101104     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
101105         " trigger on table: %S", pTableName, 0);
101106     goto trigger_cleanup;
101107   }
101108   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101109
101110 #ifndef SQLITE_OMIT_AUTHORIZATION
101111   {
101112     int code = SQLITE_CREATE_TRIGGER;
101113     const char *zDb = db->aDb[iTabDb].zName;
101114     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
101115     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
101116     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
101117       goto trigger_cleanup;
101118     }
101119     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
101120       goto trigger_cleanup;
101121     }
101122   }
101123 #endif
101124
101125   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
101126   ** cannot appear on views.  So we might as well translate every
101127   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
101128   ** elsewhere.
101129   */
101130   if (tr_tm == TK_INSTEAD){
101131     tr_tm = TK_BEFORE;
101132   }
101133
101134   /* Build the Trigger object */
101135   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
101136   if( pTrigger==0 ) goto trigger_cleanup;
101137   pTrigger->zName = zName;
101138   zName = 0;
101139   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
101140   pTrigger->pSchema = db->aDb[iDb].pSchema;
101141   pTrigger->pTabSchema = pTab->pSchema;
101142   pTrigger->op = (u8)op;
101143   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
101144   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
101145   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
101146   assert( pParse->pNewTrigger==0 );
101147   pParse->pNewTrigger = pTrigger;
101148
101149 trigger_cleanup:
101150   sqlite3DbFree(db, zName);
101151   sqlite3SrcListDelete(db, pTableName);
101152   sqlite3IdListDelete(db, pColumns);
101153   sqlite3ExprDelete(db, pWhen);
101154   if( !pParse->pNewTrigger ){
101155     sqlite3DeleteTrigger(db, pTrigger);
101156   }else{
101157     assert( pParse->pNewTrigger==pTrigger );
101158   }
101159 }
101160
101161 /*
101162 ** This routine is called after all of the trigger actions have been parsed
101163 ** in order to complete the process of building the trigger.
101164 */
101165 SQLITE_PRIVATE void sqlite3FinishTrigger(
101166   Parse *pParse,          /* Parser context */
101167   TriggerStep *pStepList, /* The triggered program */
101168   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
101169 ){
101170   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
101171   char *zName;                            /* Name of trigger */
101172   sqlite3 *db = pParse->db;               /* The database */
101173   DbFixer sFix;                           /* Fixer object */
101174   int iDb;                                /* Database containing the trigger */
101175   Token nameToken;                        /* Trigger name for error reporting */
101176
101177   pParse->pNewTrigger = 0;
101178   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
101179   zName = pTrig->zName;
101180   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
101181   pTrig->step_list = pStepList;
101182   while( pStepList ){
101183     pStepList->pTrig = pTrig;
101184     pStepList = pStepList->pNext;
101185   }
101186   nameToken.z = pTrig->zName;
101187   nameToken.n = sqlite3Strlen30(nameToken.z);
101188   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
101189           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
101190     goto triggerfinish_cleanup;
101191   }
101192
101193   /* if we are not initializing,
101194   ** build the sqlite_master entry
101195   */
101196   if( !db->init.busy ){
101197     Vdbe *v;
101198     char *z;
101199
101200     /* Make an entry in the sqlite_master table */
101201     v = sqlite3GetVdbe(pParse);
101202     if( v==0 ) goto triggerfinish_cleanup;
101203     sqlite3BeginWriteOperation(pParse, 0, iDb);
101204     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
101205     sqlite3NestedParse(pParse,
101206        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
101207        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
101208        pTrig->table, z);
101209     sqlite3DbFree(db, z);
101210     sqlite3ChangeCookie(pParse, iDb);
101211     sqlite3VdbeAddParseSchemaOp(v, iDb,
101212         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
101213   }
101214
101215   if( db->init.busy ){
101216     Trigger *pLink = pTrig;
101217     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
101218     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101219     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
101220     if( pTrig ){
101221       db->mallocFailed = 1;
101222     }else if( pLink->pSchema==pLink->pTabSchema ){
101223       Table *pTab;
101224       int n = sqlite3Strlen30(pLink->table);
101225       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
101226       assert( pTab!=0 );
101227       pLink->pNext = pTab->pTrigger;
101228       pTab->pTrigger = pLink;
101229     }
101230   }
101231
101232 triggerfinish_cleanup:
101233   sqlite3DeleteTrigger(db, pTrig);
101234   assert( !pParse->pNewTrigger );
101235   sqlite3DeleteTriggerStep(db, pStepList);
101236 }
101237
101238 /*
101239 ** Turn a SELECT statement (that the pSelect parameter points to) into
101240 ** a trigger step.  Return a pointer to a TriggerStep structure.
101241 **
101242 ** The parser calls this routine when it finds a SELECT statement in
101243 ** body of a TRIGGER.
101244 */
101245 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
101246   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
101247   if( pTriggerStep==0 ) {
101248     sqlite3SelectDelete(db, pSelect);
101249     return 0;
101250   }
101251   pTriggerStep->op = TK_SELECT;
101252   pTriggerStep->pSelect = pSelect;
101253   pTriggerStep->orconf = OE_Default;
101254   return pTriggerStep;
101255 }
101256
101257 /*
101258 ** Allocate space to hold a new trigger step.  The allocated space
101259 ** holds both the TriggerStep object and the TriggerStep.target.z string.
101260 **
101261 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
101262 */
101263 static TriggerStep *triggerStepAllocate(
101264   sqlite3 *db,                /* Database connection */
101265   u8 op,                      /* Trigger opcode */
101266   Token *pName                /* The target name */
101267 ){
101268   TriggerStep *pTriggerStep;
101269
101270   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
101271   if( pTriggerStep ){
101272     char *z = (char*)&pTriggerStep[1];
101273     memcpy(z, pName->z, pName->n);
101274     pTriggerStep->target.z = z;
101275     pTriggerStep->target.n = pName->n;
101276     pTriggerStep->op = op;
101277   }
101278   return pTriggerStep;
101279 }
101280
101281 /*
101282 ** Build a trigger step out of an INSERT statement.  Return a pointer
101283 ** to the new trigger step.
101284 **
101285 ** The parser calls this routine when it sees an INSERT inside the
101286 ** body of a trigger.
101287 */
101288 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
101289   sqlite3 *db,        /* The database connection */
101290   Token *pTableName,  /* Name of the table into which we insert */
101291   IdList *pColumn,    /* List of columns in pTableName to insert into */
101292   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
101293   Select *pSelect,    /* A SELECT statement that supplies values */
101294   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
101295 ){
101296   TriggerStep *pTriggerStep;
101297
101298   assert(pEList == 0 || pSelect == 0);
101299   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
101300
101301   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
101302   if( pTriggerStep ){
101303     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
101304     pTriggerStep->pIdList = pColumn;
101305     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101306     pTriggerStep->orconf = orconf;
101307   }else{
101308     sqlite3IdListDelete(db, pColumn);
101309   }
101310   sqlite3ExprListDelete(db, pEList);
101311   sqlite3SelectDelete(db, pSelect);
101312
101313   return pTriggerStep;
101314 }
101315
101316 /*
101317 ** Construct a trigger step that implements an UPDATE statement and return
101318 ** a pointer to that trigger step.  The parser calls this routine when it
101319 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
101320 */
101321 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
101322   sqlite3 *db,         /* The database connection */
101323   Token *pTableName,   /* Name of the table to be updated */
101324   ExprList *pEList,    /* The SET clause: list of column and new values */
101325   Expr *pWhere,        /* The WHERE clause */
101326   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
101327 ){
101328   TriggerStep *pTriggerStep;
101329
101330   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
101331   if( pTriggerStep ){
101332     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101333     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101334     pTriggerStep->orconf = orconf;
101335   }
101336   sqlite3ExprListDelete(db, pEList);
101337   sqlite3ExprDelete(db, pWhere);
101338   return pTriggerStep;
101339 }
101340
101341 /*
101342 ** Construct a trigger step that implements a DELETE statement and return
101343 ** a pointer to that trigger step.  The parser calls this routine when it
101344 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
101345 */
101346 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
101347   sqlite3 *db,            /* Database connection */
101348   Token *pTableName,      /* The table from which rows are deleted */
101349   Expr *pWhere            /* The WHERE clause */
101350 ){
101351   TriggerStep *pTriggerStep;
101352
101353   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
101354   if( pTriggerStep ){
101355     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101356     pTriggerStep->orconf = OE_Default;
101357   }
101358   sqlite3ExprDelete(db, pWhere);
101359   return pTriggerStep;
101360 }
101361
101362 /*
101363 ** Recursively delete a Trigger structure
101364 */
101365 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
101366   if( pTrigger==0 ) return;
101367   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
101368   sqlite3DbFree(db, pTrigger->zName);
101369   sqlite3DbFree(db, pTrigger->table);
101370   sqlite3ExprDelete(db, pTrigger->pWhen);
101371   sqlite3IdListDelete(db, pTrigger->pColumns);
101372   sqlite3DbFree(db, pTrigger);
101373 }
101374
101375 /*
101376 ** This function is called to drop a trigger from the database schema.
101377 **
101378 ** This may be called directly from the parser and therefore identifies
101379 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
101380 ** same job as this routine except it takes a pointer to the trigger
101381 ** instead of the trigger name.
101382 **/
101383 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
101384   Trigger *pTrigger = 0;
101385   int i;
101386   const char *zDb;
101387   const char *zName;
101388   int nName;
101389   sqlite3 *db = pParse->db;
101390
101391   if( db->mallocFailed ) goto drop_trigger_cleanup;
101392   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101393     goto drop_trigger_cleanup;
101394   }
101395
101396   assert( pName->nSrc==1 );
101397   zDb = pName->a[0].zDatabase;
101398   zName = pName->a[0].zName;
101399   nName = sqlite3Strlen30(zName);
101400   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
101401   for(i=OMIT_TEMPDB; i<db->nDb; i++){
101402     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
101403     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
101404     assert( sqlite3SchemaMutexHeld(db, j, 0) );
101405     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
101406     if( pTrigger ) break;
101407   }
101408   if( !pTrigger ){
101409     if( !noErr ){
101410       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
101411     }else{
101412       sqlite3CodeVerifyNamedSchema(pParse, zDb);
101413     }
101414     pParse->checkSchema = 1;
101415     goto drop_trigger_cleanup;
101416   }
101417   sqlite3DropTriggerPtr(pParse, pTrigger);
101418
101419 drop_trigger_cleanup:
101420   sqlite3SrcListDelete(db, pName);
101421 }
101422
101423 /*
101424 ** Return a pointer to the Table structure for the table that a trigger
101425 ** is set on.
101426 */
101427 static Table *tableOfTrigger(Trigger *pTrigger){
101428   int n = sqlite3Strlen30(pTrigger->table);
101429   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
101430 }
101431
101432
101433 /*
101434 ** Drop a trigger given a pointer to that trigger.
101435 */
101436 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
101437   Table   *pTable;
101438   Vdbe *v;
101439   sqlite3 *db = pParse->db;
101440   int iDb;
101441
101442   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
101443   assert( iDb>=0 && iDb<db->nDb );
101444   pTable = tableOfTrigger(pTrigger);
101445   assert( pTable );
101446   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
101447 #ifndef SQLITE_OMIT_AUTHORIZATION
101448   {
101449     int code = SQLITE_DROP_TRIGGER;
101450     const char *zDb = db->aDb[iDb].zName;
101451     const char *zTab = SCHEMA_TABLE(iDb);
101452     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
101453     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
101454       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
101455       return;
101456     }
101457   }
101458 #endif
101459
101460   /* Generate code to destroy the database record of the trigger.
101461   */
101462   assert( pTable!=0 );
101463   if( (v = sqlite3GetVdbe(pParse))!=0 ){
101464     int base;
101465     static const VdbeOpList dropTrigger[] = {
101466       { OP_Rewind,     0, ADDR(9),  0},
101467       { OP_String8,    0, 1,        0}, /* 1 */
101468       { OP_Column,     0, 1,        2},
101469       { OP_Ne,         2, ADDR(8),  1},
101470       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
101471       { OP_Column,     0, 0,        2},
101472       { OP_Ne,         2, ADDR(8),  1},
101473       { OP_Delete,     0, 0,        0},
101474       { OP_Next,       0, ADDR(1),  0}, /* 8 */
101475     };
101476
101477     sqlite3BeginWriteOperation(pParse, 0, iDb);
101478     sqlite3OpenMasterTable(pParse, iDb);
101479     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
101480     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
101481     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
101482     sqlite3ChangeCookie(pParse, iDb);
101483     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
101484     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
101485     if( pParse->nMem<3 ){
101486       pParse->nMem = 3;
101487     }
101488   }
101489 }
101490
101491 /*
101492 ** Remove a trigger from the hash tables of the sqlite* pointer.
101493 */
101494 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
101495   Trigger *pTrigger;
101496   Hash *pHash;
101497
101498   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101499   pHash = &(db->aDb[iDb].pSchema->trigHash);
101500   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
101501   if( ALWAYS(pTrigger) ){
101502     if( pTrigger->pSchema==pTrigger->pTabSchema ){
101503       Table *pTab = tableOfTrigger(pTrigger);
101504       Trigger **pp;
101505       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
101506       *pp = (*pp)->pNext;
101507     }
101508     sqlite3DeleteTrigger(db, pTrigger);
101509     db->flags |= SQLITE_InternChanges;
101510   }
101511 }
101512
101513 /*
101514 ** pEList is the SET clause of an UPDATE statement.  Each entry
101515 ** in pEList is of the format <id>=<expr>.  If any of the entries
101516 ** in pEList have an <id> which matches an identifier in pIdList,
101517 ** then return TRUE.  If pIdList==NULL, then it is considered a
101518 ** wildcard that matches anything.  Likewise if pEList==NULL then
101519 ** it matches anything so always return true.  Return false only
101520 ** if there is no match.
101521 */
101522 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
101523   int e;
101524   if( pIdList==0 || NEVER(pEList==0) ) return 1;
101525   for(e=0; e<pEList->nExpr; e++){
101526     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
101527   }
101528   return 0;
101529 }
101530
101531 /*
101532 ** Return a list of all triggers on table pTab if there exists at least
101533 ** one trigger that must be fired when an operation of type 'op' is
101534 ** performed on the table, and, if that operation is an UPDATE, if at
101535 ** least one of the columns in pChanges is being modified.
101536 */
101537 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
101538   Parse *pParse,          /* Parse context */
101539   Table *pTab,            /* The table the contains the triggers */
101540   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
101541   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
101542   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
101543 ){
101544   int mask = 0;
101545   Trigger *pList = 0;
101546   Trigger *p;
101547
101548   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
101549     pList = sqlite3TriggerList(pParse, pTab);
101550   }
101551   assert( pList==0 || IsVirtual(pTab)==0 );
101552   for(p=pList; p; p=p->pNext){
101553     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
101554       mask |= p->tr_tm;
101555     }
101556   }
101557   if( pMask ){
101558     *pMask = mask;
101559   }
101560   return (mask ? pList : 0);
101561 }
101562
101563 /*
101564 ** Convert the pStep->target token into a SrcList and return a pointer
101565 ** to that SrcList.
101566 **
101567 ** This routine adds a specific database name, if needed, to the target when
101568 ** forming the SrcList.  This prevents a trigger in one database from
101569 ** referring to a target in another database.  An exception is when the
101570 ** trigger is in TEMP in which case it can refer to any other database it
101571 ** wants.
101572 */
101573 static SrcList *targetSrcList(
101574   Parse *pParse,       /* The parsing context */
101575   TriggerStep *pStep   /* The trigger containing the target token */
101576 ){
101577   int iDb;             /* Index of the database to use */
101578   SrcList *pSrc;       /* SrcList to be returned */
101579
101580   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
101581   if( pSrc ){
101582     assert( pSrc->nSrc>0 );
101583     assert( pSrc->a!=0 );
101584     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
101585     if( iDb==0 || iDb>=2 ){
101586       sqlite3 *db = pParse->db;
101587       assert( iDb<pParse->db->nDb );
101588       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
101589     }
101590   }
101591   return pSrc;
101592 }
101593
101594 /*
101595 ** Generate VDBE code for the statements inside the body of a single
101596 ** trigger.
101597 */
101598 static int codeTriggerProgram(
101599   Parse *pParse,            /* The parser context */
101600   TriggerStep *pStepList,   /* List of statements inside the trigger body */
101601   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
101602 ){
101603   TriggerStep *pStep;
101604   Vdbe *v = pParse->pVdbe;
101605   sqlite3 *db = pParse->db;
101606
101607   assert( pParse->pTriggerTab && pParse->pToplevel );
101608   assert( pStepList );
101609   assert( v!=0 );
101610   for(pStep=pStepList; pStep; pStep=pStep->pNext){
101611     /* Figure out the ON CONFLICT policy that will be used for this step
101612     ** of the trigger program. If the statement that caused this trigger
101613     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
101614     ** the ON CONFLICT policy that was specified as part of the trigger
101615     ** step statement. Example:
101616     **
101617     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
101618     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
101619     **   END;
101620     **
101621     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
101622     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
101623     */
101624     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
101625
101626     /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
101627     ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
101628     ** that it is not safe to refactor constants (this happens after the
101629     ** start of the first loop in the SQL statement is coded - at that
101630     ** point code may be conditionally executed, so it is no longer safe to
101631     ** initialize constant register values).  */
101632     assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
101633     pParse->cookieGoto = 0;
101634
101635     switch( pStep->op ){
101636       case TK_UPDATE: {
101637         sqlite3Update(pParse,
101638           targetSrcList(pParse, pStep),
101639           sqlite3ExprListDup(db, pStep->pExprList, 0),
101640           sqlite3ExprDup(db, pStep->pWhere, 0),
101641           pParse->eOrconf
101642         );
101643         break;
101644       }
101645       case TK_INSERT: {
101646         sqlite3Insert(pParse,
101647           targetSrcList(pParse, pStep),
101648           sqlite3ExprListDup(db, pStep->pExprList, 0),
101649           sqlite3SelectDup(db, pStep->pSelect, 0),
101650           sqlite3IdListDup(db, pStep->pIdList),
101651           pParse->eOrconf
101652         );
101653         break;
101654       }
101655       case TK_DELETE: {
101656         sqlite3DeleteFrom(pParse,
101657           targetSrcList(pParse, pStep),
101658           sqlite3ExprDup(db, pStep->pWhere, 0)
101659         );
101660         break;
101661       }
101662       default: assert( pStep->op==TK_SELECT ); {
101663         SelectDest sDest;
101664         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
101665         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
101666         sqlite3Select(pParse, pSelect, &sDest);
101667         sqlite3SelectDelete(db, pSelect);
101668         break;
101669       }
101670     }
101671     if( pStep->op!=TK_SELECT ){
101672       sqlite3VdbeAddOp0(v, OP_ResetCount);
101673     }
101674   }
101675
101676   return 0;
101677 }
101678
101679 #ifdef SQLITE_DEBUG
101680 /*
101681 ** This function is used to add VdbeComment() annotations to a VDBE
101682 ** program. It is not used in production code, only for debugging.
101683 */
101684 static const char *onErrorText(int onError){
101685   switch( onError ){
101686     case OE_Abort:    return "abort";
101687     case OE_Rollback: return "rollback";
101688     case OE_Fail:     return "fail";
101689     case OE_Replace:  return "replace";
101690     case OE_Ignore:   return "ignore";
101691     case OE_Default:  return "default";
101692   }
101693   return "n/a";
101694 }
101695 #endif
101696
101697 /*
101698 ** Parse context structure pFrom has just been used to create a sub-vdbe
101699 ** (trigger program). If an error has occurred, transfer error information
101700 ** from pFrom to pTo.
101701 */
101702 static void transferParseError(Parse *pTo, Parse *pFrom){
101703   assert( pFrom->zErrMsg==0 || pFrom->nErr );
101704   assert( pTo->zErrMsg==0 || pTo->nErr );
101705   if( pTo->nErr==0 ){
101706     pTo->zErrMsg = pFrom->zErrMsg;
101707     pTo->nErr = pFrom->nErr;
101708   }else{
101709     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
101710   }
101711 }
101712
101713 /*
101714 ** Create and populate a new TriggerPrg object with a sub-program
101715 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
101716 */
101717 static TriggerPrg *codeRowTrigger(
101718   Parse *pParse,       /* Current parse context */
101719   Trigger *pTrigger,   /* Trigger to code */
101720   Table *pTab,         /* The table pTrigger is attached to */
101721   int orconf           /* ON CONFLICT policy to code trigger program with */
101722 ){
101723   Parse *pTop = sqlite3ParseToplevel(pParse);
101724   sqlite3 *db = pParse->db;   /* Database handle */
101725   TriggerPrg *pPrg;           /* Value to return */
101726   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
101727   Vdbe *v;                    /* Temporary VM */
101728   NameContext sNC;            /* Name context for sub-vdbe */
101729   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
101730   Parse *pSubParse;           /* Parse context for sub-vdbe */
101731   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
101732
101733   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
101734   assert( pTop->pVdbe );
101735
101736   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
101737   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
101738   ** list of the top-level Parse object sooner rather than later.  */
101739   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
101740   if( !pPrg ) return 0;
101741   pPrg->pNext = pTop->pTriggerPrg;
101742   pTop->pTriggerPrg = pPrg;
101743   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
101744   if( !pProgram ) return 0;
101745   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
101746   pPrg->pTrigger = pTrigger;
101747   pPrg->orconf = orconf;
101748   pPrg->aColmask[0] = 0xffffffff;
101749   pPrg->aColmask[1] = 0xffffffff;
101750
101751   /* Allocate and populate a new Parse context to use for coding the
101752   ** trigger sub-program.  */
101753   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
101754   if( !pSubParse ) return 0;
101755   memset(&sNC, 0, sizeof(sNC));
101756   sNC.pParse = pSubParse;
101757   pSubParse->db = db;
101758   pSubParse->pTriggerTab = pTab;
101759   pSubParse->pToplevel = pTop;
101760   pSubParse->zAuthContext = pTrigger->zName;
101761   pSubParse->eTriggerOp = pTrigger->op;
101762   pSubParse->nQueryLoop = pParse->nQueryLoop;
101763
101764   v = sqlite3GetVdbe(pSubParse);
101765   if( v ){
101766     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
101767       pTrigger->zName, onErrorText(orconf),
101768       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
101769         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
101770         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
101771         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
101772       pTab->zName
101773     ));
101774 #ifndef SQLITE_OMIT_TRACE
101775     sqlite3VdbeChangeP4(v, -1,
101776       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
101777     );
101778 #endif
101779
101780     /* If one was specified, code the WHEN clause. If it evaluates to false
101781     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
101782     ** OP_Halt inserted at the end of the program.  */
101783     if( pTrigger->pWhen ){
101784       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
101785       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
101786        && db->mallocFailed==0
101787       ){
101788         iEndTrigger = sqlite3VdbeMakeLabel(v);
101789         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
101790       }
101791       sqlite3ExprDelete(db, pWhen);
101792     }
101793
101794     /* Code the trigger program into the sub-vdbe. */
101795     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
101796
101797     /* Insert an OP_Halt at the end of the sub-program. */
101798     if( iEndTrigger ){
101799       sqlite3VdbeResolveLabel(v, iEndTrigger);
101800     }
101801     sqlite3VdbeAddOp0(v, OP_Halt);
101802     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
101803
101804     transferParseError(pParse, pSubParse);
101805     if( db->mallocFailed==0 ){
101806       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
101807     }
101808     pProgram->nMem = pSubParse->nMem;
101809     pProgram->nCsr = pSubParse->nTab;
101810     pProgram->nOnce = pSubParse->nOnce;
101811     pProgram->token = (void *)pTrigger;
101812     pPrg->aColmask[0] = pSubParse->oldmask;
101813     pPrg->aColmask[1] = pSubParse->newmask;
101814     sqlite3VdbeDelete(v);
101815   }
101816
101817   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
101818   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
101819   sqlite3StackFree(db, pSubParse);
101820
101821   return pPrg;
101822 }
101823
101824 /*
101825 ** Return a pointer to a TriggerPrg object containing the sub-program for
101826 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
101827 ** TriggerPrg object exists, a new object is allocated and populated before
101828 ** being returned.
101829 */
101830 static TriggerPrg *getRowTrigger(
101831   Parse *pParse,       /* Current parse context */
101832   Trigger *pTrigger,   /* Trigger to code */
101833   Table *pTab,         /* The table trigger pTrigger is attached to */
101834   int orconf           /* ON CONFLICT algorithm. */
101835 ){
101836   Parse *pRoot = sqlite3ParseToplevel(pParse);
101837   TriggerPrg *pPrg;
101838
101839   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
101840
101841   /* It may be that this trigger has already been coded (or is in the
101842   ** process of being coded). If this is the case, then an entry with
101843   ** a matching TriggerPrg.pTrigger field will be present somewhere
101844   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
101845   for(pPrg=pRoot->pTriggerPrg;
101846       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
101847       pPrg=pPrg->pNext
101848   );
101849
101850   /* If an existing TriggerPrg could not be located, create a new one. */
101851   if( !pPrg ){
101852     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
101853   }
101854
101855   return pPrg;
101856 }
101857
101858 /*
101859 ** Generate code for the trigger program associated with trigger p on
101860 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
101861 ** function are the same as those described in the header function for
101862 ** sqlite3CodeRowTrigger()
101863 */
101864 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
101865   Parse *pParse,       /* Parse context */
101866   Trigger *p,          /* Trigger to code */
101867   Table *pTab,         /* The table to code triggers from */
101868   int reg,             /* Reg array containing OLD.* and NEW.* values */
101869   int orconf,          /* ON CONFLICT policy */
101870   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
101871 ){
101872   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
101873   TriggerPrg *pPrg;
101874   pPrg = getRowTrigger(pParse, p, pTab, orconf);
101875   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
101876
101877   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
101878   ** is a pointer to the sub-vdbe containing the trigger program.  */
101879   if( pPrg ){
101880     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
101881
101882     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
101883     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
101884     VdbeComment(
101885         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
101886
101887     /* Set the P5 operand of the OP_Program instruction to non-zero if
101888     ** recursive invocation of this trigger program is disallowed. Recursive
101889     ** invocation is disallowed if (a) the sub-program is really a trigger,
101890     ** not a foreign key action, and (b) the flag to enable recursive triggers
101891     ** is clear.  */
101892     sqlite3VdbeChangeP5(v, (u8)bRecursive);
101893   }
101894 }
101895
101896 /*
101897 ** This is called to code the required FOR EACH ROW triggers for an operation
101898 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
101899 ** is given by the op paramater. The tr_tm parameter determines whether the
101900 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
101901 ** parameter pChanges is passed the list of columns being modified.
101902 **
101903 ** If there are no triggers that fire at the specified time for the specified
101904 ** operation on pTab, this function is a no-op.
101905 **
101906 ** The reg argument is the address of the first in an array of registers
101907 ** that contain the values substituted for the new.* and old.* references
101908 ** in the trigger program. If N is the number of columns in table pTab
101909 ** (a copy of pTab->nCol), then registers are populated as follows:
101910 **
101911 **   Register       Contains
101912 **   ------------------------------------------------------
101913 **   reg+0          OLD.rowid
101914 **   reg+1          OLD.* value of left-most column of pTab
101915 **   ...            ...
101916 **   reg+N          OLD.* value of right-most column of pTab
101917 **   reg+N+1        NEW.rowid
101918 **   reg+N+2        OLD.* value of left-most column of pTab
101919 **   ...            ...
101920 **   reg+N+N+1      NEW.* value of right-most column of pTab
101921 **
101922 ** For ON DELETE triggers, the registers containing the NEW.* values will
101923 ** never be accessed by the trigger program, so they are not allocated or
101924 ** populated by the caller (there is no data to populate them with anyway).
101925 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
101926 ** are never accessed, and so are not allocated by the caller. So, for an
101927 ** ON INSERT trigger, the value passed to this function as parameter reg
101928 ** is not a readable register, although registers (reg+N) through
101929 ** (reg+N+N+1) are.
101930 **
101931 ** Parameter orconf is the default conflict resolution algorithm for the
101932 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
101933 ** is the instruction that control should jump to if a trigger program
101934 ** raises an IGNORE exception.
101935 */
101936 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
101937   Parse *pParse,       /* Parse context */
101938   Trigger *pTrigger,   /* List of triggers on table pTab */
101939   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
101940   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
101941   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
101942   Table *pTab,         /* The table to code triggers from */
101943   int reg,             /* The first in an array of registers (see above) */
101944   int orconf,          /* ON CONFLICT policy */
101945   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
101946 ){
101947   Trigger *p;          /* Used to iterate through pTrigger list */
101948
101949   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
101950   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
101951   assert( (op==TK_UPDATE)==(pChanges!=0) );
101952
101953   for(p=pTrigger; p; p=p->pNext){
101954
101955     /* Sanity checking:  The schema for the trigger and for the table are
101956     ** always defined.  The trigger must be in the same schema as the table
101957     ** or else it must be a TEMP trigger. */
101958     assert( p->pSchema!=0 );
101959     assert( p->pTabSchema!=0 );
101960     assert( p->pSchema==p->pTabSchema
101961          || p->pSchema==pParse->db->aDb[1].pSchema );
101962
101963     /* Determine whether we should code this trigger */
101964     if( p->op==op
101965      && p->tr_tm==tr_tm
101966      && checkColumnOverlap(p->pColumns, pChanges)
101967     ){
101968       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
101969     }
101970   }
101971 }
101972
101973 /*
101974 ** Triggers may access values stored in the old.* or new.* pseudo-table.
101975 ** This function returns a 32-bit bitmask indicating which columns of the
101976 ** old.* or new.* tables actually are used by triggers. This information
101977 ** may be used by the caller, for example, to avoid having to load the entire
101978 ** old.* record into memory when executing an UPDATE or DELETE command.
101979 **
101980 ** Bit 0 of the returned mask is set if the left-most column of the
101981 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
101982 ** the second leftmost column value is required, and so on. If there
101983 ** are more than 32 columns in the table, and at least one of the columns
101984 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
101985 **
101986 ** It is not possible to determine if the old.rowid or new.rowid column is
101987 ** accessed by triggers. The caller must always assume that it is.
101988 **
101989 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
101990 ** applies to the old.* table. If 1, the new.* table.
101991 **
101992 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
101993 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
101994 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
101995 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
101996 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
101997 */
101998 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
101999   Parse *pParse,       /* Parse context */
102000   Trigger *pTrigger,   /* List of triggers on table pTab */
102001   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
102002   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
102003   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102004   Table *pTab,         /* The table to code triggers from */
102005   int orconf           /* Default ON CONFLICT policy for trigger steps */
102006 ){
102007   const int op = pChanges ? TK_UPDATE : TK_DELETE;
102008   u32 mask = 0;
102009   Trigger *p;
102010
102011   assert( isNew==1 || isNew==0 );
102012   for(p=pTrigger; p; p=p->pNext){
102013     if( p->op==op && (tr_tm&p->tr_tm)
102014      && checkColumnOverlap(p->pColumns,pChanges)
102015     ){
102016       TriggerPrg *pPrg;
102017       pPrg = getRowTrigger(pParse, p, pTab, orconf);
102018       if( pPrg ){
102019         mask |= pPrg->aColmask[isNew];
102020       }
102021     }
102022   }
102023
102024   return mask;
102025 }
102026
102027 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
102028
102029 /************** End of trigger.c *********************************************/
102030 /************** Begin file update.c ******************************************/
102031 /*
102032 ** 2001 September 15
102033 **
102034 ** The author disclaims copyright to this source code.  In place of
102035 ** a legal notice, here is a blessing:
102036 **
102037 **    May you do good and not evil.
102038 **    May you find forgiveness for yourself and forgive others.
102039 **    May you share freely, never taking more than you give.
102040 **
102041 *************************************************************************
102042 ** This file contains C code routines that are called by the parser
102043 ** to handle UPDATE statements.
102044 */
102045
102046 #ifndef SQLITE_OMIT_VIRTUALTABLE
102047 /* Forward declaration */
102048 static void updateVirtualTable(
102049   Parse *pParse,       /* The parsing context */
102050   SrcList *pSrc,       /* The virtual table to be modified */
102051   Table *pTab,         /* The virtual table */
102052   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
102053   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
102054   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
102055   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
102056   int onError          /* ON CONFLICT strategy */
102057 );
102058 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102059
102060 /*
102061 ** The most recently coded instruction was an OP_Column to retrieve the
102062 ** i-th column of table pTab. This routine sets the P4 parameter of the
102063 ** OP_Column to the default value, if any.
102064 **
102065 ** The default value of a column is specified by a DEFAULT clause in the
102066 ** column definition. This was either supplied by the user when the table
102067 ** was created, or added later to the table definition by an ALTER TABLE
102068 ** command. If the latter, then the row-records in the table btree on disk
102069 ** may not contain a value for the column and the default value, taken
102070 ** from the P4 parameter of the OP_Column instruction, is returned instead.
102071 ** If the former, then all row-records are guaranteed to include a value
102072 ** for the column and the P4 value is not required.
102073 **
102074 ** Column definitions created by an ALTER TABLE command may only have
102075 ** literal default values specified: a number, null or a string. (If a more
102076 ** complicated default expression value was provided, it is evaluated
102077 ** when the ALTER TABLE is executed and one of the literal values written
102078 ** into the sqlite_master table.)
102079 **
102080 ** Therefore, the P4 parameter is only required if the default value for
102081 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
102082 ** function is capable of transforming these types of expressions into
102083 ** sqlite3_value objects.
102084 **
102085 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
102086 ** on register iReg. This is used when an equivalent integer value is
102087 ** stored in place of an 8-byte floating point value in order to save
102088 ** space.
102089 */
102090 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
102091   assert( pTab!=0 );
102092   if( !pTab->pSelect ){
102093     sqlite3_value *pValue;
102094     u8 enc = ENC(sqlite3VdbeDb(v));
102095     Column *pCol = &pTab->aCol[i];
102096     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
102097     assert( i<pTab->nCol );
102098     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
102099                          pCol->affinity, &pValue);
102100     if( pValue ){
102101       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
102102     }
102103 #ifndef SQLITE_OMIT_FLOATING_POINT
102104     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
102105       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
102106     }
102107 #endif
102108   }
102109 }
102110
102111 /*
102112 ** Process an UPDATE statement.
102113 **
102114 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
102115 **          \_______/ \________/     \______/       \________________/
102116 *            onError   pTabList      pChanges             pWhere
102117 */
102118 SQLITE_PRIVATE void sqlite3Update(
102119   Parse *pParse,         /* The parser context */
102120   SrcList *pTabList,     /* The table in which we should change things */
102121   ExprList *pChanges,    /* Things to be changed */
102122   Expr *pWhere,          /* The WHERE clause.  May be null */
102123   int onError            /* How to handle constraint errors */
102124 ){
102125   int i, j;              /* Loop counters */
102126   Table *pTab;           /* The table to be updated */
102127   int addr = 0;          /* VDBE instruction address of the start of the loop */
102128   WhereInfo *pWInfo;     /* Information about the WHERE clause */
102129   Vdbe *v;               /* The virtual database engine */
102130   Index *pIdx;           /* For looping over indices */
102131   int nIdx;              /* Number of indices that need updating */
102132   int iCur;              /* VDBE Cursor number of pTab */
102133   sqlite3 *db;           /* The database structure */
102134   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
102135   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
102136                          ** an expression for the i-th column of the table.
102137                          ** aXRef[i]==-1 if the i-th column is not changed. */
102138   int chngRowid;         /* True if the record number is being changed */
102139   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
102140   int openAll = 0;       /* True if all indices need to be opened */
102141   AuthContext sContext;  /* The authorization context */
102142   NameContext sNC;       /* The name-context to resolve expressions in */
102143   int iDb;               /* Database containing the table being updated */
102144   int okOnePass;         /* True for one-pass algorithm without the FIFO */
102145   int hasFK;             /* True if foreign key processing is required */
102146
102147 #ifndef SQLITE_OMIT_TRIGGER
102148   int isView;            /* True when updating a view (INSTEAD OF trigger) */
102149   Trigger *pTrigger;     /* List of triggers on pTab, if required */
102150   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102151 #endif
102152   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
102153
102154   /* Register Allocations */
102155   int regRowCount = 0;   /* A count of rows changed */
102156   int regOldRowid;       /* The old rowid */
102157   int regNewRowid;       /* The new rowid */
102158   int regNew;            /* Content of the NEW.* table in triggers */
102159   int regOld = 0;        /* Content of OLD.* table in triggers */
102160   int regRowSet = 0;     /* Rowset of rows to be updated */
102161
102162   memset(&sContext, 0, sizeof(sContext));
102163   db = pParse->db;
102164   if( pParse->nErr || db->mallocFailed ){
102165     goto update_cleanup;
102166   }
102167   assert( pTabList->nSrc==1 );
102168
102169   /* Locate the table which we want to update.
102170   */
102171   pTab = sqlite3SrcListLookup(pParse, pTabList);
102172   if( pTab==0 ) goto update_cleanup;
102173   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102174
102175   /* Figure out if we have any triggers and if the table being
102176   ** updated is a view.
102177   */
102178 #ifndef SQLITE_OMIT_TRIGGER
102179   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
102180   isView = pTab->pSelect!=0;
102181   assert( pTrigger || tmask==0 );
102182 #else
102183 # define pTrigger 0
102184 # define isView 0
102185 # define tmask 0
102186 #endif
102187 #ifdef SQLITE_OMIT_VIEW
102188 # undef isView
102189 # define isView 0
102190 #endif
102191
102192   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102193     goto update_cleanup;
102194   }
102195   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
102196     goto update_cleanup;
102197   }
102198   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
102199   if( aXRef==0 ) goto update_cleanup;
102200   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
102201
102202   /* Allocate a cursors for the main database table and for all indices.
102203   ** The index cursors might not be used, but if they are used they
102204   ** need to occur right after the database cursor.  So go ahead and
102205   ** allocate enough space, just in case.
102206   */
102207   pTabList->a[0].iCursor = iCur = pParse->nTab++;
102208   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102209     pParse->nTab++;
102210   }
102211
102212   /* Initialize the name-context */
102213   memset(&sNC, 0, sizeof(sNC));
102214   sNC.pParse = pParse;
102215   sNC.pSrcList = pTabList;
102216
102217   /* Resolve the column names in all the expressions of the
102218   ** of the UPDATE statement.  Also find the column index
102219   ** for each column to be updated in the pChanges array.  For each
102220   ** column to be updated, make sure we have authorization to change
102221   ** that column.
102222   */
102223   chngRowid = 0;
102224   for(i=0; i<pChanges->nExpr; i++){
102225     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
102226       goto update_cleanup;
102227     }
102228     for(j=0; j<pTab->nCol; j++){
102229       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
102230         if( j==pTab->iPKey ){
102231           chngRowid = 1;
102232           pRowidExpr = pChanges->a[i].pExpr;
102233         }
102234         aXRef[j] = i;
102235         break;
102236       }
102237     }
102238     if( j>=pTab->nCol ){
102239       if( sqlite3IsRowid(pChanges->a[i].zName) ){
102240         chngRowid = 1;
102241         pRowidExpr = pChanges->a[i].pExpr;
102242       }else{
102243         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
102244         pParse->checkSchema = 1;
102245         goto update_cleanup;
102246       }
102247     }
102248 #ifndef SQLITE_OMIT_AUTHORIZATION
102249     {
102250       int rc;
102251       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
102252                            pTab->aCol[j].zName, db->aDb[iDb].zName);
102253       if( rc==SQLITE_DENY ){
102254         goto update_cleanup;
102255       }else if( rc==SQLITE_IGNORE ){
102256         aXRef[j] = -1;
102257       }
102258     }
102259 #endif
102260   }
102261
102262   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
102263
102264   /* Allocate memory for the array aRegIdx[].  There is one entry in the
102265   ** array for each index associated with table being updated.  Fill in
102266   ** the value with a register number for indices that are to be used
102267   ** and with zero for unused indices.
102268   */
102269   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
102270   if( nIdx>0 ){
102271     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
102272     if( aRegIdx==0 ) goto update_cleanup;
102273   }
102274   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102275     int reg;
102276     if( hasFK || chngRowid ){
102277       reg = ++pParse->nMem;
102278     }else{
102279       reg = 0;
102280       for(i=0; i<pIdx->nColumn; i++){
102281         if( aXRef[pIdx->aiColumn[i]]>=0 ){
102282           reg = ++pParse->nMem;
102283           break;
102284         }
102285       }
102286     }
102287     aRegIdx[j] = reg;
102288   }
102289
102290   /* Begin generating code. */
102291   v = sqlite3GetVdbe(pParse);
102292   if( v==0 ) goto update_cleanup;
102293   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102294   sqlite3BeginWriteOperation(pParse, 1, iDb);
102295
102296 #ifndef SQLITE_OMIT_VIRTUALTABLE
102297   /* Virtual tables must be handled separately */
102298   if( IsVirtual(pTab) ){
102299     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
102300                        pWhere, onError);
102301     pWhere = 0;
102302     pTabList = 0;
102303     goto update_cleanup;
102304   }
102305 #endif
102306
102307   /* Allocate required registers. */
102308   regRowSet = ++pParse->nMem;
102309   regOldRowid = regNewRowid = ++pParse->nMem;
102310   if( pTrigger || hasFK ){
102311     regOld = pParse->nMem + 1;
102312     pParse->nMem += pTab->nCol;
102313   }
102314   if( chngRowid || pTrigger || hasFK ){
102315     regNewRowid = ++pParse->nMem;
102316   }
102317   regNew = pParse->nMem + 1;
102318   pParse->nMem += pTab->nCol;
102319
102320   /* Start the view context. */
102321   if( isView ){
102322     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
102323   }
102324
102325   /* If we are trying to update a view, realize that view into
102326   ** a ephemeral table.
102327   */
102328 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102329   if( isView ){
102330     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
102331   }
102332 #endif
102333
102334   /* Resolve the column names in all the expressions in the
102335   ** WHERE clause.
102336   */
102337   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102338     goto update_cleanup;
102339   }
102340
102341   /* Begin the database scan
102342   */
102343   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102344   pWInfo = sqlite3WhereBegin(
102345       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102346   );
102347   if( pWInfo==0 ) goto update_cleanup;
102348   okOnePass = pWInfo->okOnePass;
102349
102350   /* Remember the rowid of every item to be updated.
102351   */
102352   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102353   if( !okOnePass ){
102354     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
102355   }
102356
102357   /* End the database scan loop.
102358   */
102359   sqlite3WhereEnd(pWInfo);
102360
102361   /* Initialize the count of updated rows
102362   */
102363   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
102364     regRowCount = ++pParse->nMem;
102365     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
102366   }
102367
102368   if( !isView ){
102369     /*
102370     ** Open every index that needs updating.  Note that if any
102371     ** index could potentially invoke a REPLACE conflict resolution
102372     ** action, then we need to open all indices because we might need
102373     ** to be deleting some records.
102374     */
102375     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
102376     if( onError==OE_Replace ){
102377       openAll = 1;
102378     }else{
102379       openAll = 0;
102380       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102381         if( pIdx->onError==OE_Replace ){
102382           openAll = 1;
102383           break;
102384         }
102385       }
102386     }
102387     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102388       assert( aRegIdx );
102389       if( openAll || aRegIdx[i]>0 ){
102390         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
102391         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
102392                        (char*)pKey, P4_KEYINFO_HANDOFF);
102393         assert( pParse->nTab>iCur+i+1 );
102394       }
102395     }
102396   }
102397
102398   /* Top of the update loop */
102399   if( okOnePass ){
102400     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
102401     addr = sqlite3VdbeAddOp0(v, OP_Goto);
102402     sqlite3VdbeJumpHere(v, a1);
102403   }else{
102404     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
102405   }
102406
102407   /* Make cursor iCur point to the record that is being updated. If
102408   ** this record does not exist for some reason (deleted by a trigger,
102409   ** for example, then jump to the next iteration of the RowSet loop.  */
102410   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
102411
102412   /* If the record number will change, set register regNewRowid to
102413   ** contain the new value. If the record number is not being modified,
102414   ** then regNewRowid is the same register as regOldRowid, which is
102415   ** already populated.  */
102416   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
102417   if( chngRowid ){
102418     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
102419     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
102420   }
102421
102422   /* If there are triggers on this table, populate an array of registers
102423   ** with the required old.* column data.  */
102424   if( hasFK || pTrigger ){
102425     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
102426     oldmask |= sqlite3TriggerColmask(pParse,
102427         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
102428     );
102429     for(i=0; i<pTab->nCol; i++){
102430       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
102431         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
102432       }else{
102433         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
102434       }
102435     }
102436     if( chngRowid==0 ){
102437       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
102438     }
102439   }
102440
102441   /* Populate the array of registers beginning at regNew with the new
102442   ** row data. This array is used to check constaints, create the new
102443   ** table and index records, and as the values for any new.* references
102444   ** made by triggers.
102445   **
102446   ** If there are one or more BEFORE triggers, then do not populate the
102447   ** registers associated with columns that are (a) not modified by
102448   ** this UPDATE statement and (b) not accessed by new.* references. The
102449   ** values for registers not modified by the UPDATE must be reloaded from
102450   ** the database after the BEFORE triggers are fired anyway (as the trigger
102451   ** may have modified them). So not loading those that are not going to
102452   ** be used eliminates some redundant opcodes.
102453   */
102454   newmask = sqlite3TriggerColmask(
102455       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
102456   );
102457   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
102458   for(i=0; i<pTab->nCol; i++){
102459     if( i==pTab->iPKey ){
102460       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
102461     }else{
102462       j = aXRef[i];
102463       if( j>=0 ){
102464         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
102465       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
102466         /* This branch loads the value of a column that will not be changed
102467         ** into a register. This is done if there are no BEFORE triggers, or
102468         ** if there are one or more BEFORE triggers that use this value via
102469         ** a new.* reference in a trigger program.
102470         */
102471         testcase( i==31 );
102472         testcase( i==32 );
102473         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
102474         sqlite3ColumnDefault(v, pTab, i, regNew+i);
102475       }
102476     }
102477   }
102478
102479   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
102480   ** verified. One could argue that this is wrong.
102481   */
102482   if( tmask&TRIGGER_BEFORE ){
102483     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
102484     sqlite3TableAffinityStr(v, pTab);
102485     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
102486         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
102487
102488     /* The row-trigger may have deleted the row being updated. In this
102489     ** case, jump to the next row. No updates or AFTER triggers are
102490     ** required. This behaviour - what happens when the row being updated
102491     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
102492     ** documentation.
102493     */
102494     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
102495
102496     /* If it did not delete it, the row-trigger may still have modified
102497     ** some of the columns of the row being updated. Load the values for
102498     ** all columns not modified by the update statement into their
102499     ** registers in case this has happened.
102500     */
102501     for(i=0; i<pTab->nCol; i++){
102502       if( aXRef[i]<0 && i!=pTab->iPKey ){
102503         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
102504         sqlite3ColumnDefault(v, pTab, i, regNew+i);
102505       }
102506     }
102507   }
102508
102509   if( !isView ){
102510     int j1;                       /* Address of jump instruction */
102511
102512     /* Do constraint checks. */
102513     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
102514         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
102515
102516     /* Do FK constraint checks. */
102517     if( hasFK ){
102518       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
102519     }
102520
102521     /* Delete the index entries associated with the current record.  */
102522     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
102523     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
102524
102525     /* If changing the record number, delete the old record.  */
102526     if( hasFK || chngRowid ){
102527       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
102528     }
102529     sqlite3VdbeJumpHere(v, j1);
102530
102531     if( hasFK ){
102532       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
102533     }
102534
102535     /* Insert the new index entries and the new record. */
102536     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
102537
102538     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
102539     ** handle rows (possibly in other tables) that refer via a foreign key
102540     ** to the row just updated. */
102541     if( hasFK ){
102542       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
102543     }
102544   }
102545
102546   /* Increment the row counter
102547   */
102548   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
102549     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
102550   }
102551
102552   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
102553       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
102554
102555   /* Repeat the above with the next record to be updated, until
102556   ** all record selected by the WHERE clause have been updated.
102557   */
102558   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
102559   sqlite3VdbeJumpHere(v, addr);
102560
102561   /* Close all tables */
102562   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102563     assert( aRegIdx );
102564     if( openAll || aRegIdx[i]>0 ){
102565       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
102566     }
102567   }
102568   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
102569
102570   /* Update the sqlite_sequence table by storing the content of the
102571   ** maximum rowid counter values recorded while inserting into
102572   ** autoincrement tables.
102573   */
102574   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102575     sqlite3AutoincrementEnd(pParse);
102576   }
102577
102578   /*
102579   ** Return the number of rows that were changed. If this routine is
102580   ** generating code because of a call to sqlite3NestedParse(), do not
102581   ** invoke the callback function.
102582   */
102583   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
102584     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
102585     sqlite3VdbeSetNumCols(v, 1);
102586     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
102587   }
102588
102589 update_cleanup:
102590   sqlite3AuthContextPop(&sContext);
102591   sqlite3DbFree(db, aRegIdx);
102592   sqlite3DbFree(db, aXRef);
102593   sqlite3SrcListDelete(db, pTabList);
102594   sqlite3ExprListDelete(db, pChanges);
102595   sqlite3ExprDelete(db, pWhere);
102596   return;
102597 }
102598 /* Make sure "isView" and other macros defined above are undefined. Otherwise
102599 ** thely may interfere with compilation of other functions in this file
102600 ** (or in another file, if this file becomes part of the amalgamation).  */
102601 #ifdef isView
102602  #undef isView
102603 #endif
102604 #ifdef pTrigger
102605  #undef pTrigger
102606 #endif
102607
102608 #ifndef SQLITE_OMIT_VIRTUALTABLE
102609 /*
102610 ** Generate code for an UPDATE of a virtual table.
102611 **
102612 ** The strategy is that we create an ephemerial table that contains
102613 ** for each row to be changed:
102614 **
102615 **   (A)  The original rowid of that row.
102616 **   (B)  The revised rowid for the row. (note1)
102617 **   (C)  The content of every column in the row.
102618 **
102619 ** Then we loop over this ephemeral table and for each row in
102620 ** the ephermeral table call VUpdate.
102621 **
102622 ** When finished, drop the ephemeral table.
102623 **
102624 ** (note1) Actually, if we know in advance that (A) is always the same
102625 ** as (B) we only store (A), then duplicate (A) when pulling
102626 ** it out of the ephemeral table before calling VUpdate.
102627 */
102628 static void updateVirtualTable(
102629   Parse *pParse,       /* The parsing context */
102630   SrcList *pSrc,       /* The virtual table to be modified */
102631   Table *pTab,         /* The virtual table */
102632   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
102633   Expr *pRowid,        /* Expression used to recompute the rowid */
102634   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
102635   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
102636   int onError          /* ON CONFLICT strategy */
102637 ){
102638   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
102639   ExprList *pEList = 0;     /* The result set of the SELECT statement */
102640   Select *pSelect = 0;      /* The SELECT statement */
102641   Expr *pExpr;              /* Temporary expression */
102642   int ephemTab;             /* Table holding the result of the SELECT */
102643   int i;                    /* Loop counter */
102644   int addr;                 /* Address of top of loop */
102645   int iReg;                 /* First register in set passed to OP_VUpdate */
102646   sqlite3 *db = pParse->db; /* Database connection */
102647   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
102648   SelectDest dest;
102649
102650   /* Construct the SELECT statement that will find the new values for
102651   ** all updated rows.
102652   */
102653   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
102654   if( pRowid ){
102655     pEList = sqlite3ExprListAppend(pParse, pEList,
102656                                    sqlite3ExprDup(db, pRowid, 0));
102657   }
102658   assert( pTab->iPKey<0 );
102659   for(i=0; i<pTab->nCol; i++){
102660     if( aXRef[i]>=0 ){
102661       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
102662     }else{
102663       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
102664     }
102665     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
102666   }
102667   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
102668
102669   /* Create the ephemeral table into which the update results will
102670   ** be stored.
102671   */
102672   assert( v );
102673   ephemTab = pParse->nTab++;
102674   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
102675   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
102676
102677   /* fill the ephemeral table
102678   */
102679   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
102680   sqlite3Select(pParse, pSelect, &dest);
102681
102682   /* Generate code to scan the ephemeral table and call VUpdate. */
102683   iReg = ++pParse->nMem;
102684   pParse->nMem += pTab->nCol+1;
102685   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
102686   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
102687   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
102688   for(i=0; i<pTab->nCol; i++){
102689     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
102690   }
102691   sqlite3VtabMakeWritable(pParse, pTab);
102692   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
102693   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
102694   sqlite3MayAbort(pParse);
102695   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
102696   sqlite3VdbeJumpHere(v, addr);
102697   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
102698
102699   /* Cleanup */
102700   sqlite3SelectDelete(db, pSelect);
102701 }
102702 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102703
102704 /************** End of update.c **********************************************/
102705 /************** Begin file vacuum.c ******************************************/
102706 /*
102707 ** 2003 April 6
102708 **
102709 ** The author disclaims copyright to this source code.  In place of
102710 ** a legal notice, here is a blessing:
102711 **
102712 **    May you do good and not evil.
102713 **    May you find forgiveness for yourself and forgive others.
102714 **    May you share freely, never taking more than you give.
102715 **
102716 *************************************************************************
102717 ** This file contains code used to implement the VACUUM command.
102718 **
102719 ** Most of the code in this file may be omitted by defining the
102720 ** SQLITE_OMIT_VACUUM macro.
102721 */
102722
102723 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
102724 /*
102725 ** Finalize a prepared statement.  If there was an error, store the
102726 ** text of the error message in *pzErrMsg.  Return the result code.
102727 */
102728 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
102729   int rc;
102730   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
102731   if( rc ){
102732     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102733   }
102734   return rc;
102735 }
102736
102737 /*
102738 ** Execute zSql on database db. Return an error code.
102739 */
102740 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102741   sqlite3_stmt *pStmt;
102742   VVA_ONLY( int rc; )
102743   if( !zSql ){
102744     return SQLITE_NOMEM;
102745   }
102746   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
102747     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102748     return sqlite3_errcode(db);
102749   }
102750   VVA_ONLY( rc = ) sqlite3_step(pStmt);
102751   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
102752   return vacuumFinalize(db, pStmt, pzErrMsg);
102753 }
102754
102755 /*
102756 ** Execute zSql on database db. The statement returns exactly
102757 ** one column. Execute this as SQL on the same database.
102758 */
102759 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102760   sqlite3_stmt *pStmt;
102761   int rc;
102762
102763   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
102764   if( rc!=SQLITE_OK ) return rc;
102765
102766   while( SQLITE_ROW==sqlite3_step(pStmt) ){
102767     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
102768     if( rc!=SQLITE_OK ){
102769       vacuumFinalize(db, pStmt, pzErrMsg);
102770       return rc;
102771     }
102772   }
102773
102774   return vacuumFinalize(db, pStmt, pzErrMsg);
102775 }
102776
102777 /*
102778 ** The non-standard VACUUM command is used to clean up the database,
102779 ** collapse free space, etc.  It is modelled after the VACUUM command
102780 ** in PostgreSQL.
102781 **
102782 ** In version 1.0.x of SQLite, the VACUUM command would call
102783 ** gdbm_reorganize() on all the database tables.  But beginning
102784 ** with 2.0.0, SQLite no longer uses GDBM so this command has
102785 ** become a no-op.
102786 */
102787 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
102788   Vdbe *v = sqlite3GetVdbe(pParse);
102789   if( v ){
102790     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
102791     sqlite3VdbeUsesBtree(v, 0);
102792   }
102793   return;
102794 }
102795
102796 /*
102797 ** This routine implements the OP_Vacuum opcode of the VDBE.
102798 */
102799 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
102800   int rc = SQLITE_OK;     /* Return code from service routines */
102801   Btree *pMain;           /* The database being vacuumed */
102802   Btree *pTemp;           /* The temporary database we vacuum into */
102803   char *zSql = 0;         /* SQL statements */
102804   int saved_flags;        /* Saved value of the db->flags */
102805   int saved_nChange;      /* Saved value of db->nChange */
102806   int saved_nTotalChange; /* Saved value of db->nTotalChange */
102807   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
102808   Db *pDb = 0;            /* Database to detach at end of vacuum */
102809   int isMemDb;            /* True if vacuuming a :memory: database */
102810   int nRes;               /* Bytes of reserved space at the end of each page */
102811   int nDb;                /* Number of attached databases */
102812
102813   if( !db->autoCommit ){
102814     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
102815     return SQLITE_ERROR;
102816   }
102817   if( db->activeVdbeCnt>1 ){
102818     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
102819     return SQLITE_ERROR;
102820   }
102821
102822   /* Save the current value of the database flags so that it can be
102823   ** restored before returning. Then set the writable-schema flag, and
102824   ** disable CHECK and foreign key constraints.  */
102825   saved_flags = db->flags;
102826   saved_nChange = db->nChange;
102827   saved_nTotalChange = db->nTotalChange;
102828   saved_xTrace = db->xTrace;
102829   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
102830   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
102831   db->xTrace = 0;
102832
102833   pMain = db->aDb[0].pBt;
102834   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
102835
102836   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
102837   ** can be set to 'off' for this file, as it is not recovered if a crash
102838   ** occurs anyway. The integrity of the database is maintained by a
102839   ** (possibly synchronous) transaction opened on the main database before
102840   ** sqlite3BtreeCopyFile() is called.
102841   **
102842   ** An optimisation would be to use a non-journaled pager.
102843   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
102844   ** that actually made the VACUUM run slower.  Very little journalling
102845   ** actually occurs when doing a vacuum since the vacuum_db is initially
102846   ** empty.  Only the journal header is written.  Apparently it takes more
102847   ** time to parse and run the PRAGMA to turn journalling off than it does
102848   ** to write the journal header file.
102849   */
102850   nDb = db->nDb;
102851   if( sqlite3TempInMemory(db) ){
102852     zSql = "ATTACH ':memory:' AS vacuum_db;";
102853   }else{
102854     zSql = "ATTACH '' AS vacuum_db;";
102855   }
102856   rc = execSql(db, pzErrMsg, zSql);
102857   if( db->nDb>nDb ){
102858     pDb = &db->aDb[db->nDb-1];
102859     assert( strcmp(pDb->zName,"vacuum_db")==0 );
102860   }
102861   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102862   pTemp = db->aDb[db->nDb-1].pBt;
102863
102864   /* The call to execSql() to attach the temp database has left the file
102865   ** locked (as there was more than one active statement when the transaction
102866   ** to read the schema was concluded. Unlock it here so that this doesn't
102867   ** cause problems for the call to BtreeSetPageSize() below.  */
102868   sqlite3BtreeCommit(pTemp);
102869
102870   nRes = sqlite3BtreeGetReserve(pMain);
102871
102872   /* A VACUUM cannot change the pagesize of an encrypted database. */
102873 #ifdef SQLITE_HAS_CODEC
102874   if( db->nextPagesize ){
102875     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
102876     int nKey;
102877     char *zKey;
102878     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
102879     if( nKey ) db->nextPagesize = 0;
102880   }
102881 #endif
102882
102883   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
102884   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102885
102886   /* Begin a transaction and take an exclusive lock on the main database
102887   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
102888   ** to ensure that we do not try to change the page-size on a WAL database.
102889   */
102890   rc = execSql(db, pzErrMsg, "BEGIN;");
102891   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102892   rc = sqlite3BtreeBeginTrans(pMain, 2);
102893   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102894
102895   /* Do not attempt to change the page size for a WAL database */
102896   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
102897                                                ==PAGER_JOURNALMODE_WAL ){
102898     db->nextPagesize = 0;
102899   }
102900
102901   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
102902    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
102903    || NEVER(db->mallocFailed)
102904   ){
102905     rc = SQLITE_NOMEM;
102906     goto end_of_vacuum;
102907   }
102908
102909 #ifndef SQLITE_OMIT_AUTOVACUUM
102910   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
102911                                            sqlite3BtreeGetAutoVacuum(pMain));
102912 #endif
102913
102914   /* Query the schema of the main database. Create a mirror schema
102915   ** in the temporary database.
102916   */
102917   rc = execExecSql(db, pzErrMsg,
102918       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
102919       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
102920       "   AND rootpage>0"
102921   );
102922   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102923   rc = execExecSql(db, pzErrMsg,
102924       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
102925       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
102926   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102927   rc = execExecSql(db, pzErrMsg,
102928       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
102929       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
102930   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102931
102932   /* Loop through the tables in the main database. For each, do
102933   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
102934   ** the contents to the temporary database.
102935   */
102936   rc = execExecSql(db, pzErrMsg,
102937       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
102938       "|| ' SELECT * FROM main.' || quote(name) || ';'"
102939       "FROM main.sqlite_master "
102940       "WHERE type = 'table' AND name!='sqlite_sequence' "
102941       "  AND rootpage>0"
102942   );
102943   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102944
102945   /* Copy over the sequence table
102946   */
102947   rc = execExecSql(db, pzErrMsg,
102948       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
102949       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
102950   );
102951   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102952   rc = execExecSql(db, pzErrMsg,
102953       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
102954       "|| ' SELECT * FROM main.' || quote(name) || ';' "
102955       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
102956   );
102957   if( rc!=SQLITE_OK ) goto end_of_vacuum;
102958
102959
102960   /* Copy the triggers, views, and virtual tables from the main database
102961   ** over to the temporary database.  None of these objects has any
102962   ** associated storage, so all we have to do is copy their entries
102963   ** from the SQLITE_MASTER table.
102964   */
102965   rc = execSql(db, pzErrMsg,
102966       "INSERT INTO vacuum_db.sqlite_master "
102967       "  SELECT type, name, tbl_name, rootpage, sql"
102968       "    FROM main.sqlite_master"
102969       "   WHERE type='view' OR type='trigger'"
102970       "      OR (type='table' AND rootpage=0)"
102971   );
102972   if( rc ) goto end_of_vacuum;
102973
102974   /* At this point, there is a write transaction open on both the
102975   ** vacuum database and the main database. Assuming no error occurs,
102976   ** both transactions are closed by this block - the main database
102977   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
102978   ** call to sqlite3BtreeCommit().
102979   */
102980   {
102981     u32 meta;
102982     int i;
102983
102984     /* This array determines which meta meta values are preserved in the
102985     ** vacuum.  Even entries are the meta value number and odd entries
102986     ** are an increment to apply to the meta value after the vacuum.
102987     ** The increment is used to increase the schema cookie so that other
102988     ** connections to the same database will know to reread the schema.
102989     */
102990     static const unsigned char aCopy[] = {
102991        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
102992        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
102993        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
102994        BTREE_USER_VERSION,       0,  /* Preserve the user version */
102995     };
102996
102997     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
102998     assert( 1==sqlite3BtreeIsInTrans(pMain) );
102999
103000     /* Copy Btree meta values */
103001     for(i=0; i<ArraySize(aCopy); i+=2){
103002       /* GetMeta() and UpdateMeta() cannot fail in this context because
103003       ** we already have page 1 loaded into cache and marked dirty. */
103004       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
103005       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
103006       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
103007     }
103008
103009     rc = sqlite3BtreeCopyFile(pMain, pTemp);
103010     if( rc!=SQLITE_OK ) goto end_of_vacuum;
103011     rc = sqlite3BtreeCommit(pTemp);
103012     if( rc!=SQLITE_OK ) goto end_of_vacuum;
103013 #ifndef SQLITE_OMIT_AUTOVACUUM
103014     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
103015 #endif
103016   }
103017
103018   assert( rc==SQLITE_OK );
103019   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
103020
103021 end_of_vacuum:
103022   /* Restore the original value of db->flags */
103023   db->flags = saved_flags;
103024   db->nChange = saved_nChange;
103025   db->nTotalChange = saved_nTotalChange;
103026   db->xTrace = saved_xTrace;
103027   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
103028
103029   /* Currently there is an SQL level transaction open on the vacuum
103030   ** database. No locks are held on any other files (since the main file
103031   ** was committed at the btree level). So it safe to end the transaction
103032   ** by manually setting the autoCommit flag to true and detaching the
103033   ** vacuum database. The vacuum_db journal file is deleted when the pager
103034   ** is closed by the DETACH.
103035   */
103036   db->autoCommit = 1;
103037
103038   if( pDb ){
103039     sqlite3BtreeClose(pDb->pBt);
103040     pDb->pBt = 0;
103041     pDb->pSchema = 0;
103042   }
103043
103044   /* This both clears the schemas and reduces the size of the db->aDb[]
103045   ** array. */
103046   sqlite3ResetAllSchemasOfConnection(db);
103047
103048   return rc;
103049 }
103050
103051 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
103052
103053 /************** End of vacuum.c **********************************************/
103054 /************** Begin file vtab.c ********************************************/
103055 /*
103056 ** 2006 June 10
103057 **
103058 ** The author disclaims copyright to this source code.  In place of
103059 ** a legal notice, here is a blessing:
103060 **
103061 **    May you do good and not evil.
103062 **    May you find forgiveness for yourself and forgive others.
103063 **    May you share freely, never taking more than you give.
103064 **
103065 *************************************************************************
103066 ** This file contains code used to help implement virtual tables.
103067 */
103068 #ifndef SQLITE_OMIT_VIRTUALTABLE
103069
103070 /*
103071 ** Before a virtual table xCreate() or xConnect() method is invoked, the
103072 ** sqlite3.pVtabCtx member variable is set to point to an instance of
103073 ** this struct allocated on the stack. It is used by the implementation of
103074 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
103075 ** are invoked only from within xCreate and xConnect methods.
103076 */
103077 struct VtabCtx {
103078   VTable *pVTable;    /* The virtual table being constructed */
103079   Table *pTab;        /* The Table object to which the virtual table belongs */
103080 };
103081
103082 /*
103083 ** The actual function that does the work of creating a new module.
103084 ** This function implements the sqlite3_create_module() and
103085 ** sqlite3_create_module_v2() interfaces.
103086 */
103087 static int createModule(
103088   sqlite3 *db,                    /* Database in which module is registered */
103089   const char *zName,              /* Name assigned to this module */
103090   const sqlite3_module *pModule,  /* The definition of the module */
103091   void *pAux,                     /* Context pointer for xCreate/xConnect */
103092   void (*xDestroy)(void *)        /* Module destructor function */
103093 ){
103094   int rc = SQLITE_OK;
103095   int nName;
103096
103097   sqlite3_mutex_enter(db->mutex);
103098   nName = sqlite3Strlen30(zName);
103099   if( sqlite3HashFind(&db->aModule, zName, nName) ){
103100     rc = SQLITE_MISUSE_BKPT;
103101   }else{
103102     Module *pMod;
103103     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
103104     if( pMod ){
103105       Module *pDel;
103106       char *zCopy = (char *)(&pMod[1]);
103107       memcpy(zCopy, zName, nName+1);
103108       pMod->zName = zCopy;
103109       pMod->pModule = pModule;
103110       pMod->pAux = pAux;
103111       pMod->xDestroy = xDestroy;
103112       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
103113       assert( pDel==0 || pDel==pMod );
103114       if( pDel ){
103115         db->mallocFailed = 1;
103116         sqlite3DbFree(db, pDel);
103117       }
103118     }
103119   }
103120   rc = sqlite3ApiExit(db, rc);
103121   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
103122
103123   sqlite3_mutex_leave(db->mutex);
103124   return rc;
103125 }
103126
103127
103128 /*
103129 ** External API function used to create a new virtual-table module.
103130 */
103131 SQLITE_API int sqlite3_create_module(
103132   sqlite3 *db,                    /* Database in which module is registered */
103133   const char *zName,              /* Name assigned to this module */
103134   const sqlite3_module *pModule,  /* The definition of the module */
103135   void *pAux                      /* Context pointer for xCreate/xConnect */
103136 ){
103137   return createModule(db, zName, pModule, pAux, 0);
103138 }
103139
103140 /*
103141 ** External API function used to create a new virtual-table module.
103142 */
103143 SQLITE_API int sqlite3_create_module_v2(
103144   sqlite3 *db,                    /* Database in which module is registered */
103145   const char *zName,              /* Name assigned to this module */
103146   const sqlite3_module *pModule,  /* The definition of the module */
103147   void *pAux,                     /* Context pointer for xCreate/xConnect */
103148   void (*xDestroy)(void *)        /* Module destructor function */
103149 ){
103150   return createModule(db, zName, pModule, pAux, xDestroy);
103151 }
103152
103153 /*
103154 ** Lock the virtual table so that it cannot be disconnected.
103155 ** Locks nest.  Every lock should have a corresponding unlock.
103156 ** If an unlock is omitted, resources leaks will occur.
103157 **
103158 ** If a disconnect is attempted while a virtual table is locked,
103159 ** the disconnect is deferred until all locks have been removed.
103160 */
103161 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
103162   pVTab->nRef++;
103163 }
103164
103165
103166 /*
103167 ** pTab is a pointer to a Table structure representing a virtual-table.
103168 ** Return a pointer to the VTable object used by connection db to access
103169 ** this virtual-table, if one has been created, or NULL otherwise.
103170 */
103171 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
103172   VTable *pVtab;
103173   assert( IsVirtual(pTab) );
103174   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
103175   return pVtab;
103176 }
103177
103178 /*
103179 ** Decrement the ref-count on a virtual table object. When the ref-count
103180 ** reaches zero, call the xDisconnect() method to delete the object.
103181 */
103182 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
103183   sqlite3 *db = pVTab->db;
103184
103185   assert( db );
103186   assert( pVTab->nRef>0 );
103187   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
103188
103189   pVTab->nRef--;
103190   if( pVTab->nRef==0 ){
103191     sqlite3_vtab *p = pVTab->pVtab;
103192     if( p ){
103193       p->pModule->xDisconnect(p);
103194     }
103195     sqlite3DbFree(db, pVTab);
103196   }
103197 }
103198
103199 /*
103200 ** Table p is a virtual table. This function moves all elements in the
103201 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
103202 ** database connections to be disconnected at the next opportunity.
103203 ** Except, if argument db is not NULL, then the entry associated with
103204 ** connection db is left in the p->pVTable list.
103205 */
103206 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
103207   VTable *pRet = 0;
103208   VTable *pVTable = p->pVTable;
103209   p->pVTable = 0;
103210
103211   /* Assert that the mutex (if any) associated with the BtShared database
103212   ** that contains table p is held by the caller. See header comments
103213   ** above function sqlite3VtabUnlockList() for an explanation of why
103214   ** this makes it safe to access the sqlite3.pDisconnect list of any
103215   ** database connection that may have an entry in the p->pVTable list.
103216   */
103217   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
103218
103219   while( pVTable ){
103220     sqlite3 *db2 = pVTable->db;
103221     VTable *pNext = pVTable->pNext;
103222     assert( db2 );
103223     if( db2==db ){
103224       pRet = pVTable;
103225       p->pVTable = pRet;
103226       pRet->pNext = 0;
103227     }else{
103228       pVTable->pNext = db2->pDisconnect;
103229       db2->pDisconnect = pVTable;
103230     }
103231     pVTable = pNext;
103232   }
103233
103234   assert( !db || pRet );
103235   return pRet;
103236 }
103237
103238 /*
103239 ** Table *p is a virtual table. This function removes the VTable object
103240 ** for table *p associated with database connection db from the linked
103241 ** list in p->pVTab. It also decrements the VTable ref count. This is
103242 ** used when closing database connection db to free all of its VTable
103243 ** objects without disturbing the rest of the Schema object (which may
103244 ** be being used by other shared-cache connections).
103245 */
103246 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
103247   VTable **ppVTab;
103248
103249   assert( IsVirtual(p) );
103250   assert( sqlite3BtreeHoldsAllMutexes(db) );
103251   assert( sqlite3_mutex_held(db->mutex) );
103252
103253   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
103254     if( (*ppVTab)->db==db  ){
103255       VTable *pVTab = *ppVTab;
103256       *ppVTab = pVTab->pNext;
103257       sqlite3VtabUnlock(pVTab);
103258       break;
103259     }
103260   }
103261 }
103262
103263
103264 /*
103265 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
103266 **
103267 ** This function may only be called when the mutexes associated with all
103268 ** shared b-tree databases opened using connection db are held by the
103269 ** caller. This is done to protect the sqlite3.pDisconnect list. The
103270 ** sqlite3.pDisconnect list is accessed only as follows:
103271 **
103272 **   1) By this function. In this case, all BtShared mutexes and the mutex
103273 **      associated with the database handle itself must be held.
103274 **
103275 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
103276 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
103277 **      associated with the database the virtual table is stored in is held
103278 **      or, if the virtual table is stored in a non-sharable database, then
103279 **      the database handle mutex is held.
103280 **
103281 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
103282 ** by multiple threads. It is thread-safe.
103283 */
103284 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
103285   VTable *p = db->pDisconnect;
103286   db->pDisconnect = 0;
103287
103288   assert( sqlite3BtreeHoldsAllMutexes(db) );
103289   assert( sqlite3_mutex_held(db->mutex) );
103290
103291   if( p ){
103292     sqlite3ExpirePreparedStatements(db);
103293     do {
103294       VTable *pNext = p->pNext;
103295       sqlite3VtabUnlock(p);
103296       p = pNext;
103297     }while( p );
103298   }
103299 }
103300
103301 /*
103302 ** Clear any and all virtual-table information from the Table record.
103303 ** This routine is called, for example, just before deleting the Table
103304 ** record.
103305 **
103306 ** Since it is a virtual-table, the Table structure contains a pointer
103307 ** to the head of a linked list of VTable structures. Each VTable
103308 ** structure is associated with a single sqlite3* user of the schema.
103309 ** The reference count of the VTable structure associated with database
103310 ** connection db is decremented immediately (which may lead to the
103311 ** structure being xDisconnected and free). Any other VTable structures
103312 ** in the list are moved to the sqlite3.pDisconnect list of the associated
103313 ** database connection.
103314 */
103315 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
103316   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
103317   if( p->azModuleArg ){
103318     int i;
103319     for(i=0; i<p->nModuleArg; i++){
103320       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
103321     }
103322     sqlite3DbFree(db, p->azModuleArg);
103323   }
103324 }
103325
103326 /*
103327 ** Add a new module argument to pTable->azModuleArg[].
103328 ** The string is not copied - the pointer is stored.  The
103329 ** string will be freed automatically when the table is
103330 ** deleted.
103331 */
103332 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
103333   int i = pTable->nModuleArg++;
103334   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
103335   char **azModuleArg;
103336   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
103337   if( azModuleArg==0 ){
103338     int j;
103339     for(j=0; j<i; j++){
103340       sqlite3DbFree(db, pTable->azModuleArg[j]);
103341     }
103342     sqlite3DbFree(db, zArg);
103343     sqlite3DbFree(db, pTable->azModuleArg);
103344     pTable->nModuleArg = 0;
103345   }else{
103346     azModuleArg[i] = zArg;
103347     azModuleArg[i+1] = 0;
103348   }
103349   pTable->azModuleArg = azModuleArg;
103350 }
103351
103352 /*
103353 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
103354 ** statement.  The module name has been parsed, but the optional list
103355 ** of parameters that follow the module name are still pending.
103356 */
103357 SQLITE_PRIVATE void sqlite3VtabBeginParse(
103358   Parse *pParse,        /* Parsing context */
103359   Token *pName1,        /* Name of new table, or database name */
103360   Token *pName2,        /* Name of new table or NULL */
103361   Token *pModuleName,   /* Name of the module for the virtual table */
103362   int ifNotExists       /* No error if the table already exists */
103363 ){
103364   int iDb;              /* The database the table is being created in */
103365   Table *pTable;        /* The new virtual table */
103366   sqlite3 *db;          /* Database connection */
103367
103368   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
103369   pTable = pParse->pNewTable;
103370   if( pTable==0 ) return;
103371   assert( 0==pTable->pIndex );
103372
103373   db = pParse->db;
103374   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
103375   assert( iDb>=0 );
103376
103377   pTable->tabFlags |= TF_Virtual;
103378   pTable->nModuleArg = 0;
103379   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
103380   addModuleArgument(db, pTable, 0);
103381   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
103382   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
103383
103384 #ifndef SQLITE_OMIT_AUTHORIZATION
103385   /* Creating a virtual table invokes the authorization callback twice.
103386   ** The first invocation, to obtain permission to INSERT a row into the
103387   ** sqlite_master table, has already been made by sqlite3StartTable().
103388   ** The second call, to obtain permission to create the table, is made now.
103389   */
103390   if( pTable->azModuleArg ){
103391     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
103392             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
103393   }
103394 #endif
103395 }
103396
103397 /*
103398 ** This routine takes the module argument that has been accumulating
103399 ** in pParse->zArg[] and appends it to the list of arguments on the
103400 ** virtual table currently under construction in pParse->pTable.
103401 */
103402 static void addArgumentToVtab(Parse *pParse){
103403   if( pParse->sArg.z && pParse->pNewTable ){
103404     const char *z = (const char*)pParse->sArg.z;
103405     int n = pParse->sArg.n;
103406     sqlite3 *db = pParse->db;
103407     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
103408   }
103409 }
103410
103411 /*
103412 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
103413 ** has been completely parsed.
103414 */
103415 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
103416   Table *pTab = pParse->pNewTable;  /* The table being constructed */
103417   sqlite3 *db = pParse->db;         /* The database connection */
103418
103419   if( pTab==0 ) return;
103420   addArgumentToVtab(pParse);
103421   pParse->sArg.z = 0;
103422   if( pTab->nModuleArg<1 ) return;
103423
103424   /* If the CREATE VIRTUAL TABLE statement is being entered for the
103425   ** first time (in other words if the virtual table is actually being
103426   ** created now instead of just being read out of sqlite_master) then
103427   ** do additional initialization work and store the statement text
103428   ** in the sqlite_master table.
103429   */
103430   if( !db->init.busy ){
103431     char *zStmt;
103432     char *zWhere;
103433     int iDb;
103434     Vdbe *v;
103435
103436     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
103437     if( pEnd ){
103438       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
103439     }
103440     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
103441
103442     /* A slot for the record has already been allocated in the
103443     ** SQLITE_MASTER table.  We just need to update that slot with all
103444     ** the information we've collected.
103445     **
103446     ** The VM register number pParse->regRowid holds the rowid of an
103447     ** entry in the sqlite_master table tht was created for this vtab
103448     ** by sqlite3StartTable().
103449     */
103450     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103451     sqlite3NestedParse(pParse,
103452       "UPDATE %Q.%s "
103453          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
103454        "WHERE rowid=#%d",
103455       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
103456       pTab->zName,
103457       pTab->zName,
103458       zStmt,
103459       pParse->regRowid
103460     );
103461     sqlite3DbFree(db, zStmt);
103462     v = sqlite3GetVdbe(pParse);
103463     sqlite3ChangeCookie(pParse, iDb);
103464
103465     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
103466     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
103467     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
103468     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
103469                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
103470   }
103471
103472   /* If we are rereading the sqlite_master table create the in-memory
103473   ** record of the table. The xConnect() method is not called until
103474   ** the first time the virtual table is used in an SQL statement. This
103475   ** allows a schema that contains virtual tables to be loaded before
103476   ** the required virtual table implementations are registered.  */
103477   else {
103478     Table *pOld;
103479     Schema *pSchema = pTab->pSchema;
103480     const char *zName = pTab->zName;
103481     int nName = sqlite3Strlen30(zName);
103482     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
103483     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
103484     if( pOld ){
103485       db->mallocFailed = 1;
103486       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
103487       return;
103488     }
103489     pParse->pNewTable = 0;
103490   }
103491 }
103492
103493 /*
103494 ** The parser calls this routine when it sees the first token
103495 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
103496 */
103497 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
103498   addArgumentToVtab(pParse);
103499   pParse->sArg.z = 0;
103500   pParse->sArg.n = 0;
103501 }
103502
103503 /*
103504 ** The parser calls this routine for each token after the first token
103505 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
103506 */
103507 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
103508   Token *pArg = &pParse->sArg;
103509   if( pArg->z==0 ){
103510     pArg->z = p->z;
103511     pArg->n = p->n;
103512   }else{
103513     assert(pArg->z < p->z);
103514     pArg->n = (int)(&p->z[p->n] - pArg->z);
103515   }
103516 }
103517
103518 /*
103519 ** Invoke a virtual table constructor (either xCreate or xConnect). The
103520 ** pointer to the function to invoke is passed as the fourth parameter
103521 ** to this procedure.
103522 */
103523 static int vtabCallConstructor(
103524   sqlite3 *db,
103525   Table *pTab,
103526   Module *pMod,
103527   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
103528   char **pzErr
103529 ){
103530   VtabCtx sCtx, *pPriorCtx;
103531   VTable *pVTable;
103532   int rc;
103533   const char *const*azArg = (const char *const*)pTab->azModuleArg;
103534   int nArg = pTab->nModuleArg;
103535   char *zErr = 0;
103536   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
103537   int iDb;
103538
103539   if( !zModuleName ){
103540     return SQLITE_NOMEM;
103541   }
103542
103543   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
103544   if( !pVTable ){
103545     sqlite3DbFree(db, zModuleName);
103546     return SQLITE_NOMEM;
103547   }
103548   pVTable->db = db;
103549   pVTable->pMod = pMod;
103550
103551   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103552   pTab->azModuleArg[1] = db->aDb[iDb].zName;
103553
103554   /* Invoke the virtual table constructor */
103555   assert( &db->pVtabCtx );
103556   assert( xConstruct );
103557   sCtx.pTab = pTab;
103558   sCtx.pVTable = pVTable;
103559   pPriorCtx = db->pVtabCtx;
103560   db->pVtabCtx = &sCtx;
103561   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
103562   db->pVtabCtx = pPriorCtx;
103563   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
103564
103565   if( SQLITE_OK!=rc ){
103566     if( zErr==0 ){
103567       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
103568     }else {
103569       *pzErr = sqlite3MPrintf(db, "%s", zErr);
103570       sqlite3_free(zErr);
103571     }
103572     sqlite3DbFree(db, pVTable);
103573   }else if( ALWAYS(pVTable->pVtab) ){
103574     /* Justification of ALWAYS():  A correct vtab constructor must allocate
103575     ** the sqlite3_vtab object if successful.  */
103576     pVTable->pVtab->pModule = pMod->pModule;
103577     pVTable->nRef = 1;
103578     if( sCtx.pTab ){
103579       const char *zFormat = "vtable constructor did not declare schema: %s";
103580       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
103581       sqlite3VtabUnlock(pVTable);
103582       rc = SQLITE_ERROR;
103583     }else{
103584       int iCol;
103585       /* If everything went according to plan, link the new VTable structure
103586       ** into the linked list headed by pTab->pVTable. Then loop through the
103587       ** columns of the table to see if any of them contain the token "hidden".
103588       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
103589       ** the type string.  */
103590       pVTable->pNext = pTab->pVTable;
103591       pTab->pVTable = pVTable;
103592
103593       for(iCol=0; iCol<pTab->nCol; iCol++){
103594         char *zType = pTab->aCol[iCol].zType;
103595         int nType;
103596         int i = 0;
103597         if( !zType ) continue;
103598         nType = sqlite3Strlen30(zType);
103599         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
103600           for(i=0; i<nType; i++){
103601             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
103602              && (zType[i+7]=='\0' || zType[i+7]==' ')
103603             ){
103604               i++;
103605               break;
103606             }
103607           }
103608         }
103609         if( i<nType ){
103610           int j;
103611           int nDel = 6 + (zType[i+6] ? 1 : 0);
103612           for(j=i; (j+nDel)<=nType; j++){
103613             zType[j] = zType[j+nDel];
103614           }
103615           if( zType[i]=='\0' && i>0 ){
103616             assert(zType[i-1]==' ');
103617             zType[i-1] = '\0';
103618           }
103619           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
103620         }
103621       }
103622     }
103623   }
103624
103625   sqlite3DbFree(db, zModuleName);
103626   return rc;
103627 }
103628
103629 /*
103630 ** This function is invoked by the parser to call the xConnect() method
103631 ** of the virtual table pTab. If an error occurs, an error code is returned
103632 ** and an error left in pParse.
103633 **
103634 ** This call is a no-op if table pTab is not a virtual table.
103635 */
103636 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
103637   sqlite3 *db = pParse->db;
103638   const char *zMod;
103639   Module *pMod;
103640   int rc;
103641
103642   assert( pTab );
103643   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
103644     return SQLITE_OK;
103645   }
103646
103647   /* Locate the required virtual table module */
103648   zMod = pTab->azModuleArg[0];
103649   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103650
103651   if( !pMod ){
103652     const char *zModule = pTab->azModuleArg[0];
103653     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
103654     rc = SQLITE_ERROR;
103655   }else{
103656     char *zErr = 0;
103657     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
103658     if( rc!=SQLITE_OK ){
103659       sqlite3ErrorMsg(pParse, "%s", zErr);
103660     }
103661     sqlite3DbFree(db, zErr);
103662   }
103663
103664   return rc;
103665 }
103666 /*
103667 ** Grow the db->aVTrans[] array so that there is room for at least one
103668 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
103669 */
103670 static int growVTrans(sqlite3 *db){
103671   const int ARRAY_INCR = 5;
103672
103673   /* Grow the sqlite3.aVTrans array if required */
103674   if( (db->nVTrans%ARRAY_INCR)==0 ){
103675     VTable **aVTrans;
103676     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
103677     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
103678     if( !aVTrans ){
103679       return SQLITE_NOMEM;
103680     }
103681     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
103682     db->aVTrans = aVTrans;
103683   }
103684
103685   return SQLITE_OK;
103686 }
103687
103688 /*
103689 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
103690 ** have already been reserved using growVTrans().
103691 */
103692 static void addToVTrans(sqlite3 *db, VTable *pVTab){
103693   /* Add pVtab to the end of sqlite3.aVTrans */
103694   db->aVTrans[db->nVTrans++] = pVTab;
103695   sqlite3VtabLock(pVTab);
103696 }
103697
103698 /*
103699 ** This function is invoked by the vdbe to call the xCreate method
103700 ** of the virtual table named zTab in database iDb.
103701 **
103702 ** If an error occurs, *pzErr is set to point an an English language
103703 ** description of the error and an SQLITE_XXX error code is returned.
103704 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
103705 */
103706 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
103707   int rc = SQLITE_OK;
103708   Table *pTab;
103709   Module *pMod;
103710   const char *zMod;
103711
103712   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
103713   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
103714
103715   /* Locate the required virtual table module */
103716   zMod = pTab->azModuleArg[0];
103717   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103718
103719   /* If the module has been registered and includes a Create method,
103720   ** invoke it now. If the module has not been registered, return an
103721   ** error. Otherwise, do nothing.
103722   */
103723   if( !pMod ){
103724     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
103725     rc = SQLITE_ERROR;
103726   }else{
103727     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
103728   }
103729
103730   /* Justification of ALWAYS():  The xConstructor method is required to
103731   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
103732   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
103733     rc = growVTrans(db);
103734     if( rc==SQLITE_OK ){
103735       addToVTrans(db, sqlite3GetVTable(db, pTab));
103736     }
103737   }
103738
103739   return rc;
103740 }
103741
103742 /*
103743 ** This function is used to set the schema of a virtual table.  It is only
103744 ** valid to call this function from within the xCreate() or xConnect() of a
103745 ** virtual table module.
103746 */
103747 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
103748   Parse *pParse;
103749
103750   int rc = SQLITE_OK;
103751   Table *pTab;
103752   char *zErr = 0;
103753
103754   sqlite3_mutex_enter(db->mutex);
103755   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
103756     sqlite3Error(db, SQLITE_MISUSE, 0);
103757     sqlite3_mutex_leave(db->mutex);
103758     return SQLITE_MISUSE_BKPT;
103759   }
103760   assert( (pTab->tabFlags & TF_Virtual)!=0 );
103761
103762   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
103763   if( pParse==0 ){
103764     rc = SQLITE_NOMEM;
103765   }else{
103766     pParse->declareVtab = 1;
103767     pParse->db = db;
103768     pParse->nQueryLoop = 1;
103769
103770     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
103771      && pParse->pNewTable
103772      && !db->mallocFailed
103773      && !pParse->pNewTable->pSelect
103774      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
103775     ){
103776       if( !pTab->aCol ){
103777         pTab->aCol = pParse->pNewTable->aCol;
103778         pTab->nCol = pParse->pNewTable->nCol;
103779         pParse->pNewTable->nCol = 0;
103780         pParse->pNewTable->aCol = 0;
103781       }
103782       db->pVtabCtx->pTab = 0;
103783     }else{
103784       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
103785       sqlite3DbFree(db, zErr);
103786       rc = SQLITE_ERROR;
103787     }
103788     pParse->declareVtab = 0;
103789
103790     if( pParse->pVdbe ){
103791       sqlite3VdbeFinalize(pParse->pVdbe);
103792     }
103793     sqlite3DeleteTable(db, pParse->pNewTable);
103794     sqlite3StackFree(db, pParse);
103795   }
103796
103797   assert( (rc&0xff)==rc );
103798   rc = sqlite3ApiExit(db, rc);
103799   sqlite3_mutex_leave(db->mutex);
103800   return rc;
103801 }
103802
103803 /*
103804 ** This function is invoked by the vdbe to call the xDestroy method
103805 ** of the virtual table named zTab in database iDb. This occurs
103806 ** when a DROP TABLE is mentioned.
103807 **
103808 ** This call is a no-op if zTab is not a virtual table.
103809 */
103810 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
103811   int rc = SQLITE_OK;
103812   Table *pTab;
103813
103814   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
103815   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
103816     VTable *p = vtabDisconnectAll(db, pTab);
103817
103818     assert( rc==SQLITE_OK );
103819     rc = p->pMod->pModule->xDestroy(p->pVtab);
103820
103821     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
103822     if( rc==SQLITE_OK ){
103823       assert( pTab->pVTable==p && p->pNext==0 );
103824       p->pVtab = 0;
103825       pTab->pVTable = 0;
103826       sqlite3VtabUnlock(p);
103827     }
103828   }
103829
103830   return rc;
103831 }
103832
103833 /*
103834 ** This function invokes either the xRollback or xCommit method
103835 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
103836 ** called is identified by the second argument, "offset", which is
103837 ** the offset of the method to call in the sqlite3_module structure.
103838 **
103839 ** The array is cleared after invoking the callbacks.
103840 */
103841 static void callFinaliser(sqlite3 *db, int offset){
103842   int i;
103843   if( db->aVTrans ){
103844     for(i=0; i<db->nVTrans; i++){
103845       VTable *pVTab = db->aVTrans[i];
103846       sqlite3_vtab *p = pVTab->pVtab;
103847       if( p ){
103848         int (*x)(sqlite3_vtab *);
103849         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
103850         if( x ) x(p);
103851       }
103852       pVTab->iSavepoint = 0;
103853       sqlite3VtabUnlock(pVTab);
103854     }
103855     sqlite3DbFree(db, db->aVTrans);
103856     db->nVTrans = 0;
103857     db->aVTrans = 0;
103858   }
103859 }
103860
103861 /*
103862 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
103863 ** array. Return the error code for the first error that occurs, or
103864 ** SQLITE_OK if all xSync operations are successful.
103865 **
103866 ** Set *pzErrmsg to point to a buffer that should be released using
103867 ** sqlite3DbFree() containing an error message, if one is available.
103868 */
103869 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
103870   int i;
103871   int rc = SQLITE_OK;
103872   VTable **aVTrans = db->aVTrans;
103873
103874   db->aVTrans = 0;
103875   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
103876     int (*x)(sqlite3_vtab *);
103877     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
103878     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
103879       rc = x(pVtab);
103880       sqlite3DbFree(db, *pzErrmsg);
103881       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
103882       sqlite3_free(pVtab->zErrMsg);
103883     }
103884   }
103885   db->aVTrans = aVTrans;
103886   return rc;
103887 }
103888
103889 /*
103890 ** Invoke the xRollback method of all virtual tables in the
103891 ** sqlite3.aVTrans array. Then clear the array itself.
103892 */
103893 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
103894   callFinaliser(db, offsetof(sqlite3_module,xRollback));
103895   return SQLITE_OK;
103896 }
103897
103898 /*
103899 ** Invoke the xCommit method of all virtual tables in the
103900 ** sqlite3.aVTrans array. Then clear the array itself.
103901 */
103902 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
103903   callFinaliser(db, offsetof(sqlite3_module,xCommit));
103904   return SQLITE_OK;
103905 }
103906
103907 /*
103908 ** If the virtual table pVtab supports the transaction interface
103909 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
103910 ** not currently open, invoke the xBegin method now.
103911 **
103912 ** If the xBegin call is successful, place the sqlite3_vtab pointer
103913 ** in the sqlite3.aVTrans array.
103914 */
103915 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
103916   int rc = SQLITE_OK;
103917   const sqlite3_module *pModule;
103918
103919   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
103920   ** than zero, then this function is being called from within a
103921   ** virtual module xSync() callback. It is illegal to write to
103922   ** virtual module tables in this case, so return SQLITE_LOCKED.
103923   */
103924   if( sqlite3VtabInSync(db) ){
103925     return SQLITE_LOCKED;
103926   }
103927   if( !pVTab ){
103928     return SQLITE_OK;
103929   }
103930   pModule = pVTab->pVtab->pModule;
103931
103932   if( pModule->xBegin ){
103933     int i;
103934
103935     /* If pVtab is already in the aVTrans array, return early */
103936     for(i=0; i<db->nVTrans; i++){
103937       if( db->aVTrans[i]==pVTab ){
103938         return SQLITE_OK;
103939       }
103940     }
103941
103942     /* Invoke the xBegin method. If successful, add the vtab to the
103943     ** sqlite3.aVTrans[] array. */
103944     rc = growVTrans(db);
103945     if( rc==SQLITE_OK ){
103946       rc = pModule->xBegin(pVTab->pVtab);
103947       if( rc==SQLITE_OK ){
103948         addToVTrans(db, pVTab);
103949       }
103950     }
103951   }
103952   return rc;
103953 }
103954
103955 /*
103956 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
103957 ** virtual tables that currently have an open transaction. Pass iSavepoint
103958 ** as the second argument to the virtual table method invoked.
103959 **
103960 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
103961 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
103962 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
103963 ** an open transaction is invoked.
103964 **
103965 ** If any virtual table method returns an error code other than SQLITE_OK,
103966 ** processing is abandoned and the error returned to the caller of this
103967 ** function immediately. If all calls to virtual table methods are successful,
103968 ** SQLITE_OK is returned.
103969 */
103970 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
103971   int rc = SQLITE_OK;
103972
103973   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
103974   assert( iSavepoint>=0 );
103975   if( db->aVTrans ){
103976     int i;
103977     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
103978       VTable *pVTab = db->aVTrans[i];
103979       const sqlite3_module *pMod = pVTab->pMod->pModule;
103980       if( pVTab->pVtab && pMod->iVersion>=2 ){
103981         int (*xMethod)(sqlite3_vtab *, int);
103982         switch( op ){
103983           case SAVEPOINT_BEGIN:
103984             xMethod = pMod->xSavepoint;
103985             pVTab->iSavepoint = iSavepoint+1;
103986             break;
103987           case SAVEPOINT_ROLLBACK:
103988             xMethod = pMod->xRollbackTo;
103989             break;
103990           default:
103991             xMethod = pMod->xRelease;
103992             break;
103993         }
103994         if( xMethod && pVTab->iSavepoint>iSavepoint ){
103995           rc = xMethod(pVTab->pVtab, iSavepoint);
103996         }
103997       }
103998     }
103999   }
104000   return rc;
104001 }
104002
104003 /*
104004 ** The first parameter (pDef) is a function implementation.  The
104005 ** second parameter (pExpr) is the first argument to this function.
104006 ** If pExpr is a column in a virtual table, then let the virtual
104007 ** table implementation have an opportunity to overload the function.
104008 **
104009 ** This routine is used to allow virtual table implementations to
104010 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
104011 **
104012 ** Return either the pDef argument (indicating no change) or a
104013 ** new FuncDef structure that is marked as ephemeral using the
104014 ** SQLITE_FUNC_EPHEM flag.
104015 */
104016 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
104017   sqlite3 *db,    /* Database connection for reporting malloc problems */
104018   FuncDef *pDef,  /* Function to possibly overload */
104019   int nArg,       /* Number of arguments to the function */
104020   Expr *pExpr     /* First argument to the function */
104021 ){
104022   Table *pTab;
104023   sqlite3_vtab *pVtab;
104024   sqlite3_module *pMod;
104025   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
104026   void *pArg = 0;
104027   FuncDef *pNew;
104028   int rc = 0;
104029   char *zLowerName;
104030   unsigned char *z;
104031
104032
104033   /* Check to see the left operand is a column in a virtual table */
104034   if( NEVER(pExpr==0) ) return pDef;
104035   if( pExpr->op!=TK_COLUMN ) return pDef;
104036   pTab = pExpr->pTab;
104037   if( NEVER(pTab==0) ) return pDef;
104038   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
104039   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
104040   assert( pVtab!=0 );
104041   assert( pVtab->pModule!=0 );
104042   pMod = (sqlite3_module *)pVtab->pModule;
104043   if( pMod->xFindFunction==0 ) return pDef;
104044
104045   /* Call the xFindFunction method on the virtual table implementation
104046   ** to see if the implementation wants to overload this function
104047   */
104048   zLowerName = sqlite3DbStrDup(db, pDef->zName);
104049   if( zLowerName ){
104050     for(z=(unsigned char*)zLowerName; *z; z++){
104051       *z = sqlite3UpperToLower[*z];
104052     }
104053     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
104054     sqlite3DbFree(db, zLowerName);
104055   }
104056   if( rc==0 ){
104057     return pDef;
104058   }
104059
104060   /* Create a new ephemeral function definition for the overloaded
104061   ** function */
104062   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
104063                              + sqlite3Strlen30(pDef->zName) + 1);
104064   if( pNew==0 ){
104065     return pDef;
104066   }
104067   *pNew = *pDef;
104068   pNew->zName = (char *)&pNew[1];
104069   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
104070   pNew->xFunc = xFunc;
104071   pNew->pUserData = pArg;
104072   pNew->flags |= SQLITE_FUNC_EPHEM;
104073   return pNew;
104074 }
104075
104076 /*
104077 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
104078 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
104079 ** array if it is missing.  If pTab is already in the array, this routine
104080 ** is a no-op.
104081 */
104082 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
104083   Parse *pToplevel = sqlite3ParseToplevel(pParse);
104084   int i, n;
104085   Table **apVtabLock;
104086
104087   assert( IsVirtual(pTab) );
104088   for(i=0; i<pToplevel->nVtabLock; i++){
104089     if( pTab==pToplevel->apVtabLock[i] ) return;
104090   }
104091   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
104092   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
104093   if( apVtabLock ){
104094     pToplevel->apVtabLock = apVtabLock;
104095     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
104096   }else{
104097     pToplevel->db->mallocFailed = 1;
104098   }
104099 }
104100
104101 /*
104102 ** Return the ON CONFLICT resolution mode in effect for the virtual
104103 ** table update operation currently in progress.
104104 **
104105 ** The results of this routine are undefined unless it is called from
104106 ** within an xUpdate method.
104107 */
104108 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
104109   static const unsigned char aMap[] = {
104110     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
104111   };
104112   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
104113   assert( OE_Ignore==4 && OE_Replace==5 );
104114   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
104115   return (int)aMap[db->vtabOnConflict-1];
104116 }
104117
104118 /*
104119 ** Call from within the xCreate() or xConnect() methods to provide
104120 ** the SQLite core with additional information about the behavior
104121 ** of the virtual table being implemented.
104122 */
104123 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
104124   va_list ap;
104125   int rc = SQLITE_OK;
104126
104127   sqlite3_mutex_enter(db->mutex);
104128
104129   va_start(ap, op);
104130   switch( op ){
104131     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
104132       VtabCtx *p = db->pVtabCtx;
104133       if( !p ){
104134         rc = SQLITE_MISUSE_BKPT;
104135       }else{
104136         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
104137         p->pVTable->bConstraint = (u8)va_arg(ap, int);
104138       }
104139       break;
104140     }
104141     default:
104142       rc = SQLITE_MISUSE_BKPT;
104143       break;
104144   }
104145   va_end(ap);
104146
104147   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
104148   sqlite3_mutex_leave(db->mutex);
104149   return rc;
104150 }
104151
104152 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104153
104154 /************** End of vtab.c ************************************************/
104155 /************** Begin file where.c *******************************************/
104156 /*
104157 ** 2001 September 15
104158 **
104159 ** The author disclaims copyright to this source code.  In place of
104160 ** a legal notice, here is a blessing:
104161 **
104162 **    May you do good and not evil.
104163 **    May you find forgiveness for yourself and forgive others.
104164 **    May you share freely, never taking more than you give.
104165 **
104166 *************************************************************************
104167 ** This module contains C code that generates VDBE code used to process
104168 ** the WHERE clause of SQL statements.  This module is responsible for
104169 ** generating the code that loops through a table looking for applicable
104170 ** rows.  Indices are selected and used to speed the search when doing
104171 ** so is applicable.  Because this module is responsible for selecting
104172 ** indices, you might also think of this module as the "query optimizer".
104173 */
104174
104175
104176 /*
104177 ** Trace output macros
104178 */
104179 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104180 /***/ int sqlite3WhereTrace = 0;
104181 #endif
104182 #if defined(SQLITE_DEBUG) \
104183     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104184 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
104185 #else
104186 # define WHERETRACE(X)
104187 #endif
104188
104189 /* Forward reference
104190 */
104191 typedef struct WhereClause WhereClause;
104192 typedef struct WhereMaskSet WhereMaskSet;
104193 typedef struct WhereOrInfo WhereOrInfo;
104194 typedef struct WhereAndInfo WhereAndInfo;
104195 typedef struct WhereCost WhereCost;
104196
104197 /*
104198 ** The query generator uses an array of instances of this structure to
104199 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
104200 ** clause subexpression is separated from the others by AND operators,
104201 ** usually, or sometimes subexpressions separated by OR.
104202 **
104203 ** All WhereTerms are collected into a single WhereClause structure.
104204 ** The following identity holds:
104205 **
104206 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
104207 **
104208 ** When a term is of the form:
104209 **
104210 **              X <op> <expr>
104211 **
104212 ** where X is a column name and <op> is one of certain operators,
104213 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
104214 ** cursor number and column number for X.  WhereTerm.eOperator records
104215 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
104216 ** use of a bitmask encoding for the operator allows us to search
104217 ** quickly for terms that match any of several different operators.
104218 **
104219 ** A WhereTerm might also be two or more subterms connected by OR:
104220 **
104221 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
104222 **
104223 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
104224 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
104225 ** is collected about the
104226 **
104227 ** If a term in the WHERE clause does not match either of the two previous
104228 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
104229 ** to the original subexpression content and wtFlags is set up appropriately
104230 ** but no other fields in the WhereTerm object are meaningful.
104231 **
104232 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
104233 ** but they do so indirectly.  A single WhereMaskSet structure translates
104234 ** cursor number into bits and the translated bit is stored in the prereq
104235 ** fields.  The translation is used in order to maximize the number of
104236 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
104237 ** spread out over the non-negative integers.  For example, the cursor
104238 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
104239 ** translates these sparse cursor numbers into consecutive integers
104240 ** beginning with 0 in order to make the best possible use of the available
104241 ** bits in the Bitmask.  So, in the example above, the cursor numbers
104242 ** would be mapped into integers 0 through 7.
104243 **
104244 ** The number of terms in a join is limited by the number of bits
104245 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
104246 ** is only able to process joins with 64 or fewer tables.
104247 */
104248 typedef struct WhereTerm WhereTerm;
104249 struct WhereTerm {
104250   Expr *pExpr;            /* Pointer to the subexpression that is this term */
104251   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
104252   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
104253   union {
104254     int leftColumn;         /* Column number of X in "X <op> <expr>" */
104255     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
104256     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
104257   } u;
104258   u16 eOperator;          /* A WO_xx value describing <op> */
104259   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
104260   u8 nChild;              /* Number of children that must disable us */
104261   WhereClause *pWC;       /* The clause this term is part of */
104262   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
104263   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
104264 };
104265
104266 /*
104267 ** Allowed values of WhereTerm.wtFlags
104268 */
104269 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
104270 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
104271 #define TERM_CODED      0x04   /* This term is already coded */
104272 #define TERM_COPIED     0x08   /* Has a child */
104273 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
104274 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
104275 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
104276 #ifdef SQLITE_ENABLE_STAT3
104277 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
104278 #else
104279 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
104280 #endif
104281
104282 /*
104283 ** An instance of the following structure holds all information about a
104284 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
104285 **
104286 ** Explanation of pOuter:  For a WHERE clause of the form
104287 **
104288 **           a AND ((b AND c) OR (d AND e)) AND f
104289 **
104290 ** There are separate WhereClause objects for the whole clause and for
104291 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
104292 ** subclauses points to the WhereClause object for the whole clause.
104293 */
104294 struct WhereClause {
104295   Parse *pParse;           /* The parser context */
104296   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
104297   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
104298   WhereClause *pOuter;     /* Outer conjunction */
104299   u8 op;                   /* Split operator.  TK_AND or TK_OR */
104300   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
104301   int nTerm;               /* Number of terms */
104302   int nSlot;               /* Number of entries in a[] */
104303   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
104304 #if defined(SQLITE_SMALL_STACK)
104305   WhereTerm aStatic[1];    /* Initial static space for a[] */
104306 #else
104307   WhereTerm aStatic[8];    /* Initial static space for a[] */
104308 #endif
104309 };
104310
104311 /*
104312 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
104313 ** a dynamically allocated instance of the following structure.
104314 */
104315 struct WhereOrInfo {
104316   WhereClause wc;          /* Decomposition into subterms */
104317   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
104318 };
104319
104320 /*
104321 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
104322 ** a dynamically allocated instance of the following structure.
104323 */
104324 struct WhereAndInfo {
104325   WhereClause wc;          /* The subexpression broken out */
104326 };
104327
104328 /*
104329 ** An instance of the following structure keeps track of a mapping
104330 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
104331 **
104332 ** The VDBE cursor numbers are small integers contained in
104333 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
104334 ** clause, the cursor numbers might not begin with 0 and they might
104335 ** contain gaps in the numbering sequence.  But we want to make maximum
104336 ** use of the bits in our bitmasks.  This structure provides a mapping
104337 ** from the sparse cursor numbers into consecutive integers beginning
104338 ** with 0.
104339 **
104340 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
104341 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
104342 **
104343 ** For example, if the WHERE clause expression used these VDBE
104344 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
104345 ** would map those cursor numbers into bits 0 through 5.
104346 **
104347 ** Note that the mapping is not necessarily ordered.  In the example
104348 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
104349 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
104350 ** does not really matter.  What is important is that sparse cursor
104351 ** numbers all get mapped into bit numbers that begin with 0 and contain
104352 ** no gaps.
104353 */
104354 struct WhereMaskSet {
104355   int n;                        /* Number of assigned cursor values */
104356   int ix[BMS];                  /* Cursor assigned to each bit */
104357 };
104358
104359 /*
104360 ** A WhereCost object records a lookup strategy and the estimated
104361 ** cost of pursuing that strategy.
104362 */
104363 struct WhereCost {
104364   WherePlan plan;    /* The lookup strategy */
104365   double rCost;      /* Overall cost of pursuing this search strategy */
104366   Bitmask used;      /* Bitmask of cursors used by this plan */
104367 };
104368
104369 /*
104370 ** Bitmasks for the operators that indices are able to exploit.  An
104371 ** OR-ed combination of these values can be used when searching for
104372 ** terms in the where clause.
104373 */
104374 #define WO_IN     0x001
104375 #define WO_EQ     0x002
104376 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
104377 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
104378 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
104379 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
104380 #define WO_MATCH  0x040
104381 #define WO_ISNULL 0x080
104382 #define WO_OR     0x100       /* Two or more OR-connected terms */
104383 #define WO_AND    0x200       /* Two or more AND-connected terms */
104384 #define WO_NOOP   0x800       /* This term does not restrict search space */
104385
104386 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
104387 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
104388
104389 /*
104390 ** Value for wsFlags returned by bestIndex() and stored in
104391 ** WhereLevel.wsFlags.  These flags determine which search
104392 ** strategies are appropriate.
104393 **
104394 ** The least significant 12 bits is reserved as a mask for WO_ values above.
104395 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
104396 ** But if the table is the right table of a left join, WhereLevel.wsFlags
104397 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
104398 ** the "op" parameter to findTerm when we are resolving equality constraints.
104399 ** ISNULL constraints will then not be used on the right table of a left
104400 ** join.  Tickets #2177 and #2189.
104401 */
104402 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
104403 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
104404 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
104405 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
104406 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
104407 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
104408 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
104409 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
104410 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
104411 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
104412 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
104413 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
104414 #define WHERE_IDX_ONLY     0x00400000  /* Use index only - omit table */
104415 #define WHERE_ORDERED      0x00800000  /* Output will appear in correct order */
104416 #define WHERE_REVERSE      0x01000000  /* Scan in reverse order */
104417 #define WHERE_UNIQUE       0x02000000  /* Selects no more than one row */
104418 #define WHERE_ALL_UNIQUE   0x04000000  /* This and all prior have one row */
104419 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
104420 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
104421 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
104422 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
104423 #define WHERE_COVER_SCAN   0x80000000  /* Full scan of a covering index */
104424
104425 /*
104426 ** This module contains many separate subroutines that work together to
104427 ** find the best indices to use for accessing a particular table in a query.
104428 ** An instance of the following structure holds context information about the
104429 ** index search so that it can be more easily passed between the various
104430 ** routines.
104431 */
104432 typedef struct WhereBestIdx WhereBestIdx;
104433 struct WhereBestIdx {
104434   Parse *pParse;                  /* Parser context */
104435   WhereClause *pWC;               /* The WHERE clause */
104436   struct SrcList_item *pSrc;      /* The FROM clause term to search */
104437   Bitmask notReady;               /* Mask of cursors not available */
104438   Bitmask notValid;               /* Cursors not available for any purpose */
104439   ExprList *pOrderBy;             /* The ORDER BY clause */
104440   ExprList *pDistinct;            /* The select-list if query is DISTINCT */
104441   sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
104442   int i, n;                       /* Which loop is being coded; # of loops */
104443   WhereLevel *aLevel;             /* Info about outer loops */
104444   WhereCost cost;                 /* Lowest cost query plan */
104445 };
104446
104447 /*
104448 ** Return TRUE if the probe cost is less than the baseline cost
104449 */
104450 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
104451   if( pProbe->rCost<pBaseline->rCost ) return 1;
104452   if( pProbe->rCost>pBaseline->rCost ) return 0;
104453   if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
104454   if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
104455   return 0;
104456 }
104457
104458 /*
104459 ** Initialize a preallocated WhereClause structure.
104460 */
104461 static void whereClauseInit(
104462   WhereClause *pWC,        /* The WhereClause to be initialized */
104463   Parse *pParse,           /* The parsing context */
104464   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
104465   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
104466 ){
104467   pWC->pParse = pParse;
104468   pWC->pMaskSet = pMaskSet;
104469   pWC->pOuter = 0;
104470   pWC->nTerm = 0;
104471   pWC->nSlot = ArraySize(pWC->aStatic);
104472   pWC->a = pWC->aStatic;
104473   pWC->vmask = 0;
104474   pWC->wctrlFlags = wctrlFlags;
104475 }
104476
104477 /* Forward reference */
104478 static void whereClauseClear(WhereClause*);
104479
104480 /*
104481 ** Deallocate all memory associated with a WhereOrInfo object.
104482 */
104483 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
104484   whereClauseClear(&p->wc);
104485   sqlite3DbFree(db, p);
104486 }
104487
104488 /*
104489 ** Deallocate all memory associated with a WhereAndInfo object.
104490 */
104491 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
104492   whereClauseClear(&p->wc);
104493   sqlite3DbFree(db, p);
104494 }
104495
104496 /*
104497 ** Deallocate a WhereClause structure.  The WhereClause structure
104498 ** itself is not freed.  This routine is the inverse of whereClauseInit().
104499 */
104500 static void whereClauseClear(WhereClause *pWC){
104501   int i;
104502   WhereTerm *a;
104503   sqlite3 *db = pWC->pParse->db;
104504   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104505     if( a->wtFlags & TERM_DYNAMIC ){
104506       sqlite3ExprDelete(db, a->pExpr);
104507     }
104508     if( a->wtFlags & TERM_ORINFO ){
104509       whereOrInfoDelete(db, a->u.pOrInfo);
104510     }else if( a->wtFlags & TERM_ANDINFO ){
104511       whereAndInfoDelete(db, a->u.pAndInfo);
104512     }
104513   }
104514   if( pWC->a!=pWC->aStatic ){
104515     sqlite3DbFree(db, pWC->a);
104516   }
104517 }
104518
104519 /*
104520 ** Add a single new WhereTerm entry to the WhereClause object pWC.
104521 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
104522 ** The index in pWC->a[] of the new WhereTerm is returned on success.
104523 ** 0 is returned if the new WhereTerm could not be added due to a memory
104524 ** allocation error.  The memory allocation failure will be recorded in
104525 ** the db->mallocFailed flag so that higher-level functions can detect it.
104526 **
104527 ** This routine will increase the size of the pWC->a[] array as necessary.
104528 **
104529 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
104530 ** for freeing the expression p is assumed by the WhereClause object pWC.
104531 ** This is true even if this routine fails to allocate a new WhereTerm.
104532 **
104533 ** WARNING:  This routine might reallocate the space used to store
104534 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
104535 ** calling this routine.  Such pointers may be reinitialized by referencing
104536 ** the pWC->a[] array.
104537 */
104538 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
104539   WhereTerm *pTerm;
104540   int idx;
104541   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
104542   if( pWC->nTerm>=pWC->nSlot ){
104543     WhereTerm *pOld = pWC->a;
104544     sqlite3 *db = pWC->pParse->db;
104545     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104546     if( pWC->a==0 ){
104547       if( wtFlags & TERM_DYNAMIC ){
104548         sqlite3ExprDelete(db, p);
104549       }
104550       pWC->a = pOld;
104551       return 0;
104552     }
104553     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
104554     if( pOld!=pWC->aStatic ){
104555       sqlite3DbFree(db, pOld);
104556     }
104557     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
104558   }
104559   pTerm = &pWC->a[idx = pWC->nTerm++];
104560   pTerm->pExpr = sqlite3ExprSkipCollate(p);
104561   pTerm->wtFlags = wtFlags;
104562   pTerm->pWC = pWC;
104563   pTerm->iParent = -1;
104564   return idx;
104565 }
104566
104567 /*
104568 ** This routine identifies subexpressions in the WHERE clause where
104569 ** each subexpression is separated by the AND operator or some other
104570 ** operator specified in the op parameter.  The WhereClause structure
104571 ** is filled with pointers to subexpressions.  For example:
104572 **
104573 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
104574 **           \________/     \_______________/     \________________/
104575 **            slot[0]            slot[1]               slot[2]
104576 **
104577 ** The original WHERE clause in pExpr is unaltered.  All this routine
104578 ** does is make slot[] entries point to substructure within pExpr.
104579 **
104580 ** In the previous sentence and in the diagram, "slot[]" refers to
104581 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
104582 ** all terms of the WHERE clause.
104583 */
104584 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
104585   pWC->op = (u8)op;
104586   if( pExpr==0 ) return;
104587   if( pExpr->op!=op ){
104588     whereClauseInsert(pWC, pExpr, 0);
104589   }else{
104590     whereSplit(pWC, pExpr->pLeft, op);
104591     whereSplit(pWC, pExpr->pRight, op);
104592   }
104593 }
104594
104595 /*
104596 ** Initialize an expression mask set (a WhereMaskSet object)
104597 */
104598 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
104599
104600 /*
104601 ** Return the bitmask for the given cursor number.  Return 0 if
104602 ** iCursor is not in the set.
104603 */
104604 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104605   int i;
104606   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104607   for(i=0; i<pMaskSet->n; i++){
104608     if( pMaskSet->ix[i]==iCursor ){
104609       return ((Bitmask)1)<<i;
104610     }
104611   }
104612   return 0;
104613 }
104614
104615 /*
104616 ** Create a new mask for cursor iCursor.
104617 **
104618 ** There is one cursor per table in the FROM clause.  The number of
104619 ** tables in the FROM clause is limited by a test early in the
104620 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
104621 ** array will never overflow.
104622 */
104623 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
104624   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104625   pMaskSet->ix[pMaskSet->n++] = iCursor;
104626 }
104627
104628 /*
104629 ** This routine walks (recursively) an expression tree and generates
104630 ** a bitmask indicating which tables are used in that expression
104631 ** tree.
104632 **
104633 ** In order for this routine to work, the calling function must have
104634 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
104635 ** the header comment on that routine for additional information.
104636 ** The sqlite3ResolveExprNames() routines looks for column names and
104637 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
104638 ** the VDBE cursor number of the table.  This routine just has to
104639 ** translate the cursor numbers into bitmask values and OR all
104640 ** the bitmasks together.
104641 */
104642 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104643 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104644 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104645   Bitmask mask = 0;
104646   if( p==0 ) return 0;
104647   if( p->op==TK_COLUMN ){
104648     mask = getMask(pMaskSet, p->iTable);
104649     return mask;
104650   }
104651   mask = exprTableUsage(pMaskSet, p->pRight);
104652   mask |= exprTableUsage(pMaskSet, p->pLeft);
104653   if( ExprHasProperty(p, EP_xIsSelect) ){
104654     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
104655   }else{
104656     mask |= exprListTableUsage(pMaskSet, p->x.pList);
104657   }
104658   return mask;
104659 }
104660 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
104661   int i;
104662   Bitmask mask = 0;
104663   if( pList ){
104664     for(i=0; i<pList->nExpr; i++){
104665       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
104666     }
104667   }
104668   return mask;
104669 }
104670 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
104671   Bitmask mask = 0;
104672   while( pS ){
104673     SrcList *pSrc = pS->pSrc;
104674     mask |= exprListTableUsage(pMaskSet, pS->pEList);
104675     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
104676     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
104677     mask |= exprTableUsage(pMaskSet, pS->pWhere);
104678     mask |= exprTableUsage(pMaskSet, pS->pHaving);
104679     if( ALWAYS(pSrc!=0) ){
104680       int i;
104681       for(i=0; i<pSrc->nSrc; i++){
104682         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
104683         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
104684       }
104685     }
104686     pS = pS->pPrior;
104687   }
104688   return mask;
104689 }
104690
104691 /*
104692 ** Return TRUE if the given operator is one of the operators that is
104693 ** allowed for an indexable WHERE clause term.  The allowed operators are
104694 ** "=", "<", ">", "<=", ">=", and "IN".
104695 **
104696 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
104697 ** of one of the following forms: column = expression column > expression
104698 ** column >= expression column < expression column <= expression
104699 ** expression = column expression > column expression >= column
104700 ** expression < column expression <= column column IN
104701 ** (expression-list) column IN (subquery) column IS NULL
104702 */
104703 static int allowedOp(int op){
104704   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
104705   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
104706   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
104707   assert( TK_GE==TK_EQ+4 );
104708   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
104709 }
104710
104711 /*
104712 ** Swap two objects of type TYPE.
104713 */
104714 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
104715
104716 /*
104717 ** Commute a comparison operator.  Expressions of the form "X op Y"
104718 ** are converted into "Y op X".
104719 **
104720 ** If left/right precendence rules come into play when determining the
104721 ** collating
104722 ** side of the comparison, it remains associated with the same side after
104723 ** the commutation. So "Y collate NOCASE op X" becomes
104724 ** "X op Y". This is because any collation sequence on
104725 ** the left hand side of a comparison overrides any collation sequence
104726 ** attached to the right. For the same reason the EP_Collate flag
104727 ** is not commuted.
104728 */
104729 static void exprCommute(Parse *pParse, Expr *pExpr){
104730   u16 expRight = (pExpr->pRight->flags & EP_Collate);
104731   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
104732   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
104733   if( expRight==expLeft ){
104734     /* Either X and Y both have COLLATE operator or neither do */
104735     if( expRight ){
104736       /* Both X and Y have COLLATE operators.  Make sure X is always
104737       ** used by clearing the EP_Collate flag from Y. */
104738       pExpr->pRight->flags &= ~EP_Collate;
104739     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
104740       /* Neither X nor Y have COLLATE operators, but X has a non-default
104741       ** collating sequence.  So add the EP_Collate marker on X to cause
104742       ** it to be searched first. */
104743       pExpr->pLeft->flags |= EP_Collate;
104744     }
104745   }
104746   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
104747   if( pExpr->op>=TK_GT ){
104748     assert( TK_LT==TK_GT+2 );
104749     assert( TK_GE==TK_LE+2 );
104750     assert( TK_GT>TK_EQ );
104751     assert( TK_GT<TK_LE );
104752     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
104753     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
104754   }
104755 }
104756
104757 /*
104758 ** Translate from TK_xx operator to WO_xx bitmask.
104759 */
104760 static u16 operatorMask(int op){
104761   u16 c;
104762   assert( allowedOp(op) );
104763   if( op==TK_IN ){
104764     c = WO_IN;
104765   }else if( op==TK_ISNULL ){
104766     c = WO_ISNULL;
104767   }else{
104768     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
104769     c = (u16)(WO_EQ<<(op-TK_EQ));
104770   }
104771   assert( op!=TK_ISNULL || c==WO_ISNULL );
104772   assert( op!=TK_IN || c==WO_IN );
104773   assert( op!=TK_EQ || c==WO_EQ );
104774   assert( op!=TK_LT || c==WO_LT );
104775   assert( op!=TK_LE || c==WO_LE );
104776   assert( op!=TK_GT || c==WO_GT );
104777   assert( op!=TK_GE || c==WO_GE );
104778   return c;
104779 }
104780
104781 /*
104782 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
104783 ** where X is a reference to the iColumn of table iCur and <op> is one of
104784 ** the WO_xx operator codes specified by the op parameter.
104785 ** Return a pointer to the term.  Return 0 if not found.
104786 */
104787 static WhereTerm *findTerm(
104788   WhereClause *pWC,     /* The WHERE clause to be searched */
104789   int iCur,             /* Cursor number of LHS */
104790   int iColumn,          /* Column number of LHS */
104791   Bitmask notReady,     /* RHS must not overlap with this mask */
104792   u32 op,               /* Mask of WO_xx values describing operator */
104793   Index *pIdx           /* Must be compatible with this index, if not NULL */
104794 ){
104795   WhereTerm *pTerm;
104796   int k;
104797   assert( iCur>=0 );
104798   op &= WO_ALL;
104799   for(; pWC; pWC=pWC->pOuter){
104800     for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
104801       if( pTerm->leftCursor==iCur
104802          && (pTerm->prereqRight & notReady)==0
104803          && pTerm->u.leftColumn==iColumn
104804          && (pTerm->eOperator & op)!=0
104805       ){
104806         if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
104807           Expr *pX = pTerm->pExpr;
104808           CollSeq *pColl;
104809           char idxaff;
104810           int j;
104811           Parse *pParse = pWC->pParse;
104812
104813           idxaff = pIdx->pTable->aCol[iColumn].affinity;
104814           if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
104815
104816           /* Figure out the collation sequence required from an index for
104817           ** it to be useful for optimising expression pX. Store this
104818           ** value in variable pColl.
104819           */
104820           assert(pX->pLeft);
104821           pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104822           if( pColl==0 ) pColl = pParse->db->pDfltColl;
104823
104824           for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
104825             if( NEVER(j>=pIdx->nColumn) ) return 0;
104826           }
104827           if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
104828         }
104829         return pTerm;
104830       }
104831     }
104832   }
104833   return 0;
104834 }
104835
104836 /* Forward reference */
104837 static void exprAnalyze(SrcList*, WhereClause*, int);
104838
104839 /*
104840 ** Call exprAnalyze on all terms in a WHERE clause.
104841 **
104842 **
104843 */
104844 static void exprAnalyzeAll(
104845   SrcList *pTabList,       /* the FROM clause */
104846   WhereClause *pWC         /* the WHERE clause to be analyzed */
104847 ){
104848   int i;
104849   for(i=pWC->nTerm-1; i>=0; i--){
104850     exprAnalyze(pTabList, pWC, i);
104851   }
104852 }
104853
104854 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
104855 /*
104856 ** Check to see if the given expression is a LIKE or GLOB operator that
104857 ** can be optimized using inequality constraints.  Return TRUE if it is
104858 ** so and false if not.
104859 **
104860 ** In order for the operator to be optimizible, the RHS must be a string
104861 ** literal that does not begin with a wildcard.
104862 */
104863 static int isLikeOrGlob(
104864   Parse *pParse,    /* Parsing and code generating context */
104865   Expr *pExpr,      /* Test this expression */
104866   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
104867   int *pisComplete, /* True if the only wildcard is % in the last character */
104868   int *pnoCase      /* True if uppercase is equivalent to lowercase */
104869 ){
104870   const char *z = 0;         /* String on RHS of LIKE operator */
104871   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
104872   ExprList *pList;           /* List of operands to the LIKE operator */
104873   int c;                     /* One character in z[] */
104874   int cnt;                   /* Number of non-wildcard prefix characters */
104875   char wc[3];                /* Wildcard characters */
104876   sqlite3 *db = pParse->db;  /* Database connection */
104877   sqlite3_value *pVal = 0;
104878   int op;                    /* Opcode of pRight */
104879
104880   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
104881     return 0;
104882   }
104883 #ifdef SQLITE_EBCDIC
104884   if( *pnoCase ) return 0;
104885 #endif
104886   pList = pExpr->x.pList;
104887   pLeft = pList->a[1].pExpr;
104888   if( pLeft->op!=TK_COLUMN
104889    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
104890    || IsVirtual(pLeft->pTab)
104891   ){
104892     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
104893     ** be the name of an indexed column with TEXT affinity. */
104894     return 0;
104895   }
104896   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
104897
104898   pRight = pList->a[0].pExpr;
104899   op = pRight->op;
104900   if( op==TK_REGISTER ){
104901     op = pRight->op2;
104902   }
104903   if( op==TK_VARIABLE ){
104904     Vdbe *pReprepare = pParse->pReprepare;
104905     int iCol = pRight->iColumn;
104906     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
104907     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
104908       z = (char *)sqlite3_value_text(pVal);
104909     }
104910     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
104911     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
104912   }else if( op==TK_STRING ){
104913     z = pRight->u.zToken;
104914   }
104915   if( z ){
104916     cnt = 0;
104917     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
104918       cnt++;
104919     }
104920     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
104921       Expr *pPrefix;
104922       *pisComplete = c==wc[0] && z[cnt+1]==0;
104923       pPrefix = sqlite3Expr(db, TK_STRING, z);
104924       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
104925       *ppPrefix = pPrefix;
104926       if( op==TK_VARIABLE ){
104927         Vdbe *v = pParse->pVdbe;
104928         sqlite3VdbeSetVarmask(v, pRight->iColumn);
104929         if( *pisComplete && pRight->u.zToken[1] ){
104930           /* If the rhs of the LIKE expression is a variable, and the current
104931           ** value of the variable means there is no need to invoke the LIKE
104932           ** function, then no OP_Variable will be added to the program.
104933           ** This causes problems for the sqlite3_bind_parameter_name()
104934           ** API. To workaround them, add a dummy OP_Variable here.
104935           */
104936           int r1 = sqlite3GetTempReg(pParse);
104937           sqlite3ExprCodeTarget(pParse, pRight, r1);
104938           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
104939           sqlite3ReleaseTempReg(pParse, r1);
104940         }
104941       }
104942     }else{
104943       z = 0;
104944     }
104945   }
104946
104947   sqlite3ValueFree(pVal);
104948   return (z!=0);
104949 }
104950 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
104951
104952
104953 #ifndef SQLITE_OMIT_VIRTUALTABLE
104954 /*
104955 ** Check to see if the given expression is of the form
104956 **
104957 **         column MATCH expr
104958 **
104959 ** If it is then return TRUE.  If not, return FALSE.
104960 */
104961 static int isMatchOfColumn(
104962   Expr *pExpr      /* Test this expression */
104963 ){
104964   ExprList *pList;
104965
104966   if( pExpr->op!=TK_FUNCTION ){
104967     return 0;
104968   }
104969   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
104970     return 0;
104971   }
104972   pList = pExpr->x.pList;
104973   if( pList->nExpr!=2 ){
104974     return 0;
104975   }
104976   if( pList->a[1].pExpr->op != TK_COLUMN ){
104977     return 0;
104978   }
104979   return 1;
104980 }
104981 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104982
104983 /*
104984 ** If the pBase expression originated in the ON or USING clause of
104985 ** a join, then transfer the appropriate markings over to derived.
104986 */
104987 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
104988   pDerived->flags |= pBase->flags & EP_FromJoin;
104989   pDerived->iRightJoinTable = pBase->iRightJoinTable;
104990 }
104991
104992 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
104993 /*
104994 ** Analyze a term that consists of two or more OR-connected
104995 ** subterms.  So in:
104996 **
104997 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
104998 **                          ^^^^^^^^^^^^^^^^^^^^
104999 **
105000 ** This routine analyzes terms such as the middle term in the above example.
105001 ** A WhereOrTerm object is computed and attached to the term under
105002 ** analysis, regardless of the outcome of the analysis.  Hence:
105003 **
105004 **     WhereTerm.wtFlags   |=  TERM_ORINFO
105005 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
105006 **
105007 ** The term being analyzed must have two or more of OR-connected subterms.
105008 ** A single subterm might be a set of AND-connected sub-subterms.
105009 ** Examples of terms under analysis:
105010 **
105011 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
105012 **     (B)     x=expr1 OR expr2=x OR x=expr3
105013 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
105014 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
105015 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
105016 **
105017 ** CASE 1:
105018 **
105019 ** If all subterms are of the form T.C=expr for some single column of C
105020 ** a single table T (as shown in example B above) then create a new virtual
105021 ** term that is an equivalent IN expression.  In other words, if the term
105022 ** being analyzed is:
105023 **
105024 **      x = expr1  OR  expr2 = x  OR  x = expr3
105025 **
105026 ** then create a new virtual term like this:
105027 **
105028 **      x IN (expr1,expr2,expr3)
105029 **
105030 ** CASE 2:
105031 **
105032 ** If all subterms are indexable by a single table T, then set
105033 **
105034 **     WhereTerm.eOperator              =  WO_OR
105035 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
105036 **
105037 ** A subterm is "indexable" if it is of the form
105038 ** "T.C <op> <expr>" where C is any column of table T and
105039 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
105040 ** A subterm is also indexable if it is an AND of two or more
105041 ** subsubterms at least one of which is indexable.  Indexable AND
105042 ** subterms have their eOperator set to WO_AND and they have
105043 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
105044 **
105045 ** From another point of view, "indexable" means that the subterm could
105046 ** potentially be used with an index if an appropriate index exists.
105047 ** This analysis does not consider whether or not the index exists; that
105048 ** is something the bestIndex() routine will determine.  This analysis
105049 ** only looks at whether subterms appropriate for indexing exist.
105050 **
105051 ** All examples A through E above all satisfy case 2.  But if a term
105052 ** also statisfies case 1 (such as B) we know that the optimizer will
105053 ** always prefer case 1, so in that case we pretend that case 2 is not
105054 ** satisfied.
105055 **
105056 ** It might be the case that multiple tables are indexable.  For example,
105057 ** (E) above is indexable on tables P, Q, and R.
105058 **
105059 ** Terms that satisfy case 2 are candidates for lookup by using
105060 ** separate indices to find rowids for each subterm and composing
105061 ** the union of all rowids using a RowSet object.  This is similar
105062 ** to "bitmap indices" in other database engines.
105063 **
105064 ** OTHERWISE:
105065 **
105066 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
105067 ** zero.  This term is not useful for search.
105068 */
105069 static void exprAnalyzeOrTerm(
105070   SrcList *pSrc,            /* the FROM clause */
105071   WhereClause *pWC,         /* the complete WHERE clause */
105072   int idxTerm               /* Index of the OR-term to be analyzed */
105073 ){
105074   Parse *pParse = pWC->pParse;            /* Parser context */
105075   sqlite3 *db = pParse->db;               /* Database connection */
105076   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
105077   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
105078   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
105079   int i;                                  /* Loop counters */
105080   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
105081   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
105082   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
105083   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
105084   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
105085
105086   /*
105087   ** Break the OR clause into its separate subterms.  The subterms are
105088   ** stored in a WhereClause structure containing within the WhereOrInfo
105089   ** object that is attached to the original OR clause term.
105090   */
105091   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
105092   assert( pExpr->op==TK_OR );
105093   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105094   if( pOrInfo==0 ) return;
105095   pTerm->wtFlags |= TERM_ORINFO;
105096   pOrWc = &pOrInfo->wc;
105097   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105098   whereSplit(pOrWc, pExpr, TK_OR);
105099   exprAnalyzeAll(pSrc, pOrWc);
105100   if( db->mallocFailed ) return;
105101   assert( pOrWc->nTerm>=2 );
105102
105103   /*
105104   ** Compute the set of tables that might satisfy cases 1 or 2.
105105   */
105106   indexable = ~(Bitmask)0;
105107   chngToIN = ~(pWC->vmask);
105108   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
105109     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
105110       WhereAndInfo *pAndInfo;
105111       assert( pOrTerm->eOperator==0 );
105112       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
105113       chngToIN = 0;
105114       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
105115       if( pAndInfo ){
105116         WhereClause *pAndWC;
105117         WhereTerm *pAndTerm;
105118         int j;
105119         Bitmask b = 0;
105120         pOrTerm->u.pAndInfo = pAndInfo;
105121         pOrTerm->wtFlags |= TERM_ANDINFO;
105122         pOrTerm->eOperator = WO_AND;
105123         pAndWC = &pAndInfo->wc;
105124         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105125         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105126         exprAnalyzeAll(pSrc, pAndWC);
105127         pAndWC->pOuter = pWC;
105128         testcase( db->mallocFailed );
105129         if( !db->mallocFailed ){
105130           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105131             assert( pAndTerm->pExpr );
105132             if( allowedOp(pAndTerm->pExpr->op) ){
105133               b |= getMask(pMaskSet, pAndTerm->leftCursor);
105134             }
105135           }
105136         }
105137         indexable &= b;
105138       }
105139     }else if( pOrTerm->wtFlags & TERM_COPIED ){
105140       /* Skip this term for now.  We revisit it when we process the
105141       ** corresponding TERM_VIRTUAL term */
105142     }else{
105143       Bitmask b;
105144       b = getMask(pMaskSet, pOrTerm->leftCursor);
105145       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105146         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105147         b |= getMask(pMaskSet, pOther->leftCursor);
105148       }
105149       indexable &= b;
105150       if( pOrTerm->eOperator!=WO_EQ ){
105151         chngToIN = 0;
105152       }else{
105153         chngToIN &= b;
105154       }
105155     }
105156   }
105157
105158   /*
105159   ** Record the set of tables that satisfy case 2.  The set might be
105160   ** empty.
105161   */
105162   pOrInfo->indexable = indexable;
105163   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
105164
105165   /*
105166   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
105167   ** we have to do some additional checking to see if case 1 really
105168   ** is satisfied.
105169   **
105170   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
105171   ** that there is no possibility of transforming the OR clause into an
105172   ** IN operator because one or more terms in the OR clause contain
105173   ** something other than == on a column in the single table.  The 1-bit
105174   ** case means that every term of the OR clause is of the form
105175   ** "table.column=expr" for some single table.  The one bit that is set
105176   ** will correspond to the common table.  We still need to check to make
105177   ** sure the same column is used on all terms.  The 2-bit case is when
105178   ** the all terms are of the form "table1.column=table2.column".  It
105179   ** might be possible to form an IN operator with either table1.column
105180   ** or table2.column as the LHS if either is common to every term of
105181   ** the OR clause.
105182   **
105183   ** Note that terms of the form "table.column1=table.column2" (the
105184   ** same table on both sizes of the ==) cannot be optimized.
105185   */
105186   if( chngToIN ){
105187     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
105188     int iColumn = -1;         /* Column index on lhs of IN operator */
105189     int iCursor = -1;         /* Table cursor common to all terms */
105190     int j = 0;                /* Loop counter */
105191
105192     /* Search for a table and column that appears on one side or the
105193     ** other of the == operator in every subterm.  That table and column
105194     ** will be recorded in iCursor and iColumn.  There might not be any
105195     ** such table and column.  Set okToChngToIN if an appropriate table
105196     ** and column is found but leave okToChngToIN false if not found.
105197     */
105198     for(j=0; j<2 && !okToChngToIN; j++){
105199       pOrTerm = pOrWc->a;
105200       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
105201         assert( pOrTerm->eOperator==WO_EQ );
105202         pOrTerm->wtFlags &= ~TERM_OR_OK;
105203         if( pOrTerm->leftCursor==iCursor ){
105204           /* This is the 2-bit case and we are on the second iteration and
105205           ** current term is from the first iteration.  So skip this term. */
105206           assert( j==1 );
105207           continue;
105208         }
105209         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
105210           /* This term must be of the form t1.a==t2.b where t2 is in the
105211           ** chngToIN set but t1 is not.  This term will be either preceeded
105212           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
105213           ** and use its inversion. */
105214           testcase( pOrTerm->wtFlags & TERM_COPIED );
105215           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
105216           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
105217           continue;
105218         }
105219         iColumn = pOrTerm->u.leftColumn;
105220         iCursor = pOrTerm->leftCursor;
105221         break;
105222       }
105223       if( i<0 ){
105224         /* No candidate table+column was found.  This can only occur
105225         ** on the second iteration */
105226         assert( j==1 );
105227         assert( (chngToIN&(chngToIN-1))==0 );
105228         assert( chngToIN==getMask(pMaskSet, iCursor) );
105229         break;
105230       }
105231       testcase( j==1 );
105232
105233       /* We have found a candidate table and column.  Check to see if that
105234       ** table and column is common to every term in the OR clause */
105235       okToChngToIN = 1;
105236       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
105237         assert( pOrTerm->eOperator==WO_EQ );
105238         if( pOrTerm->leftCursor!=iCursor ){
105239           pOrTerm->wtFlags &= ~TERM_OR_OK;
105240         }else if( pOrTerm->u.leftColumn!=iColumn ){
105241           okToChngToIN = 0;
105242         }else{
105243           int affLeft, affRight;
105244           /* If the right-hand side is also a column, then the affinities
105245           ** of both right and left sides must be such that no type
105246           ** conversions are required on the right.  (Ticket #2249)
105247           */
105248           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
105249           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
105250           if( affRight!=0 && affRight!=affLeft ){
105251             okToChngToIN = 0;
105252           }else{
105253             pOrTerm->wtFlags |= TERM_OR_OK;
105254           }
105255         }
105256       }
105257     }
105258
105259     /* At this point, okToChngToIN is true if original pTerm satisfies
105260     ** case 1.  In that case, construct a new virtual term that is
105261     ** pTerm converted into an IN operator.
105262     **
105263     ** EV: R-00211-15100
105264     */
105265     if( okToChngToIN ){
105266       Expr *pDup;            /* A transient duplicate expression */
105267       ExprList *pList = 0;   /* The RHS of the IN operator */
105268       Expr *pLeft = 0;       /* The LHS of the IN operator */
105269       Expr *pNew;            /* The complete IN operator */
105270
105271       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
105272         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105273         assert( pOrTerm->eOperator==WO_EQ );
105274         assert( pOrTerm->leftCursor==iCursor );
105275         assert( pOrTerm->u.leftColumn==iColumn );
105276         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105277         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
105278         pLeft = pOrTerm->pExpr->pLeft;
105279       }
105280       assert( pLeft!=0 );
105281       pDup = sqlite3ExprDup(db, pLeft, 0);
105282       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
105283       if( pNew ){
105284         int idxNew;
105285         transferJoinMarkings(pNew, pExpr);
105286         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
105287         pNew->x.pList = pList;
105288         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
105289         testcase( idxNew==0 );
105290         exprAnalyze(pSrc, pWC, idxNew);
105291         pTerm = &pWC->a[idxTerm];
105292         pWC->a[idxNew].iParent = idxTerm;
105293         pTerm->nChild = 1;
105294       }else{
105295         sqlite3ExprListDelete(db, pList);
105296       }
105297       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
105298     }
105299   }
105300 }
105301 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
105302
105303
105304 /*
105305 ** The input to this routine is an WhereTerm structure with only the
105306 ** "pExpr" field filled in.  The job of this routine is to analyze the
105307 ** subexpression and populate all the other fields of the WhereTerm
105308 ** structure.
105309 **
105310 ** If the expression is of the form "<expr> <op> X" it gets commuted
105311 ** to the standard form of "X <op> <expr>".
105312 **
105313 ** If the expression is of the form "X <op> Y" where both X and Y are
105314 ** columns, then the original expression is unchanged and a new virtual
105315 ** term of the form "Y <op> X" is added to the WHERE clause and
105316 ** analyzed separately.  The original term is marked with TERM_COPIED
105317 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
105318 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
105319 ** is a commuted copy of a prior term.)  The original term has nChild=1
105320 ** and the copy has idxParent set to the index of the original term.
105321 */
105322 static void exprAnalyze(
105323   SrcList *pSrc,            /* the FROM clause */
105324   WhereClause *pWC,         /* the WHERE clause */
105325   int idxTerm               /* Index of the term to be analyzed */
105326 ){
105327   WhereTerm *pTerm;                /* The term to be analyzed */
105328   WhereMaskSet *pMaskSet;          /* Set of table index masks */
105329   Expr *pExpr;                     /* The expression to be analyzed */
105330   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
105331   Bitmask prereqAll;               /* Prerequesites of pExpr */
105332   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
105333   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
105334   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
105335   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
105336   int op;                          /* Top-level operator.  pExpr->op */
105337   Parse *pParse = pWC->pParse;     /* Parsing context */
105338   sqlite3 *db = pParse->db;        /* Database connection */
105339
105340   if( db->mallocFailed ){
105341     return;
105342   }
105343   pTerm = &pWC->a[idxTerm];
105344   pMaskSet = pWC->pMaskSet;
105345   pExpr = pTerm->pExpr;
105346   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105347   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105348   op = pExpr->op;
105349   if( op==TK_IN ){
105350     assert( pExpr->pRight==0 );
105351     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105352       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
105353     }else{
105354       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
105355     }
105356   }else if( op==TK_ISNULL ){
105357     pTerm->prereqRight = 0;
105358   }else{
105359     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
105360   }
105361   prereqAll = exprTableUsage(pMaskSet, pExpr);
105362   if( ExprHasProperty(pExpr, EP_FromJoin) ){
105363     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
105364     prereqAll |= x;
105365     extraRight = x-1;  /* ON clause terms may not be used with an index
105366                        ** on left table of a LEFT JOIN.  Ticket #3015 */
105367   }
105368   pTerm->prereqAll = prereqAll;
105369   pTerm->leftCursor = -1;
105370   pTerm->iParent = -1;
105371   pTerm->eOperator = 0;
105372   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
105373     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
105374     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
105375     if( pLeft->op==TK_COLUMN ){
105376       pTerm->leftCursor = pLeft->iTable;
105377       pTerm->u.leftColumn = pLeft->iColumn;
105378       pTerm->eOperator = operatorMask(op);
105379     }
105380     if( pRight && pRight->op==TK_COLUMN ){
105381       WhereTerm *pNew;
105382       Expr *pDup;
105383       if( pTerm->leftCursor>=0 ){
105384         int idxNew;
105385         pDup = sqlite3ExprDup(db, pExpr, 0);
105386         if( db->mallocFailed ){
105387           sqlite3ExprDelete(db, pDup);
105388           return;
105389         }
105390         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
105391         if( idxNew==0 ) return;
105392         pNew = &pWC->a[idxNew];
105393         pNew->iParent = idxTerm;
105394         pTerm = &pWC->a[idxTerm];
105395         pTerm->nChild = 1;
105396         pTerm->wtFlags |= TERM_COPIED;
105397       }else{
105398         pDup = pExpr;
105399         pNew = pTerm;
105400       }
105401       exprCommute(pParse, pDup);
105402       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
105403       pNew->leftCursor = pLeft->iTable;
105404       pNew->u.leftColumn = pLeft->iColumn;
105405       testcase( (prereqLeft | extraRight) != prereqLeft );
105406       pNew->prereqRight = prereqLeft | extraRight;
105407       pNew->prereqAll = prereqAll;
105408       pNew->eOperator = operatorMask(pDup->op);
105409     }
105410   }
105411
105412 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
105413   /* If a term is the BETWEEN operator, create two new virtual terms
105414   ** that define the range that the BETWEEN implements.  For example:
105415   **
105416   **      a BETWEEN b AND c
105417   **
105418   ** is converted into:
105419   **
105420   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
105421   **
105422   ** The two new terms are added onto the end of the WhereClause object.
105423   ** The new terms are "dynamic" and are children of the original BETWEEN
105424   ** term.  That means that if the BETWEEN term is coded, the children are
105425   ** skipped.  Or, if the children are satisfied by an index, the original
105426   ** BETWEEN term is skipped.
105427   */
105428   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
105429     ExprList *pList = pExpr->x.pList;
105430     int i;
105431     static const u8 ops[] = {TK_GE, TK_LE};
105432     assert( pList!=0 );
105433     assert( pList->nExpr==2 );
105434     for(i=0; i<2; i++){
105435       Expr *pNewExpr;
105436       int idxNew;
105437       pNewExpr = sqlite3PExpr(pParse, ops[i],
105438                              sqlite3ExprDup(db, pExpr->pLeft, 0),
105439                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
105440       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
105441       testcase( idxNew==0 );
105442       exprAnalyze(pSrc, pWC, idxNew);
105443       pTerm = &pWC->a[idxTerm];
105444       pWC->a[idxNew].iParent = idxTerm;
105445     }
105446     pTerm->nChild = 2;
105447   }
105448 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
105449
105450 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
105451   /* Analyze a term that is composed of two or more subterms connected by
105452   ** an OR operator.
105453   */
105454   else if( pExpr->op==TK_OR ){
105455     assert( pWC->op==TK_AND );
105456     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
105457     pTerm = &pWC->a[idxTerm];
105458   }
105459 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
105460
105461 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
105462   /* Add constraints to reduce the search space on a LIKE or GLOB
105463   ** operator.
105464   **
105465   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
105466   **
105467   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
105468   **
105469   ** The last character of the prefix "abc" is incremented to form the
105470   ** termination condition "abd".
105471   */
105472   if( pWC->op==TK_AND
105473    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
105474   ){
105475     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
105476     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
105477     Expr *pNewExpr1;
105478     Expr *pNewExpr2;
105479     int idxNew1;
105480     int idxNew2;
105481     Token sCollSeqName;  /* Name of collating sequence */
105482
105483     pLeft = pExpr->x.pList->a[1].pExpr;
105484     pStr2 = sqlite3ExprDup(db, pStr1, 0);
105485     if( !db->mallocFailed ){
105486       u8 c, *pC;       /* Last character before the first wildcard */
105487       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
105488       c = *pC;
105489       if( noCase ){
105490         /* The point is to increment the last character before the first
105491         ** wildcard.  But if we increment '@', that will push it into the
105492         ** alphabetic range where case conversions will mess up the
105493         ** inequality.  To avoid this, make sure to also run the full
105494         ** LIKE on all candidate expressions by clearing the isComplete flag
105495         */
105496         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
105497
105498
105499         c = sqlite3UpperToLower[c];
105500       }
105501       *pC = c + 1;
105502     }
105503     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
105504     sCollSeqName.n = 6;
105505     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
105506     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
105507            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
105508            pStr1, 0);
105509     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
105510     testcase( idxNew1==0 );
105511     exprAnalyze(pSrc, pWC, idxNew1);
105512     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
105513     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
105514            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
105515            pStr2, 0);
105516     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
105517     testcase( idxNew2==0 );
105518     exprAnalyze(pSrc, pWC, idxNew2);
105519     pTerm = &pWC->a[idxTerm];
105520     if( isComplete ){
105521       pWC->a[idxNew1].iParent = idxTerm;
105522       pWC->a[idxNew2].iParent = idxTerm;
105523       pTerm->nChild = 2;
105524     }
105525   }
105526 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
105527
105528 #ifndef SQLITE_OMIT_VIRTUALTABLE
105529   /* Add a WO_MATCH auxiliary term to the constraint set if the
105530   ** current expression is of the form:  column MATCH expr.
105531   ** This information is used by the xBestIndex methods of
105532   ** virtual tables.  The native query optimizer does not attempt
105533   ** to do anything with MATCH functions.
105534   */
105535   if( isMatchOfColumn(pExpr) ){
105536     int idxNew;
105537     Expr *pRight, *pLeft;
105538     WhereTerm *pNewTerm;
105539     Bitmask prereqColumn, prereqExpr;
105540
105541     pRight = pExpr->x.pList->a[0].pExpr;
105542     pLeft = pExpr->x.pList->a[1].pExpr;
105543     prereqExpr = exprTableUsage(pMaskSet, pRight);
105544     prereqColumn = exprTableUsage(pMaskSet, pLeft);
105545     if( (prereqExpr & prereqColumn)==0 ){
105546       Expr *pNewExpr;
105547       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
105548                               0, sqlite3ExprDup(db, pRight, 0), 0);
105549       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
105550       testcase( idxNew==0 );
105551       pNewTerm = &pWC->a[idxNew];
105552       pNewTerm->prereqRight = prereqExpr;
105553       pNewTerm->leftCursor = pLeft->iTable;
105554       pNewTerm->u.leftColumn = pLeft->iColumn;
105555       pNewTerm->eOperator = WO_MATCH;
105556       pNewTerm->iParent = idxTerm;
105557       pTerm = &pWC->a[idxTerm];
105558       pTerm->nChild = 1;
105559       pTerm->wtFlags |= TERM_COPIED;
105560       pNewTerm->prereqAll = pTerm->prereqAll;
105561     }
105562   }
105563 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105564
105565 #ifdef SQLITE_ENABLE_STAT3
105566   /* When sqlite_stat3 histogram data is available an operator of the
105567   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
105568   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
105569   ** virtual term of that form.
105570   **
105571   ** Note that the virtual term must be tagged with TERM_VNULL.  This
105572   ** TERM_VNULL tag will suppress the not-null check at the beginning
105573   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
105574   ** the start of the loop will prevent any results from being returned.
105575   */
105576   if( pExpr->op==TK_NOTNULL
105577    && pExpr->pLeft->op==TK_COLUMN
105578    && pExpr->pLeft->iColumn>=0
105579   ){
105580     Expr *pNewExpr;
105581     Expr *pLeft = pExpr->pLeft;
105582     int idxNew;
105583     WhereTerm *pNewTerm;
105584
105585     pNewExpr = sqlite3PExpr(pParse, TK_GT,
105586                             sqlite3ExprDup(db, pLeft, 0),
105587                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
105588
105589     idxNew = whereClauseInsert(pWC, pNewExpr,
105590                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
105591     if( idxNew ){
105592       pNewTerm = &pWC->a[idxNew];
105593       pNewTerm->prereqRight = 0;
105594       pNewTerm->leftCursor = pLeft->iTable;
105595       pNewTerm->u.leftColumn = pLeft->iColumn;
105596       pNewTerm->eOperator = WO_GT;
105597       pNewTerm->iParent = idxTerm;
105598       pTerm = &pWC->a[idxTerm];
105599       pTerm->nChild = 1;
105600       pTerm->wtFlags |= TERM_COPIED;
105601       pNewTerm->prereqAll = pTerm->prereqAll;
105602     }
105603   }
105604 #endif /* SQLITE_ENABLE_STAT */
105605
105606   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
105607   ** an index for tables to the left of the join.
105608   */
105609   pTerm->prereqRight |= extraRight;
105610 }
105611
105612 /*
105613 ** This function searches the expression list passed as the second argument
105614 ** for an expression of type TK_COLUMN that refers to the same column and
105615 ** uses the same collation sequence as the iCol'th column of index pIdx.
105616 ** Argument iBase is the cursor number used for the table that pIdx refers
105617 ** to.
105618 **
105619 ** If such an expression is found, its index in pList->a[] is returned. If
105620 ** no expression is found, -1 is returned.
105621 */
105622 static int findIndexCol(
105623   Parse *pParse,                  /* Parse context */
105624   ExprList *pList,                /* Expression list to search */
105625   int iBase,                      /* Cursor for table associated with pIdx */
105626   Index *pIdx,                    /* Index to match column of */
105627   int iCol                        /* Column of index to match */
105628 ){
105629   int i;
105630   const char *zColl = pIdx->azColl[iCol];
105631
105632   for(i=0; i<pList->nExpr; i++){
105633     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
105634     if( p->op==TK_COLUMN
105635      && p->iColumn==pIdx->aiColumn[iCol]
105636      && p->iTable==iBase
105637     ){
105638       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
105639       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
105640         return i;
105641       }
105642     }
105643   }
105644
105645   return -1;
105646 }
105647
105648 /*
105649 ** This routine determines if pIdx can be used to assist in processing a
105650 ** DISTINCT qualifier. In other words, it tests whether or not using this
105651 ** index for the outer loop guarantees that rows with equal values for
105652 ** all expressions in the pDistinct list are delivered grouped together.
105653 **
105654 ** For example, the query
105655 **
105656 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
105657 **
105658 ** can benefit from any index on columns "b" and "c".
105659 */
105660 static int isDistinctIndex(
105661   Parse *pParse,                  /* Parsing context */
105662   WhereClause *pWC,               /* The WHERE clause */
105663   Index *pIdx,                    /* The index being considered */
105664   int base,                       /* Cursor number for the table pIdx is on */
105665   ExprList *pDistinct,            /* The DISTINCT expressions */
105666   int nEqCol                      /* Number of index columns with == */
105667 ){
105668   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
105669   int i;                          /* Iterator variable */
105670
105671   assert( pDistinct!=0 );
105672   if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
105673   testcase( pDistinct->nExpr==BMS-1 );
105674
105675   /* Loop through all the expressions in the distinct list. If any of them
105676   ** are not simple column references, return early. Otherwise, test if the
105677   ** WHERE clause contains a "col=X" clause. If it does, the expression
105678   ** can be ignored. If it does not, and the column does not belong to the
105679   ** same table as index pIdx, return early. Finally, if there is no
105680   ** matching "col=X" expression and the column is on the same table as pIdx,
105681   ** set the corresponding bit in variable mask.
105682   */
105683   for(i=0; i<pDistinct->nExpr; i++){
105684     WhereTerm *pTerm;
105685     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
105686     if( p->op!=TK_COLUMN ) return 0;
105687     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
105688     if( pTerm ){
105689       Expr *pX = pTerm->pExpr;
105690       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
105691       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
105692       if( p1==p2 ) continue;
105693     }
105694     if( p->iTable!=base ) return 0;
105695     mask |= (((Bitmask)1) << i);
105696   }
105697
105698   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
105699     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
105700     if( iExpr<0 ) break;
105701     mask &= ~(((Bitmask)1) << iExpr);
105702   }
105703
105704   return (mask==0);
105705 }
105706
105707
105708 /*
105709 ** Return true if the DISTINCT expression-list passed as the third argument
105710 ** is redundant. A DISTINCT list is redundant if the database contains a
105711 ** UNIQUE index that guarantees that the result of the query will be distinct
105712 ** anyway.
105713 */
105714 static int isDistinctRedundant(
105715   Parse *pParse,
105716   SrcList *pTabList,
105717   WhereClause *pWC,
105718   ExprList *pDistinct
105719 ){
105720   Table *pTab;
105721   Index *pIdx;
105722   int i;
105723   int iBase;
105724
105725   /* If there is more than one table or sub-select in the FROM clause of
105726   ** this query, then it will not be possible to show that the DISTINCT
105727   ** clause is redundant. */
105728   if( pTabList->nSrc!=1 ) return 0;
105729   iBase = pTabList->a[0].iCursor;
105730   pTab = pTabList->a[0].pTab;
105731
105732   /* If any of the expressions is an IPK column on table iBase, then return
105733   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
105734   ** current SELECT is a correlated sub-query.
105735   */
105736   for(i=0; i<pDistinct->nExpr; i++){
105737     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
105738     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
105739   }
105740
105741   /* Loop through all indices on the table, checking each to see if it makes
105742   ** the DISTINCT qualifier redundant. It does so if:
105743   **
105744   **   1. The index is itself UNIQUE, and
105745   **
105746   **   2. All of the columns in the index are either part of the pDistinct
105747   **      list, or else the WHERE clause contains a term of the form "col=X",
105748   **      where X is a constant value. The collation sequences of the
105749   **      comparison and select-list expressions must match those of the index.
105750   **
105751   **   3. All of those index columns for which the WHERE clause does not
105752   **      contain a "col=X" term are subject to a NOT NULL constraint.
105753   */
105754   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
105755     if( pIdx->onError==OE_None ) continue;
105756     for(i=0; i<pIdx->nColumn; i++){
105757       int iCol = pIdx->aiColumn[i];
105758       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
105759         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
105760         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
105761           break;
105762         }
105763       }
105764     }
105765     if( i==pIdx->nColumn ){
105766       /* This index implies that the DISTINCT qualifier is redundant. */
105767       return 1;
105768     }
105769   }
105770
105771   return 0;
105772 }
105773
105774 /*
105775 ** Prepare a crude estimate of the logarithm of the input value.
105776 ** The results need not be exact.  This is only used for estimating
105777 ** the total cost of performing operations with O(logN) or O(NlogN)
105778 ** complexity.  Because N is just a guess, it is no great tragedy if
105779 ** logN is a little off.
105780 */
105781 static double estLog(double N){
105782   double logN = 1;
105783   double x = 10;
105784   while( N>x ){
105785     logN += 1;
105786     x *= 10;
105787   }
105788   return logN;
105789 }
105790
105791 /*
105792 ** Two routines for printing the content of an sqlite3_index_info
105793 ** structure.  Used for testing and debugging only.  If neither
105794 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
105795 ** are no-ops.
105796 */
105797 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
105798 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
105799   int i;
105800   if( !sqlite3WhereTrace ) return;
105801   for(i=0; i<p->nConstraint; i++){
105802     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
105803        i,
105804        p->aConstraint[i].iColumn,
105805        p->aConstraint[i].iTermOffset,
105806        p->aConstraint[i].op,
105807        p->aConstraint[i].usable);
105808   }
105809   for(i=0; i<p->nOrderBy; i++){
105810     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
105811        i,
105812        p->aOrderBy[i].iColumn,
105813        p->aOrderBy[i].desc);
105814   }
105815 }
105816 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
105817   int i;
105818   if( !sqlite3WhereTrace ) return;
105819   for(i=0; i<p->nConstraint; i++){
105820     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
105821        i,
105822        p->aConstraintUsage[i].argvIndex,
105823        p->aConstraintUsage[i].omit);
105824   }
105825   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
105826   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
105827   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
105828   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
105829 }
105830 #else
105831 #define TRACE_IDX_INPUTS(A)
105832 #define TRACE_IDX_OUTPUTS(A)
105833 #endif
105834
105835 /*
105836 ** Required because bestIndex() is called by bestOrClauseIndex()
105837 */
105838 static void bestIndex(WhereBestIdx*);
105839
105840 /*
105841 ** This routine attempts to find an scanning strategy that can be used
105842 ** to optimize an 'OR' expression that is part of a WHERE clause.
105843 **
105844 ** The table associated with FROM clause term pSrc may be either a
105845 ** regular B-Tree table or a virtual table.
105846 */
105847 static void bestOrClauseIndex(WhereBestIdx *p){
105848 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
105849   WhereClause *pWC = p->pWC;           /* The WHERE clause */
105850   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
105851   const int iCur = pSrc->iCursor;      /* The cursor of the table  */
105852   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
105853   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
105854   WhereTerm *pTerm;                    /* A single term of the WHERE clause */
105855
105856   /* The OR-clause optimization is disallowed if the INDEXED BY or
105857   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
105858   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
105859     return;
105860   }
105861   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
105862     return;
105863   }
105864
105865   /* Search the WHERE clause terms for a usable WO_OR term. */
105866   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
105867     if( pTerm->eOperator==WO_OR
105868      && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
105869      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
105870     ){
105871       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
105872       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
105873       WhereTerm *pOrTerm;
105874       int flags = WHERE_MULTI_OR;
105875       double rTotal = 0;
105876       double nRow = 0;
105877       Bitmask used = 0;
105878       WhereBestIdx sBOI;
105879
105880       sBOI = *p;
105881       sBOI.pOrderBy = 0;
105882       sBOI.pDistinct = 0;
105883       sBOI.ppIdxInfo = 0;
105884       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
105885         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
105886           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
105887         ));
105888         if( pOrTerm->eOperator==WO_AND ){
105889           sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
105890           bestIndex(&sBOI);
105891         }else if( pOrTerm->leftCursor==iCur ){
105892           WhereClause tempWC;
105893           tempWC.pParse = pWC->pParse;
105894           tempWC.pMaskSet = pWC->pMaskSet;
105895           tempWC.pOuter = pWC;
105896           tempWC.op = TK_AND;
105897           tempWC.a = pOrTerm;
105898           tempWC.wctrlFlags = 0;
105899           tempWC.nTerm = 1;
105900           sBOI.pWC = &tempWC;
105901           bestIndex(&sBOI);
105902         }else{
105903           continue;
105904         }
105905         rTotal += sBOI.cost.rCost;
105906         nRow += sBOI.cost.plan.nRow;
105907         used |= sBOI.cost.used;
105908         if( rTotal>=p->cost.rCost ) break;
105909       }
105910
105911       /* If there is an ORDER BY clause, increase the scan cost to account
105912       ** for the cost of the sort. */
105913       if( p->pOrderBy!=0 ){
105914         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
105915                     rTotal, rTotal+nRow*estLog(nRow)));
105916         rTotal += nRow*estLog(nRow);
105917       }
105918
105919       /* If the cost of scanning using this OR term for optimization is
105920       ** less than the current cost stored in pCost, replace the contents
105921       ** of pCost. */
105922       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
105923       if( rTotal<p->cost.rCost ){
105924         p->cost.rCost = rTotal;
105925         p->cost.used = used;
105926         p->cost.plan.nRow = nRow;
105927         p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
105928         p->cost.plan.wsFlags = flags;
105929         p->cost.plan.u.pTerm = pTerm;
105930       }
105931     }
105932   }
105933 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
105934 }
105935
105936 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
105937 /*
105938 ** Return TRUE if the WHERE clause term pTerm is of a form where it
105939 ** could be used with an index to access pSrc, assuming an appropriate
105940 ** index existed.
105941 */
105942 static int termCanDriveIndex(
105943   WhereTerm *pTerm,              /* WHERE clause term to check */
105944   struct SrcList_item *pSrc,     /* Table we are trying to access */
105945   Bitmask notReady               /* Tables in outer loops of the join */
105946 ){
105947   char aff;
105948   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
105949   if( pTerm->eOperator!=WO_EQ ) return 0;
105950   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
105951   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
105952   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
105953   return 1;
105954 }
105955 #endif
105956
105957 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
105958 /*
105959 ** If the query plan for pSrc specified in pCost is a full table scan
105960 ** and indexing is allows (if there is no NOT INDEXED clause) and it
105961 ** possible to construct a transient index that would perform better
105962 ** than a full table scan even when the cost of constructing the index
105963 ** is taken into account, then alter the query plan to use the
105964 ** transient index.
105965 */
105966 static void bestAutomaticIndex(WhereBestIdx *p){
105967   Parse *pParse = p->pParse;            /* The parsing context */
105968   WhereClause *pWC = p->pWC;            /* The WHERE clause */
105969   struct SrcList_item *pSrc = p->pSrc;  /* The FROM clause term to search */
105970   double nTableRow;                     /* Rows in the input table */
105971   double logN;                          /* log(nTableRow) */
105972   double costTempIdx;         /* per-query cost of the transient index */
105973   WhereTerm *pTerm;           /* A single term of the WHERE clause */
105974   WhereTerm *pWCEnd;          /* End of pWC->a[] */
105975   Table *pTable;              /* Table tht might be indexed */
105976
105977   if( pParse->nQueryLoop<=(double)1 ){
105978     /* There is no point in building an automatic index for a single scan */
105979     return;
105980   }
105981   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
105982     /* Automatic indices are disabled at run-time */
105983     return;
105984   }
105985   if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
105986    && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
105987   ){
105988     /* We already have some kind of index in use for this query. */
105989     return;
105990   }
105991   if( pSrc->viaCoroutine ){
105992     /* Cannot index a co-routine */
105993     return;
105994   }
105995   if( pSrc->notIndexed ){
105996     /* The NOT INDEXED clause appears in the SQL. */
105997     return;
105998   }
105999   if( pSrc->isCorrelated ){
106000     /* The source is a correlated sub-query. No point in indexing it. */
106001     return;
106002   }
106003
106004   assert( pParse->nQueryLoop >= (double)1 );
106005   pTable = pSrc->pTab;
106006   nTableRow = pTable->nRowEst;
106007   logN = estLog(nTableRow);
106008   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
106009   if( costTempIdx>=p->cost.rCost ){
106010     /* The cost of creating the transient table would be greater than
106011     ** doing the full table scan */
106012     return;
106013   }
106014
106015   /* Search for any equality comparison term */
106016   pWCEnd = &pWC->a[pWC->nTerm];
106017   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106018     if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
106019       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
106020                     p->cost.rCost, costTempIdx));
106021       p->cost.rCost = costTempIdx;
106022       p->cost.plan.nRow = logN + 1;
106023       p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
106024       p->cost.used = pTerm->prereqRight;
106025       break;
106026     }
106027   }
106028 }
106029 #else
106030 # define bestAutomaticIndex(A)  /* no-op */
106031 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106032
106033
106034 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106035 /*
106036 ** Generate code to construct the Index object for an automatic index
106037 ** and to set up the WhereLevel object pLevel so that the code generator
106038 ** makes use of the automatic index.
106039 */
106040 static void constructAutomaticIndex(
106041   Parse *pParse,              /* The parsing context */
106042   WhereClause *pWC,           /* The WHERE clause */
106043   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
106044   Bitmask notReady,           /* Mask of cursors that are not available */
106045   WhereLevel *pLevel          /* Write new index here */
106046 ){
106047   int nColumn;                /* Number of columns in the constructed index */
106048   WhereTerm *pTerm;           /* A single term of the WHERE clause */
106049   WhereTerm *pWCEnd;          /* End of pWC->a[] */
106050   int nByte;                  /* Byte of memory needed for pIdx */
106051   Index *pIdx;                /* Object describing the transient index */
106052   Vdbe *v;                    /* Prepared statement under construction */
106053   int addrInit;               /* Address of the initialization bypass jump */
106054   Table *pTable;              /* The table being indexed */
106055   KeyInfo *pKeyinfo;          /* Key information for the index */
106056   int addrTop;                /* Top of the index fill loop */
106057   int regRecord;              /* Register holding an index record */
106058   int n;                      /* Column counter */
106059   int i;                      /* Loop counter */
106060   int mxBitCol;               /* Maximum column in pSrc->colUsed */
106061   CollSeq *pColl;             /* Collating sequence to on a column */
106062   Bitmask idxCols;            /* Bitmap of columns used for indexing */
106063   Bitmask extraCols;          /* Bitmap of additional columns */
106064
106065   /* Generate code to skip over the creation and initialization of the
106066   ** transient index on 2nd and subsequent iterations of the loop. */
106067   v = pParse->pVdbe;
106068   assert( v!=0 );
106069   addrInit = sqlite3CodeOnce(pParse);
106070
106071   /* Count the number of columns that will be added to the index
106072   ** and used to match WHERE clause constraints */
106073   nColumn = 0;
106074   pTable = pSrc->pTab;
106075   pWCEnd = &pWC->a[pWC->nTerm];
106076   idxCols = 0;
106077   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106078     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106079       int iCol = pTerm->u.leftColumn;
106080       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106081       testcase( iCol==BMS );
106082       testcase( iCol==BMS-1 );
106083       if( (idxCols & cMask)==0 ){
106084         nColumn++;
106085         idxCols |= cMask;
106086       }
106087     }
106088   }
106089   assert( nColumn>0 );
106090   pLevel->plan.nEq = nColumn;
106091
106092   /* Count the number of additional columns needed to create a
106093   ** covering index.  A "covering index" is an index that contains all
106094   ** columns that are needed by the query.  With a covering index, the
106095   ** original table never needs to be accessed.  Automatic indices must
106096   ** be a covering index because the index will not be updated if the
106097   ** original table changes and the index and table cannot both be used
106098   ** if they go out of sync.
106099   */
106100   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
106101   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106102   testcase( pTable->nCol==BMS-1 );
106103   testcase( pTable->nCol==BMS-2 );
106104   for(i=0; i<mxBitCol; i++){
106105     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
106106   }
106107   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106108     nColumn += pTable->nCol - BMS + 1;
106109   }
106110   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
106111
106112   /* Construct the Index object to describe this index */
106113   nByte = sizeof(Index);
106114   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
106115   nByte += nColumn*sizeof(char*);   /* Index.azColl */
106116   nByte += nColumn;                 /* Index.aSortOrder */
106117   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106118   if( pIdx==0 ) return;
106119   pLevel->plan.u.pIdx = pIdx;
106120   pIdx->azColl = (char**)&pIdx[1];
106121   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106122   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106123   pIdx->zName = "auto-index";
106124   pIdx->nColumn = nColumn;
106125   pIdx->pTable = pTable;
106126   n = 0;
106127   idxCols = 0;
106128   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106129     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106130       int iCol = pTerm->u.leftColumn;
106131       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106132       if( (idxCols & cMask)==0 ){
106133         Expr *pX = pTerm->pExpr;
106134         idxCols |= cMask;
106135         pIdx->aiColumn[n] = pTerm->u.leftColumn;
106136         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
106137         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106138         n++;
106139       }
106140     }
106141   }
106142   assert( (u32)n==pLevel->plan.nEq );
106143
106144   /* Add additional columns needed to make the automatic index into
106145   ** a covering index */
106146   for(i=0; i<mxBitCol; i++){
106147     if( extraCols & (((Bitmask)1)<<i) ){
106148       pIdx->aiColumn[n] = i;
106149       pIdx->azColl[n] = "BINARY";
106150       n++;
106151     }
106152   }
106153   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106154     for(i=BMS-1; i<pTable->nCol; i++){
106155       pIdx->aiColumn[n] = i;
106156       pIdx->azColl[n] = "BINARY";
106157       n++;
106158     }
106159   }
106160   assert( n==nColumn );
106161
106162   /* Create the automatic index */
106163   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106164   assert( pLevel->iIdxCur>=0 );
106165   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106166                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106167   VdbeComment((v, "for %s", pTable->zName));
106168
106169   /* Fill the automatic index with content */
106170   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
106171   regRecord = sqlite3GetTempReg(pParse);
106172   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
106173   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
106174   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
106175   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
106176   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
106177   sqlite3VdbeJumpHere(v, addrTop);
106178   sqlite3ReleaseTempReg(pParse, regRecord);
106179
106180   /* Jump here when skipping the initialization */
106181   sqlite3VdbeJumpHere(v, addrInit);
106182 }
106183 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106184
106185 #ifndef SQLITE_OMIT_VIRTUALTABLE
106186 /*
106187 ** Allocate and populate an sqlite3_index_info structure. It is the
106188 ** responsibility of the caller to eventually release the structure
106189 ** by passing the pointer returned by this function to sqlite3_free().
106190 */
106191 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
106192   Parse *pParse = p->pParse;
106193   WhereClause *pWC = p->pWC;
106194   struct SrcList_item *pSrc = p->pSrc;
106195   ExprList *pOrderBy = p->pOrderBy;
106196   int i, j;
106197   int nTerm;
106198   struct sqlite3_index_constraint *pIdxCons;
106199   struct sqlite3_index_orderby *pIdxOrderBy;
106200   struct sqlite3_index_constraint_usage *pUsage;
106201   WhereTerm *pTerm;
106202   int nOrderBy;
106203   sqlite3_index_info *pIdxInfo;
106204
106205   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
106206
106207   /* Count the number of possible WHERE clause constraints referring
106208   ** to this virtual table */
106209   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106210     if( pTerm->leftCursor != pSrc->iCursor ) continue;
106211     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
106212     testcase( pTerm->eOperator==WO_IN );
106213     testcase( pTerm->eOperator==WO_ISNULL );
106214     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
106215     if( pTerm->wtFlags & TERM_VNULL ) continue;
106216     nTerm++;
106217   }
106218
106219   /* If the ORDER BY clause contains only columns in the current
106220   ** virtual table then allocate space for the aOrderBy part of
106221   ** the sqlite3_index_info structure.
106222   */
106223   nOrderBy = 0;
106224   if( pOrderBy ){
106225     int n = pOrderBy->nExpr;
106226     for(i=0; i<n; i++){
106227       Expr *pExpr = pOrderBy->a[i].pExpr;
106228       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
106229     }
106230     if( i==n){
106231       nOrderBy = n;
106232     }
106233   }
106234
106235   /* Allocate the sqlite3_index_info structure
106236   */
106237   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106238                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106239                            + sizeof(*pIdxOrderBy)*nOrderBy );
106240   if( pIdxInfo==0 ){
106241     sqlite3ErrorMsg(pParse, "out of memory");
106242     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
106243     return 0;
106244   }
106245
106246   /* Initialize the structure.  The sqlite3_index_info structure contains
106247   ** many fields that are declared "const" to prevent xBestIndex from
106248   ** changing them.  We have to do some funky casting in order to
106249   ** initialize those fields.
106250   */
106251   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
106252   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
106253   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
106254   *(int*)&pIdxInfo->nConstraint = nTerm;
106255   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
106256   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
106257   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
106258   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
106259                                                                    pUsage;
106260
106261   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106262     if( pTerm->leftCursor != pSrc->iCursor ) continue;
106263     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
106264     testcase( pTerm->eOperator==WO_IN );
106265     testcase( pTerm->eOperator==WO_ISNULL );
106266     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
106267     if( pTerm->wtFlags & TERM_VNULL ) continue;
106268     pIdxCons[j].iColumn = pTerm->u.leftColumn;
106269     pIdxCons[j].iTermOffset = i;
106270     pIdxCons[j].op = (u8)pTerm->eOperator;
106271     /* The direct assignment in the previous line is possible only because
106272     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
106273     ** following asserts verify this fact. */
106274     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
106275     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
106276     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
106277     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
106278     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
106279     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
106280     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
106281     j++;
106282   }
106283   for(i=0; i<nOrderBy; i++){
106284     Expr *pExpr = pOrderBy->a[i].pExpr;
106285     pIdxOrderBy[i].iColumn = pExpr->iColumn;
106286     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
106287   }
106288
106289   return pIdxInfo;
106290 }
106291
106292 /*
106293 ** The table object reference passed as the second argument to this function
106294 ** must represent a virtual table. This function invokes the xBestIndex()
106295 ** method of the virtual table with the sqlite3_index_info pointer passed
106296 ** as the argument.
106297 **
106298 ** If an error occurs, pParse is populated with an error message and a
106299 ** non-zero value is returned. Otherwise, 0 is returned and the output
106300 ** part of the sqlite3_index_info structure is left populated.
106301 **
106302 ** Whether or not an error is returned, it is the responsibility of the
106303 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
106304 ** that this is required.
106305 */
106306 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106307   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106308   int i;
106309   int rc;
106310
106311   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
106312   TRACE_IDX_INPUTS(p);
106313   rc = pVtab->pModule->xBestIndex(pVtab, p);
106314   TRACE_IDX_OUTPUTS(p);
106315
106316   if( rc!=SQLITE_OK ){
106317     if( rc==SQLITE_NOMEM ){
106318       pParse->db->mallocFailed = 1;
106319     }else if( !pVtab->zErrMsg ){
106320       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
106321     }else{
106322       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
106323     }
106324   }
106325   sqlite3_free(pVtab->zErrMsg);
106326   pVtab->zErrMsg = 0;
106327
106328   for(i=0; i<p->nConstraint; i++){
106329     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
106330       sqlite3ErrorMsg(pParse,
106331           "table %s: xBestIndex returned an invalid plan", pTab->zName);
106332     }
106333   }
106334
106335   return pParse->nErr;
106336 }
106337
106338
106339 /*
106340 ** Compute the best index for a virtual table.
106341 **
106342 ** The best index is computed by the xBestIndex method of the virtual
106343 ** table module.  This routine is really just a wrapper that sets up
106344 ** the sqlite3_index_info structure that is used to communicate with
106345 ** xBestIndex.
106346 **
106347 ** In a join, this routine might be called multiple times for the
106348 ** same virtual table.  The sqlite3_index_info structure is created
106349 ** and initialized on the first invocation and reused on all subsequent
106350 ** invocations.  The sqlite3_index_info structure is also used when
106351 ** code is generated to access the virtual table.  The whereInfoDelete()
106352 ** routine takes care of freeing the sqlite3_index_info structure after
106353 ** everybody has finished with it.
106354 */
106355 static void bestVirtualIndex(WhereBestIdx *p){
106356   Parse *pParse = p->pParse;      /* The parsing context */
106357   WhereClause *pWC = p->pWC;      /* The WHERE clause */
106358   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106359   Table *pTab = pSrc->pTab;
106360   sqlite3_index_info *pIdxInfo;
106361   struct sqlite3_index_constraint *pIdxCons;
106362   struct sqlite3_index_constraint_usage *pUsage;
106363   WhereTerm *pTerm;
106364   int i, j;
106365   int nOrderBy;
106366   double rCost;
106367
106368   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
106369   ** malloc in allocateIndexInfo() fails and this function returns leaving
106370   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
106371   */
106372   memset(&p->cost, 0, sizeof(p->cost));
106373   p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
106374
106375   /* If the sqlite3_index_info structure has not been previously
106376   ** allocated and initialized, then allocate and initialize it now.
106377   */
106378   pIdxInfo = *p->ppIdxInfo;
106379   if( pIdxInfo==0 ){
106380     *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
106381   }
106382   if( pIdxInfo==0 ){
106383     return;
106384   }
106385
106386   /* At this point, the sqlite3_index_info structure that pIdxInfo points
106387   ** to will have been initialized, either during the current invocation or
106388   ** during some prior invocation.  Now we just have to customize the
106389   ** details of pIdxInfo for the current invocation and pass it to
106390   ** xBestIndex.
106391   */
106392
106393   /* The module name must be defined. Also, by this point there must
106394   ** be a pointer to an sqlite3_vtab structure. Otherwise
106395   ** sqlite3ViewGetColumnNames() would have picked up the error.
106396   */
106397   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
106398   assert( sqlite3GetVTable(pParse->db, pTab) );
106399
106400   /* Set the aConstraint[].usable fields and initialize all
106401   ** output variables to zero.
106402   **
106403   ** aConstraint[].usable is true for constraints where the right-hand
106404   ** side contains only references to tables to the left of the current
106405   ** table.  In other words, if the constraint is of the form:
106406   **
106407   **           column = expr
106408   **
106409   ** and we are evaluating a join, then the constraint on column is
106410   ** only valid if all tables referenced in expr occur to the left
106411   ** of the table containing column.
106412   **
106413   ** The aConstraints[] array contains entries for all constraints
106414   ** on the current table.  That way we only have to compute it once
106415   ** even though we might try to pick the best index multiple times.
106416   ** For each attempt at picking an index, the order of tables in the
106417   ** join might be different so we have to recompute the usable flag
106418   ** each time.
106419   */
106420   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106421   pUsage = pIdxInfo->aConstraintUsage;
106422   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106423     j = pIdxCons->iTermOffset;
106424     pTerm = &pWC->a[j];
106425     pIdxCons->usable = (pTerm->prereqRight&p->notReady) ? 0 : 1;
106426   }
106427   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
106428   if( pIdxInfo->needToFreeIdxStr ){
106429     sqlite3_free(pIdxInfo->idxStr);
106430   }
106431   pIdxInfo->idxStr = 0;
106432   pIdxInfo->idxNum = 0;
106433   pIdxInfo->needToFreeIdxStr = 0;
106434   pIdxInfo->orderByConsumed = 0;
106435   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
106436   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
106437   nOrderBy = pIdxInfo->nOrderBy;
106438   if( !p->pOrderBy ){
106439     pIdxInfo->nOrderBy = 0;
106440   }
106441
106442   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
106443     return;
106444   }
106445
106446   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106447   for(i=0; i<pIdxInfo->nConstraint; i++){
106448     if( pUsage[i].argvIndex>0 ){
106449       p->cost.used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
106450     }
106451   }
106452
106453   /* If there is an ORDER BY clause, and the selected virtual table index
106454   ** does not satisfy it, increase the cost of the scan accordingly. This
106455   ** matches the processing for non-virtual tables in bestBtreeIndex().
106456   */
106457   rCost = pIdxInfo->estimatedCost;
106458   if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
106459     rCost += estLog(rCost)*rCost;
106460   }
106461
106462   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
106463   ** inital value of lowestCost in this loop. If it is, then the
106464   ** (cost<lowestCost) test below will never be true.
106465   **
106466   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
106467   ** is defined.
106468   */
106469   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
106470     p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
106471   }else{
106472     p->cost.rCost = rCost;
106473   }
106474   p->cost.plan.u.pVtabIdx = pIdxInfo;
106475   if( pIdxInfo->orderByConsumed ){
106476     p->cost.plan.wsFlags |= WHERE_ORDERED;
106477     p->cost.plan.nOBSat = nOrderBy;
106478   }else{
106479     p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106480   }
106481   p->cost.plan.nEq = 0;
106482   pIdxInfo->nOrderBy = nOrderBy;
106483
106484   /* Try to find a more efficient access pattern by using multiple indexes
106485   ** to optimize an OR expression within the WHERE clause.
106486   */
106487   bestOrClauseIndex(p);
106488 }
106489 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106490
106491 #ifdef SQLITE_ENABLE_STAT3
106492 /*
106493 ** Estimate the location of a particular key among all keys in an
106494 ** index.  Store the results in aStat as follows:
106495 **
106496 **    aStat[0]      Est. number of rows less than pVal
106497 **    aStat[1]      Est. number of rows equal to pVal
106498 **
106499 ** Return SQLITE_OK on success.
106500 */
106501 static int whereKeyStats(
106502   Parse *pParse,              /* Database connection */
106503   Index *pIdx,                /* Index to consider domain of */
106504   sqlite3_value *pVal,        /* Value to consider */
106505   int roundUp,                /* Round up if true.  Round down if false */
106506   tRowcnt *aStat              /* OUT: stats written here */
106507 ){
106508   tRowcnt n;
106509   IndexSample *aSample;
106510   int i, eType;
106511   int isEq = 0;
106512   i64 v;
106513   double r, rS;
106514
106515   assert( roundUp==0 || roundUp==1 );
106516   assert( pIdx->nSample>0 );
106517   if( pVal==0 ) return SQLITE_ERROR;
106518   n = pIdx->aiRowEst[0];
106519   aSample = pIdx->aSample;
106520   eType = sqlite3_value_type(pVal);
106521
106522   if( eType==SQLITE_INTEGER ){
106523     v = sqlite3_value_int64(pVal);
106524     r = (i64)v;
106525     for(i=0; i<pIdx->nSample; i++){
106526       if( aSample[i].eType==SQLITE_NULL ) continue;
106527       if( aSample[i].eType>=SQLITE_TEXT ) break;
106528       if( aSample[i].eType==SQLITE_INTEGER ){
106529         if( aSample[i].u.i>=v ){
106530           isEq = aSample[i].u.i==v;
106531           break;
106532         }
106533       }else{
106534         assert( aSample[i].eType==SQLITE_FLOAT );
106535         if( aSample[i].u.r>=r ){
106536           isEq = aSample[i].u.r==r;
106537           break;
106538         }
106539       }
106540     }
106541   }else if( eType==SQLITE_FLOAT ){
106542     r = sqlite3_value_double(pVal);
106543     for(i=0; i<pIdx->nSample; i++){
106544       if( aSample[i].eType==SQLITE_NULL ) continue;
106545       if( aSample[i].eType>=SQLITE_TEXT ) break;
106546       if( aSample[i].eType==SQLITE_FLOAT ){
106547         rS = aSample[i].u.r;
106548       }else{
106549         rS = aSample[i].u.i;
106550       }
106551       if( rS>=r ){
106552         isEq = rS==r;
106553         break;
106554       }
106555     }
106556   }else if( eType==SQLITE_NULL ){
106557     i = 0;
106558     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
106559   }else{
106560     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
106561     for(i=0; i<pIdx->nSample; i++){
106562       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
106563         break;
106564       }
106565     }
106566     if( i<pIdx->nSample ){
106567       sqlite3 *db = pParse->db;
106568       CollSeq *pColl;
106569       const u8 *z;
106570       if( eType==SQLITE_BLOB ){
106571         z = (const u8 *)sqlite3_value_blob(pVal);
106572         pColl = db->pDfltColl;
106573         assert( pColl->enc==SQLITE_UTF8 );
106574       }else{
106575         pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
106576         if( pColl==0 ){
106577           return SQLITE_ERROR;
106578         }
106579         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
106580         if( !z ){
106581           return SQLITE_NOMEM;
106582         }
106583         assert( z && pColl && pColl->xCmp );
106584       }
106585       n = sqlite3ValueBytes(pVal, pColl->enc);
106586
106587       for(; i<pIdx->nSample; i++){
106588         int c;
106589         int eSampletype = aSample[i].eType;
106590         if( eSampletype<eType ) continue;
106591         if( eSampletype!=eType ) break;
106592 #ifndef SQLITE_OMIT_UTF16
106593         if( pColl->enc!=SQLITE_UTF8 ){
106594           int nSample;
106595           char *zSample = sqlite3Utf8to16(
106596               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
106597           );
106598           if( !zSample ){
106599             assert( db->mallocFailed );
106600             return SQLITE_NOMEM;
106601           }
106602           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
106603           sqlite3DbFree(db, zSample);
106604         }else
106605 #endif
106606         {
106607           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
106608         }
106609         if( c>=0 ){
106610           if( c==0 ) isEq = 1;
106611           break;
106612         }
106613       }
106614     }
106615   }
106616
106617   /* At this point, aSample[i] is the first sample that is greater than
106618   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
106619   ** than pVal.  If aSample[i]==pVal, then isEq==1.
106620   */
106621   if( isEq ){
106622     assert( i<pIdx->nSample );
106623     aStat[0] = aSample[i].nLt;
106624     aStat[1] = aSample[i].nEq;
106625   }else{
106626     tRowcnt iLower, iUpper, iGap;
106627     if( i==0 ){
106628       iLower = 0;
106629       iUpper = aSample[0].nLt;
106630     }else{
106631       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
106632       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
106633     }
106634     aStat[1] = pIdx->avgEq;
106635     if( iLower>=iUpper ){
106636       iGap = 0;
106637     }else{
106638       iGap = iUpper - iLower;
106639     }
106640     if( roundUp ){
106641       iGap = (iGap*2)/3;
106642     }else{
106643       iGap = iGap/3;
106644     }
106645     aStat[0] = iLower + iGap;
106646   }
106647   return SQLITE_OK;
106648 }
106649 #endif /* SQLITE_ENABLE_STAT3 */
106650
106651 /*
106652 ** If expression pExpr represents a literal value, set *pp to point to
106653 ** an sqlite3_value structure containing the same value, with affinity
106654 ** aff applied to it, before returning. It is the responsibility of the
106655 ** caller to eventually release this structure by passing it to
106656 ** sqlite3ValueFree().
106657 **
106658 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
106659 ** is an SQL variable that currently has a non-NULL value bound to it,
106660 ** create an sqlite3_value structure containing this value, again with
106661 ** affinity aff applied to it, instead.
106662 **
106663 ** If neither of the above apply, set *pp to NULL.
106664 **
106665 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
106666 */
106667 #ifdef SQLITE_ENABLE_STAT3
106668 static int valueFromExpr(
106669   Parse *pParse,
106670   Expr *pExpr,
106671   u8 aff,
106672   sqlite3_value **pp
106673 ){
106674   if( pExpr->op==TK_VARIABLE
106675    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
106676   ){
106677     int iVar = pExpr->iColumn;
106678     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
106679     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
106680     return SQLITE_OK;
106681   }
106682   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
106683 }
106684 #endif
106685
106686 /*
106687 ** This function is used to estimate the number of rows that will be visited
106688 ** by scanning an index for a range of values. The range may have an upper
106689 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
106690 ** and lower bounds are represented by pLower and pUpper respectively. For
106691 ** example, assuming that index p is on t1(a):
106692 **
106693 **   ... FROM t1 WHERE a > ? AND a < ? ...
106694 **                    |_____|   |_____|
106695 **                       |         |
106696 **                     pLower    pUpper
106697 **
106698 ** If either of the upper or lower bound is not present, then NULL is passed in
106699 ** place of the corresponding WhereTerm.
106700 **
106701 ** The nEq parameter is passed the index of the index column subject to the
106702 ** range constraint. Or, equivalently, the number of equality constraints
106703 ** optimized by the proposed index scan. For example, assuming index p is
106704 ** on t1(a, b), and the SQL query is:
106705 **
106706 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
106707 **
106708 ** then nEq should be passed the value 1 (as the range restricted column,
106709 ** b, is the second left-most column of the index). Or, if the query is:
106710 **
106711 **   ... FROM t1 WHERE a > ? AND a < ? ...
106712 **
106713 ** then nEq should be passed 0.
106714 **
106715 ** The returned value is an integer divisor to reduce the estimated
106716 ** search space.  A return value of 1 means that range constraints are
106717 ** no help at all.  A return value of 2 means range constraints are
106718 ** expected to reduce the search space by half.  And so forth...
106719 **
106720 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
106721 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
106722 ** results in a return of 4 and a range constraint (x>? AND x<?) results
106723 ** in a return of 16.
106724 */
106725 static int whereRangeScanEst(
106726   Parse *pParse,       /* Parsing & code generating context */
106727   Index *p,            /* The index containing the range-compared column; "x" */
106728   int nEq,             /* index into p->aCol[] of the range-compared column */
106729   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
106730   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
106731   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
106732 ){
106733   int rc = SQLITE_OK;
106734
106735 #ifdef SQLITE_ENABLE_STAT3
106736
106737   if( nEq==0 && p->nSample ){
106738     sqlite3_value *pRangeVal;
106739     tRowcnt iLower = 0;
106740     tRowcnt iUpper = p->aiRowEst[0];
106741     tRowcnt a[2];
106742     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
106743
106744     if( pLower ){
106745       Expr *pExpr = pLower->pExpr->pRight;
106746       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
106747       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
106748       if( rc==SQLITE_OK
106749        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
106750       ){
106751         iLower = a[0];
106752         if( pLower->eOperator==WO_GT ) iLower += a[1];
106753       }
106754       sqlite3ValueFree(pRangeVal);
106755     }
106756     if( rc==SQLITE_OK && pUpper ){
106757       Expr *pExpr = pUpper->pExpr->pRight;
106758       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
106759       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
106760       if( rc==SQLITE_OK
106761        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
106762       ){
106763         iUpper = a[0];
106764         if( pUpper->eOperator==WO_LE ) iUpper += a[1];
106765       }
106766       sqlite3ValueFree(pRangeVal);
106767     }
106768     if( rc==SQLITE_OK ){
106769       if( iUpper<=iLower ){
106770         *pRangeDiv = (double)p->aiRowEst[0];
106771       }else{
106772         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
106773       }
106774       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
106775                   (u32)iLower, (u32)iUpper, *pRangeDiv));
106776       return SQLITE_OK;
106777     }
106778   }
106779 #else
106780   UNUSED_PARAMETER(pParse);
106781   UNUSED_PARAMETER(p);
106782   UNUSED_PARAMETER(nEq);
106783 #endif
106784   assert( pLower || pUpper );
106785   *pRangeDiv = (double)1;
106786   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
106787   if( pUpper ) *pRangeDiv *= (double)4;
106788   return rc;
106789 }
106790
106791 #ifdef SQLITE_ENABLE_STAT3
106792 /*
106793 ** Estimate the number of rows that will be returned based on
106794 ** an equality constraint x=VALUE and where that VALUE occurs in
106795 ** the histogram data.  This only works when x is the left-most
106796 ** column of an index and sqlite_stat3 histogram data is available
106797 ** for that index.  When pExpr==NULL that means the constraint is
106798 ** "x IS NULL" instead of "x=VALUE".
106799 **
106800 ** Write the estimated row count into *pnRow and return SQLITE_OK.
106801 ** If unable to make an estimate, leave *pnRow unchanged and return
106802 ** non-zero.
106803 **
106804 ** This routine can fail if it is unable to load a collating sequence
106805 ** required for string comparison, or if unable to allocate memory
106806 ** for a UTF conversion required for comparison.  The error is stored
106807 ** in the pParse structure.
106808 */
106809 static int whereEqualScanEst(
106810   Parse *pParse,       /* Parsing & code generating context */
106811   Index *p,            /* The index whose left-most column is pTerm */
106812   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
106813   double *pnRow        /* Write the revised row estimate here */
106814 ){
106815   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
106816   u8 aff;                   /* Column affinity */
106817   int rc;                   /* Subfunction return code */
106818   tRowcnt a[2];             /* Statistics */
106819
106820   assert( p->aSample!=0 );
106821   assert( p->nSample>0 );
106822   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
106823   if( pExpr ){
106824     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
106825     if( rc ) goto whereEqualScanEst_cancel;
106826   }else{
106827     pRhs = sqlite3ValueNew(pParse->db);
106828   }
106829   if( pRhs==0 ) return SQLITE_NOTFOUND;
106830   rc = whereKeyStats(pParse, p, pRhs, 0, a);
106831   if( rc==SQLITE_OK ){
106832     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
106833     *pnRow = a[1];
106834   }
106835 whereEqualScanEst_cancel:
106836   sqlite3ValueFree(pRhs);
106837   return rc;
106838 }
106839 #endif /* defined(SQLITE_ENABLE_STAT3) */
106840
106841 #ifdef SQLITE_ENABLE_STAT3
106842 /*
106843 ** Estimate the number of rows that will be returned based on
106844 ** an IN constraint where the right-hand side of the IN operator
106845 ** is a list of values.  Example:
106846 **
106847 **        WHERE x IN (1,2,3,4)
106848 **
106849 ** Write the estimated row count into *pnRow and return SQLITE_OK.
106850 ** If unable to make an estimate, leave *pnRow unchanged and return
106851 ** non-zero.
106852 **
106853 ** This routine can fail if it is unable to load a collating sequence
106854 ** required for string comparison, or if unable to allocate memory
106855 ** for a UTF conversion required for comparison.  The error is stored
106856 ** in the pParse structure.
106857 */
106858 static int whereInScanEst(
106859   Parse *pParse,       /* Parsing & code generating context */
106860   Index *p,            /* The index whose left-most column is pTerm */
106861   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
106862   double *pnRow        /* Write the revised row estimate here */
106863 ){
106864   int rc = SQLITE_OK;         /* Subfunction return code */
106865   double nEst;                /* Number of rows for a single term */
106866   double nRowEst = (double)0; /* New estimate of the number of rows */
106867   int i;                      /* Loop counter */
106868
106869   assert( p->aSample!=0 );
106870   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
106871     nEst = p->aiRowEst[0];
106872     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
106873     nRowEst += nEst;
106874   }
106875   if( rc==SQLITE_OK ){
106876     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
106877     *pnRow = nRowEst;
106878     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
106879   }
106880   return rc;
106881 }
106882 #endif /* defined(SQLITE_ENABLE_STAT3) */
106883
106884 /*
106885 ** Check to see if column iCol of the table with cursor iTab will appear
106886 ** in sorted order according to the current query plan.
106887 **
106888 ** Return values:
106889 **
106890 **    0   iCol is not ordered
106891 **    1   iCol has only a single value
106892 **    2   iCol is in ASC order
106893 **    3   iCol is in DESC order
106894 */
106895 static int isOrderedColumn(
106896   WhereBestIdx *p,
106897   int iTab,
106898   int iCol
106899 ){
106900   int i, j;
106901   WhereLevel *pLevel = &p->aLevel[p->i-1];
106902   Index *pIdx;
106903   u8 sortOrder;
106904   for(i=p->i-1; i>=0; i--, pLevel--){
106905     if( pLevel->iTabCur!=iTab ) continue;
106906     if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
106907       return 1;
106908     }
106909     assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
106910     if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
106911       if( iCol<0 ){
106912         sortOrder = 0;
106913         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
106914       }else{
106915         int n = pIdx->nColumn;
106916         for(j=0; j<n; j++){
106917           if( iCol==pIdx->aiColumn[j] ) break;
106918         }
106919         if( j>=n ) return 0;
106920         sortOrder = pIdx->aSortOrder[j];
106921         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
106922       }
106923     }else{
106924       if( iCol!=(-1) ) return 0;
106925       sortOrder = 0;
106926       testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
106927     }
106928     if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
106929       assert( sortOrder==0 || sortOrder==1 );
106930       testcase( sortOrder==1 );
106931       sortOrder = 1 - sortOrder;
106932     }
106933     return sortOrder+2;
106934   }
106935   return 0;
106936 }
106937
106938 /*
106939 ** This routine decides if pIdx can be used to satisfy the ORDER BY
106940 ** clause, either in whole or in part.  The return value is the
106941 ** cumulative number of terms in the ORDER BY clause that are satisfied
106942 ** by the index pIdx and other indices in outer loops.
106943 **
106944 ** The table being queried has a cursor number of "base".  pIdx is the
106945 ** index that is postulated for use to access the table.
106946 **
106947 ** The *pbRev value is set to 0 order 1 depending on whether or not
106948 ** pIdx should be run in the forward order or in reverse order.
106949 */
106950 static int isSortingIndex(
106951   WhereBestIdx *p,    /* Best index search context */
106952   Index *pIdx,        /* The index we are testing */
106953   int base,           /* Cursor number for the table to be sorted */
106954   int *pbRev          /* Set to 1 for reverse-order scan of pIdx */
106955 ){
106956   int i;                        /* Number of pIdx terms used */
106957   int j;                        /* Number of ORDER BY terms satisfied */
106958   int sortOrder = 2;            /* 0: forward.  1: backward.  2: unknown */
106959   int nTerm;                    /* Number of ORDER BY terms */
106960   struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
106961   Table *pTab = pIdx->pTable;   /* Table that owns index pIdx */
106962   ExprList *pOrderBy;           /* The ORDER BY clause */
106963   Parse *pParse = p->pParse;    /* Parser context */
106964   sqlite3 *db = pParse->db;     /* Database connection */
106965   int nPriorSat;                /* ORDER BY terms satisfied by outer loops */
106966   int seenRowid = 0;            /* True if an ORDER BY rowid term is seen */
106967   int uniqueNotNull;            /* pIdx is UNIQUE with all terms are NOT NULL */
106968
106969   if( p->i==0 ){
106970     nPriorSat = 0;
106971   }else{
106972     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
106973     if( (p->aLevel[p->i-1].plan.wsFlags & WHERE_ORDERED)==0 ){
106974       /* This loop cannot be ordered unless the next outer loop is
106975       ** also ordered */
106976       return nPriorSat;
106977     }
106978     if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
106979       /* Only look at the outer-most loop if the OrderByIdxJoin
106980       ** optimization is disabled */
106981       return nPriorSat;
106982     }
106983   }
106984   pOrderBy = p->pOrderBy;
106985   assert( pOrderBy!=0 );
106986   if( pIdx->bUnordered ){
106987     /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
106988     ** be used for sorting */
106989     return nPriorSat;
106990   }
106991   nTerm = pOrderBy->nExpr;
106992   uniqueNotNull = pIdx->onError!=OE_None;
106993   assert( nTerm>0 );
106994
106995   /* Argument pIdx must either point to a 'real' named index structure,
106996   ** or an index structure allocated on the stack by bestBtreeIndex() to
106997   ** represent the rowid index that is part of every table.  */
106998   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
106999
107000   /* Match terms of the ORDER BY clause against columns of
107001   ** the index.
107002   **
107003   ** Note that indices have pIdx->nColumn regular columns plus
107004   ** one additional column containing the rowid.  The rowid column
107005   ** of the index is also allowed to match against the ORDER BY
107006   ** clause.
107007   */
107008   j = nPriorSat;
107009   for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
107010     Expr *pOBExpr;          /* The expression of the ORDER BY pOBItem */
107011     CollSeq *pColl;         /* The collating sequence of pOBExpr */
107012     int termSortOrder;      /* Sort order for this term */
107013     int iColumn;            /* The i-th column of the index.  -1 for rowid */
107014     int iSortOrder;         /* 1 for DESC, 0 for ASC on the i-th index term */
107015     int isEq;               /* Subject to an == or IS NULL constraint */
107016     int isMatch;            /* ORDER BY term matches the index term */
107017     const char *zColl;      /* Name of collating sequence for i-th index term */
107018     WhereTerm *pConstraint; /* A constraint in the WHERE clause */
107019
107020     /* If the next term of the ORDER BY clause refers to anything other than
107021     ** a column in the "base" table, then this index will not be of any
107022     ** further use in handling the ORDER BY. */
107023     pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
107024     if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
107025       break;
107026     }
107027
107028     /* Find column number and collating sequence for the next entry
107029     ** in the index */
107030     if( pIdx->zName && i<pIdx->nColumn ){
107031       iColumn = pIdx->aiColumn[i];
107032       if( iColumn==pIdx->pTable->iPKey ){
107033         iColumn = -1;
107034       }
107035       iSortOrder = pIdx->aSortOrder[i];
107036       zColl = pIdx->azColl[i];
107037       assert( zColl!=0 );
107038     }else{
107039       iColumn = -1;
107040       iSortOrder = 0;
107041       zColl = 0;
107042     }
107043
107044     /* Check to see if the column number and collating sequence of the
107045     ** index match the column number and collating sequence of the ORDER BY
107046     ** clause entry.  Set isMatch to 1 if they both match. */
107047     if( pOBExpr->iColumn==iColumn ){
107048       if( zColl ){
107049         pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
107050         if( !pColl ) pColl = db->pDfltColl;
107051         isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
107052       }else{
107053         isMatch = 1;
107054       }
107055     }else{
107056       isMatch = 0;
107057     }
107058
107059     /* termSortOrder is 0 or 1 for whether or not the access loop should
107060     ** run forward or backwards (respectively) in order to satisfy this
107061     ** term of the ORDER BY clause. */
107062     assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
107063     assert( iSortOrder==0 || iSortOrder==1 );
107064     termSortOrder = iSortOrder ^ pOBItem->sortOrder;
107065
107066     /* If X is the column in the index and ORDER BY clause, check to see
107067     ** if there are any X= or X IS NULL constraints in the WHERE clause. */
107068     pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
107069                            WO_EQ|WO_ISNULL|WO_IN, pIdx);
107070     if( pConstraint==0 ){
107071       isEq = 0;
107072     }else if( pConstraint->eOperator==WO_IN ){
107073       /* Constraints of the form: "X IN ..." cannot be used with an ORDER BY
107074       ** because we do not know in what order the values on the RHS of the IN
107075       ** operator will occur. */
107076       break;
107077     }else if( pConstraint->eOperator==WO_ISNULL ){
107078       uniqueNotNull = 0;
107079       isEq = 1;  /* "X IS NULL" means X has only a single value */
107080     }else if( pConstraint->prereqRight==0 ){
107081       isEq = 1;  /* Constraint "X=constant" means X has only a single value */
107082     }else{
107083       Expr *pRight = pConstraint->pExpr->pRight;
107084       if( pRight->op==TK_COLUMN ){
107085         WHERETRACE(("       .. isOrderedColumn(tab=%d,col=%d)",
107086                     pRight->iTable, pRight->iColumn));
107087         isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
107088         WHERETRACE((" -> isEq=%d\n", isEq));
107089
107090         /* If the constraint is of the form X=Y where Y is an ordered value
107091         ** in an outer loop, then make sure the sort order of Y matches the
107092         ** sort order required for X. */
107093         if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
107094           testcase( isEq==2 );
107095           testcase( isEq==3 );
107096           break;
107097         }
107098       }else{
107099         isEq = 0;  /* "X=expr" places no ordering constraints on X */
107100       }
107101     }
107102     if( !isMatch ){
107103       if( isEq==0 ){
107104         break;
107105       }else{
107106         continue;
107107       }
107108     }else if( isEq!=1 ){
107109       if( sortOrder==2 ){
107110         sortOrder = termSortOrder;
107111       }else if( termSortOrder!=sortOrder ){
107112         break;
107113       }
107114     }
107115     j++;
107116     pOBItem++;
107117     if( iColumn<0 ){
107118       seenRowid = 1;
107119       break;
107120     }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
107121       testcase( isEq==0 );
107122       testcase( isEq==2 );
107123       testcase( isEq==3 );
107124       uniqueNotNull = 0;
107125     }
107126   }
107127
107128   /* If we have not found at least one ORDER BY term that matches the
107129   ** index, then show no progress. */
107130   if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
107131
107132   /* Return the necessary scan order back to the caller */
107133   *pbRev = sortOrder & 1;
107134
107135   /* If there was an "ORDER BY rowid" term that matched, or it is only
107136   ** possible for a single row from this table to match, then skip over
107137   ** any additional ORDER BY terms dealing with this table.
107138   */
107139   if( seenRowid || (uniqueNotNull && i>=pIdx->nColumn) ){
107140     /* Advance j over additional ORDER BY terms associated with base */
107141     WhereMaskSet *pMS = p->pWC->pMaskSet;
107142     Bitmask m = ~getMask(pMS, base);
107143     while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
107144       j++;
107145     }
107146   }
107147   return j;
107148 }
107149
107150 /*
107151 ** Find the best query plan for accessing a particular table.  Write the
107152 ** best query plan and its cost into the p->cost.
107153 **
107154 ** The lowest cost plan wins.  The cost is an estimate of the amount of
107155 ** CPU and disk I/O needed to process the requested result.
107156 ** Factors that influence cost include:
107157 **
107158 **    *  The estimated number of rows that will be retrieved.  (The
107159 **       fewer the better.)
107160 **
107161 **    *  Whether or not sorting must occur.
107162 **
107163 **    *  Whether or not there must be separate lookups in the
107164 **       index and in the main table.
107165 **
107166 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
107167 ** the SQL statement, then this function only considers plans using the
107168 ** named index. If no such plan is found, then the returned cost is
107169 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
107170 ** then the cost is calculated in the usual way.
107171 **
107172 ** If a NOT INDEXED clause was attached to the table
107173 ** in the SELECT statement, then no indexes are considered. However, the
107174 ** selected plan may still take advantage of the built-in rowid primary key
107175 ** index.
107176 */
107177 static void bestBtreeIndex(WhereBestIdx *p){
107178   Parse *pParse = p->pParse;  /* The parsing context */
107179   WhereClause *pWC = p->pWC;  /* The WHERE clause */
107180   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
107181   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
107182   Index *pProbe;              /* An index we are evaluating */
107183   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
107184   int eqTermMask;             /* Current mask of valid equality operators */
107185   int idxEqTermMask;          /* Index mask of valid equality operators */
107186   Index sPk;                  /* A fake index object for the primary key */
107187   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
107188   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
107189   int wsFlagMask;             /* Allowed flags in p->cost.plan.wsFlag */
107190   int nPriorSat;              /* ORDER BY terms satisfied by outer loops */
107191   int nOrderBy;               /* Number of ORDER BY terms */
107192   char bSortInit;             /* Initializer for bSort in inner loop */
107193   char bDistInit;             /* Initializer for bDist in inner loop */
107194
107195
107196   /* Initialize the cost to a worst-case value */
107197   memset(&p->cost, 0, sizeof(p->cost));
107198   p->cost.rCost = SQLITE_BIG_DBL;
107199
107200   /* If the pSrc table is the right table of a LEFT JOIN then we may not
107201   ** use an index to satisfy IS NULL constraints on that table.  This is
107202   ** because columns might end up being NULL if the table does not match -
107203   ** a circumstance which the index cannot help us discover.  Ticket #2177.
107204   */
107205   if( pSrc->jointype & JT_LEFT ){
107206     idxEqTermMask = WO_EQ|WO_IN;
107207   }else{
107208     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
107209   }
107210
107211   if( pSrc->pIndex ){
107212     /* An INDEXED BY clause specifies a particular index to use */
107213     pIdx = pProbe = pSrc->pIndex;
107214     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
107215     eqTermMask = idxEqTermMask;
107216   }else{
107217     /* There is no INDEXED BY clause.  Create a fake Index object in local
107218     ** variable sPk to represent the rowid primary key index.  Make this
107219     ** fake index the first in a chain of Index objects with all of the real
107220     ** indices to follow */
107221     Index *pFirst;                  /* First of real indices on the table */
107222     memset(&sPk, 0, sizeof(Index));
107223     sPk.nColumn = 1;
107224     sPk.aiColumn = &aiColumnPk;
107225     sPk.aiRowEst = aiRowEstPk;
107226     sPk.onError = OE_Replace;
107227     sPk.pTable = pSrc->pTab;
107228     aiRowEstPk[0] = pSrc->pTab->nRowEst;
107229     aiRowEstPk[1] = 1;
107230     pFirst = pSrc->pTab->pIndex;
107231     if( pSrc->notIndexed==0 ){
107232       /* The real indices of the table are only considered if the
107233       ** NOT INDEXED qualifier is omitted from the FROM clause */
107234       sPk.pNext = pFirst;
107235     }
107236     pProbe = &sPk;
107237     wsFlagMask = ~(
107238         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
107239     );
107240     eqTermMask = WO_EQ|WO_IN;
107241     pIdx = 0;
107242   }
107243
107244   nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
107245   if( p->i ){
107246     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107247     bSortInit = nPriorSat<nOrderBy;
107248     bDistInit = 0;
107249   }else{
107250     nPriorSat = 0;
107251     bSortInit = nOrderBy>0;
107252     bDistInit = p->pDistinct!=0;
107253   }
107254
107255   /* Loop over all indices looking for the best one to use
107256   */
107257   for(; pProbe; pIdx=pProbe=pProbe->pNext){
107258     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
107259     WhereCost pc;               /* Cost of using pProbe */
107260     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
107261
107262     /* The following variables are populated based on the properties of
107263     ** index being evaluated. They are then used to determine the expected
107264     ** cost and number of rows returned.
107265     **
107266     **  pc.plan.nEq:
107267     **    Number of equality terms that can be implemented using the index.
107268     **    In other words, the number of initial fields in the index that
107269     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
107270     **
107271     **  nInMul:
107272     **    The "in-multiplier". This is an estimate of how many seek operations
107273     **    SQLite must perform on the index in question. For example, if the
107274     **    WHERE clause is:
107275     **
107276     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
107277     **
107278     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
107279     **    set to 9. Given the same schema and either of the following WHERE
107280     **    clauses:
107281     **
107282     **      WHERE a =  1
107283     **      WHERE a >= 2
107284     **
107285     **    nInMul is set to 1.
107286     **
107287     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
107288     **    the sub-select is assumed to return 25 rows for the purposes of
107289     **    determining nInMul.
107290     **
107291     **  bInEst:
107292     **    Set to true if there was at least one "x IN (SELECT ...)" term used
107293     **    in determining the value of nInMul.  Note that the RHS of the
107294     **    IN operator must be a SELECT, not a value list, for this variable
107295     **    to be true.
107296     **
107297     **  rangeDiv:
107298     **    An estimate of a divisor by which to reduce the search space due
107299     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
107300     **    data, a single inequality reduces the search space to 1/4rd its
107301     **    original size (rangeDiv==4).  Two inequalities reduce the search
107302     **    space to 1/16th of its original size (rangeDiv==16).
107303     **
107304     **  bSort:
107305     **    Boolean. True if there is an ORDER BY clause that will require an
107306     **    external sort (i.e. scanning the index being evaluated will not
107307     **    correctly order records).
107308     **
107309     **  bDist:
107310     **    Boolean. True if there is a DISTINCT clause that will require an
107311     **    external btree.
107312     **
107313     **  bLookup:
107314     **    Boolean. True if a table lookup is required for each index entry
107315     **    visited.  In other words, true if this is not a covering index.
107316     **    This is always false for the rowid primary key index of a table.
107317     **    For other indexes, it is true unless all the columns of the table
107318     **    used by the SELECT statement are present in the index (such an
107319     **    index is sometimes described as a covering index).
107320     **    For example, given the index on (a, b), the second of the following
107321     **    two queries requires table b-tree lookups in order to find the value
107322     **    of column c, but the first does not because columns a and b are
107323     **    both available in the index.
107324     **
107325     **             SELECT a, b    FROM tbl WHERE a = 1;
107326     **             SELECT a, b, c FROM tbl WHERE a = 1;
107327     */
107328     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
107329     int nInMul = 1;               /* Number of distinct equalities to lookup */
107330     double rangeDiv = (double)1;  /* Estimated reduction in search space */
107331     int nBound = 0;               /* Number of range constraints seen */
107332     char bSort = bSortInit;       /* True if external sort required */
107333     char bDist = bDistInit;       /* True if index cannot help with DISTINCT */
107334     char bLookup = 0;             /* True if not a covering index */
107335     WhereTerm *pTerm;             /* A single term of the WHERE clause */
107336 #ifdef SQLITE_ENABLE_STAT3
107337     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
107338 #endif
107339
107340     WHERETRACE((
107341       "   %s(%s):\n",
107342       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
107343     ));
107344     memset(&pc, 0, sizeof(pc));
107345     pc.plan.nOBSat = nPriorSat;
107346
107347     /* Determine the values of pc.plan.nEq and nInMul */
107348     for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
107349       int j = pProbe->aiColumn[pc.plan.nEq];
107350       pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
107351       if( pTerm==0 ) break;
107352       pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
107353       testcase( pTerm->pWC!=pWC );
107354       if( pTerm->eOperator & WO_IN ){
107355         Expr *pExpr = pTerm->pExpr;
107356         pc.plan.wsFlags |= WHERE_COLUMN_IN;
107357         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107358           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
107359           nInMul *= 25;
107360           bInEst = 1;
107361         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
107362           /* "x IN (value, value, ...)" */
107363           nInMul *= pExpr->x.pList->nExpr;
107364         }
107365       }else if( pTerm->eOperator & WO_ISNULL ){
107366         pc.plan.wsFlags |= WHERE_COLUMN_NULL;
107367       }
107368 #ifdef SQLITE_ENABLE_STAT3
107369       if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
107370 #endif
107371       pc.used |= pTerm->prereqRight;
107372     }
107373
107374     /* If the index being considered is UNIQUE, and there is an equality
107375     ** constraint for all columns in the index, then this search will find
107376     ** at most a single row. In this case set the WHERE_UNIQUE flag to
107377     ** indicate this to the caller.
107378     **
107379     ** Otherwise, if the search may find more than one row, test to see if
107380     ** there is a range constraint on indexed column (pc.plan.nEq+1) that can be
107381     ** optimized using the index.
107382     */
107383     if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
107384       testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
107385       testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
107386       if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
107387         pc.plan.wsFlags |= WHERE_UNIQUE;
107388         if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107389           pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
107390         }
107391       }
107392     }else if( pProbe->bUnordered==0 ){
107393       int j;
107394       j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
107395       if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
107396         WhereTerm *pTop, *pBtm;
107397         pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
107398         pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
107399         whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
107400         if( pTop ){
107401           nBound = 1;
107402           pc.plan.wsFlags |= WHERE_TOP_LIMIT;
107403           pc.used |= pTop->prereqRight;
107404           testcase( pTop->pWC!=pWC );
107405         }
107406         if( pBtm ){
107407           nBound++;
107408           pc.plan.wsFlags |= WHERE_BTM_LIMIT;
107409           pc.used |= pBtm->prereqRight;
107410           testcase( pBtm->pWC!=pWC );
107411         }
107412         pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
107413       }
107414     }
107415
107416     /* If there is an ORDER BY clause and the index being considered will
107417     ** naturally scan rows in the required order, set the appropriate flags
107418     ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
107419     ** the index will scan rows in a different order, set the bSort
107420     ** variable.  */
107421     if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
107422       int bRev = 2;
107423       WHERETRACE(("      --> before isSortingIndex: nPriorSat=%d\n",nPriorSat));
107424       pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev);
107425       WHERETRACE(("      --> after  isSortingIndex: bRev=%d nOBSat=%d\n",
107426                   bRev, pc.plan.nOBSat));
107427       if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107428         pc.plan.wsFlags |= WHERE_ORDERED;
107429       }
107430       if( nOrderBy==pc.plan.nOBSat ){
107431         bSort = 0;
107432         pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
107433       }
107434       if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
107435     }
107436
107437     /* If there is a DISTINCT qualifier and this index will scan rows in
107438     ** order of the DISTINCT expressions, clear bDist and set the appropriate
107439     ** flags in pc.plan.wsFlags. */
107440     if( bDist
107441      && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
107442      && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
107443     ){
107444       bDist = 0;
107445       pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
107446     }
107447
107448     /* If currently calculating the cost of using an index (not the IPK
107449     ** index), determine if all required column data may be obtained without
107450     ** using the main table (i.e. if the index is a covering
107451     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
107452     ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true.  */
107453     if( pIdx ){
107454       Bitmask m = pSrc->colUsed;
107455       int j;
107456       for(j=0; j<pIdx->nColumn; j++){
107457         int x = pIdx->aiColumn[j];
107458         if( x<BMS-1 ){
107459           m &= ~(((Bitmask)1)<<x);
107460         }
107461       }
107462       if( m==0 ){
107463         pc.plan.wsFlags |= WHERE_IDX_ONLY;
107464       }else{
107465         bLookup = 1;
107466       }
107467     }
107468
107469     /*
107470     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
107471     ** constraint, do not let the estimate exceed half the rows in the table.
107472     */
107473     pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
107474     if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
107475       pc.plan.nRow = aiRowEst[0]/2;
107476       nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
107477     }
107478
107479 #ifdef SQLITE_ENABLE_STAT3
107480     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
107481     ** and we do not think that values of x are unique and if histogram
107482     ** data is available for column x, then it might be possible
107483     ** to get a better estimate on the number of rows based on
107484     ** VALUE and how common that value is according to the histogram.
107485     */
107486     if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
107487      && pFirstTerm!=0 && aiRowEst[1]>1 ){
107488       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
107489       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
107490         testcase( pFirstTerm->eOperator==WO_EQ );
107491         testcase( pFirstTerm->eOperator==WO_ISNULL );
107492         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
107493                           &pc.plan.nRow);
107494       }else if( bInEst==0 ){
107495         assert( pFirstTerm->eOperator==WO_IN );
107496         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
107497                        &pc.plan.nRow);
107498       }
107499     }
107500 #endif /* SQLITE_ENABLE_STAT3 */
107501
107502     /* Adjust the number of output rows and downward to reflect rows
107503     ** that are excluded by range constraints.
107504     */
107505     pc.plan.nRow = pc.plan.nRow/rangeDiv;
107506     if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
107507
107508     /* Experiments run on real SQLite databases show that the time needed
107509     ** to do a binary search to locate a row in a table or index is roughly
107510     ** log10(N) times the time to move from one row to the next row within
107511     ** a table or index.  The actual times can vary, with the size of
107512     ** records being an important factor.  Both moves and searches are
107513     ** slower with larger records, presumably because fewer records fit
107514     ** on one page and hence more pages have to be fetched.
107515     **
107516     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
107517     ** not give us data on the relative sizes of table and index records.
107518     ** So this computation assumes table records are about twice as big
107519     ** as index records
107520     */
107521     if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED))==WHERE_IDX_ONLY
107522      && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
107523      && sqlite3GlobalConfig.bUseCis
107524      && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
107525     ){
107526       /* This index is not useful for indexing, but it is a covering index.
107527       ** A full-scan of the index might be a little faster than a full-scan
107528       ** of the table, so give this case a cost slightly less than a table
107529       ** scan. */
107530       pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
107531       pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
107532     }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107533       /* The cost of a full table scan is a number of move operations equal
107534       ** to the number of rows in the table.
107535       **
107536       ** We add an additional 4x penalty to full table scans.  This causes
107537       ** the cost function to err on the side of choosing an index over
107538       ** choosing a full scan.  This 4x full-scan penalty is an arguable
107539       ** decision and one which we expect to revisit in the future.  But
107540       ** it seems to be working well enough at the moment.
107541       */
107542       pc.rCost = aiRowEst[0]*4;
107543       pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
107544       if( pIdx ){
107545         pc.plan.wsFlags &= ~WHERE_ORDERED;
107546         pc.plan.nOBSat = nPriorSat;
107547       }
107548     }else{
107549       log10N = estLog(aiRowEst[0]);
107550       pc.rCost = pc.plan.nRow;
107551       if( pIdx ){
107552         if( bLookup ){
107553           /* For an index lookup followed by a table lookup:
107554           **    nInMul index searches to find the start of each index range
107555           **  + nRow steps through the index
107556           **  + nRow table searches to lookup the table entry using the rowid
107557           */
107558           pc.rCost += (nInMul + pc.plan.nRow)*log10N;
107559         }else{
107560           /* For a covering index:
107561           **     nInMul index searches to find the initial entry
107562           **   + nRow steps through the index
107563           */
107564           pc.rCost += nInMul*log10N;
107565         }
107566       }else{
107567         /* For a rowid primary key lookup:
107568         **    nInMult table searches to find the initial entry for each range
107569         **  + nRow steps through the table
107570         */
107571         pc.rCost += nInMul*log10N;
107572       }
107573     }
107574
107575     /* Add in the estimated cost of sorting the result.  Actual experimental
107576     ** measurements of sorting performance in SQLite show that sorting time
107577     ** adds C*N*log10(N) to the cost, where N is the number of rows to be
107578     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
107579     ** difference and select C of 3.0.
107580     */
107581     if( bSort ){
107582       double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
107583       m *= (double)(pc.plan.nOBSat ? 2 : 3);
107584       pc.rCost += pc.plan.nRow*m;
107585     }
107586     if( bDist ){
107587       pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
107588     }
107589
107590     /**** Cost of using this index has now been computed ****/
107591
107592     /* If there are additional constraints on this table that cannot
107593     ** be used with the current index, but which might lower the number
107594     ** of output rows, adjust the nRow value accordingly.  This only
107595     ** matters if the current index is the least costly, so do not bother
107596     ** with this step if we already know this index will not be chosen.
107597     ** Also, never reduce the output row count below 2 using this step.
107598     **
107599     ** It is critical that the notValid mask be used here instead of
107600     ** the notReady mask.  When computing an "optimal" index, the notReady
107601     ** mask will only have one bit set - the bit for the current table.
107602     ** The notValid mask, on the other hand, always has all bits set for
107603     ** tables that are not in outer loops.  If notReady is used here instead
107604     ** of notValid, then a optimal index that depends on inner joins loops
107605     ** might be selected even when there exists an optimal index that has
107606     ** no such dependency.
107607     */
107608     if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
107609       int k;                       /* Loop counter */
107610       int nSkipEq = pc.plan.nEq;   /* Number of == constraints to skip */
107611       int nSkipRange = nBound;     /* Number of < constraints to skip */
107612       Bitmask thisTab;             /* Bitmap for pSrc */
107613
107614       thisTab = getMask(pWC->pMaskSet, iCur);
107615       for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
107616         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
107617         if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
107618         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
107619           if( nSkipEq ){
107620             /* Ignore the first pc.plan.nEq equality matches since the index
107621             ** has already accounted for these */
107622             nSkipEq--;
107623           }else{
107624             /* Assume each additional equality match reduces the result
107625             ** set size by a factor of 10 */
107626             pc.plan.nRow /= 10;
107627           }
107628         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
107629           if( nSkipRange ){
107630             /* Ignore the first nSkipRange range constraints since the index
107631             ** has already accounted for these */
107632             nSkipRange--;
107633           }else{
107634             /* Assume each additional range constraint reduces the result
107635             ** set size by a factor of 3.  Indexed range constraints reduce
107636             ** the search space by a larger factor: 4.  We make indexed range
107637             ** more selective intentionally because of the subjective
107638             ** observation that indexed range constraints really are more
107639             ** selective in practice, on average. */
107640             pc.plan.nRow /= 3;
107641           }
107642         }else if( pTerm->eOperator!=WO_NOOP ){
107643           /* Any other expression lowers the output row count by half */
107644           pc.plan.nRow /= 2;
107645         }
107646       }
107647       if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
107648     }
107649
107650
107651     WHERETRACE((
107652       "      nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
107653       "      notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
107654       "      used=0x%llx nOBSat=%d\n",
107655       pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
107656       p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
107657       pc.plan.nOBSat
107658     ));
107659
107660     /* If this index is the best we have seen so far, then record this
107661     ** index and its cost in the p->cost structure.
107662     */
107663     if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
107664       p->cost = pc;
107665       p->cost.plan.wsFlags &= wsFlagMask;
107666       p->cost.plan.u.pIdx = pIdx;
107667     }
107668
107669     /* If there was an INDEXED BY clause, then only that one index is
107670     ** considered. */
107671     if( pSrc->pIndex ) break;
107672
107673     /* Reset masks for the next index in the loop */
107674     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
107675     eqTermMask = idxEqTermMask;
107676   }
107677
107678   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
107679   ** is set, then reverse the order that the index will be scanned
107680   ** in. This is used for application testing, to help find cases
107681   ** where application behaviour depends on the (undefined) order that
107682   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
107683   if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
107684     p->cost.plan.wsFlags |= WHERE_REVERSE;
107685   }
107686
107687   assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
107688   assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
107689   assert( pSrc->pIndex==0
107690        || p->cost.plan.u.pIdx==0
107691        || p->cost.plan.u.pIdx==pSrc->pIndex
107692   );
107693
107694   WHERETRACE(("   best index is: %s\n",
107695          p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk"));
107696
107697   bestOrClauseIndex(p);
107698   bestAutomaticIndex(p);
107699   p->cost.plan.wsFlags |= eqTermMask;
107700 }
107701
107702 /*
107703 ** Find the query plan for accessing table pSrc->pTab. Write the
107704 ** best query plan and its cost into the WhereCost object supplied
107705 ** as the last parameter. This function may calculate the cost of
107706 ** both real and virtual table scans.
107707 **
107708 ** This function does not take ORDER BY or DISTINCT into account.  Nor
107709 ** does it remember the virtual table query plan.  All it does is compute
107710 ** the cost while determining if an OR optimization is applicable.  The
107711 ** details will be reconsidered later if the optimization is found to be
107712 ** applicable.
107713 */
107714 static void bestIndex(WhereBestIdx *p){
107715 #ifndef SQLITE_OMIT_VIRTUALTABLE
107716   if( IsVirtual(p->pSrc->pTab) ){
107717     sqlite3_index_info *pIdxInfo = 0;
107718     p->ppIdxInfo = &pIdxInfo;
107719     bestVirtualIndex(p);
107720     if( pIdxInfo->needToFreeIdxStr ){
107721       sqlite3_free(pIdxInfo->idxStr);
107722     }
107723     sqlite3DbFree(p->pParse->db, pIdxInfo);
107724   }else
107725 #endif
107726   {
107727     bestBtreeIndex(p);
107728   }
107729 }
107730
107731 /*
107732 ** Disable a term in the WHERE clause.  Except, do not disable the term
107733 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
107734 ** or USING clause of that join.
107735 **
107736 ** Consider the term t2.z='ok' in the following queries:
107737 **
107738 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
107739 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
107740 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
107741 **
107742 ** The t2.z='ok' is disabled in the in (2) because it originates
107743 ** in the ON clause.  The term is disabled in (3) because it is not part
107744 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
107745 **
107746 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
107747 ** completely satisfied by indices.
107748 **
107749 ** Disabling a term causes that term to not be tested in the inner loop
107750 ** of the join.  Disabling is an optimization.  When terms are satisfied
107751 ** by indices, we disable them to prevent redundant tests in the inner
107752 ** loop.  We would get the correct results if nothing were ever disabled,
107753 ** but joins might run a little slower.  The trick is to disable as much
107754 ** as we can without disabling too much.  If we disabled in (1), we'd get
107755 ** the wrong answer.  See ticket #813.
107756 */
107757 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
107758   if( pTerm
107759       && (pTerm->wtFlags & TERM_CODED)==0
107760       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
107761   ){
107762     pTerm->wtFlags |= TERM_CODED;
107763     if( pTerm->iParent>=0 ){
107764       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
107765       if( (--pOther->nChild)==0 ){
107766         disableTerm(pLevel, pOther);
107767       }
107768     }
107769   }
107770 }
107771
107772 /*
107773 ** Code an OP_Affinity opcode to apply the column affinity string zAff
107774 ** to the n registers starting at base.
107775 **
107776 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
107777 ** beginning and end of zAff are ignored.  If all entries in zAff are
107778 ** SQLITE_AFF_NONE, then no code gets generated.
107779 **
107780 ** This routine makes its own copy of zAff so that the caller is free
107781 ** to modify zAff after this routine returns.
107782 */
107783 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
107784   Vdbe *v = pParse->pVdbe;
107785   if( zAff==0 ){
107786     assert( pParse->db->mallocFailed );
107787     return;
107788   }
107789   assert( v!=0 );
107790
107791   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
107792   ** and end of the affinity string.
107793   */
107794   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
107795     n--;
107796     base++;
107797     zAff++;
107798   }
107799   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
107800     n--;
107801   }
107802
107803   /* Code the OP_Affinity opcode if there is anything left to do. */
107804   if( n>0 ){
107805     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
107806     sqlite3VdbeChangeP4(v, -1, zAff, n);
107807     sqlite3ExprCacheAffinityChange(pParse, base, n);
107808   }
107809 }
107810
107811
107812 /*
107813 ** Generate code for a single equality term of the WHERE clause.  An equality
107814 ** term can be either X=expr or X IN (...).   pTerm is the term to be
107815 ** coded.
107816 **
107817 ** The current value for the constraint is left in register iReg.
107818 **
107819 ** For a constraint of the form X=expr, the expression is evaluated and its
107820 ** result is left on the stack.  For constraints of the form X IN (...)
107821 ** this routine sets up a loop that will iterate over all values of X.
107822 */
107823 static int codeEqualityTerm(
107824   Parse *pParse,      /* The parsing context */
107825   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
107826   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
107827   int iTarget         /* Attempt to leave results in this register */
107828 ){
107829   Expr *pX = pTerm->pExpr;
107830   Vdbe *v = pParse->pVdbe;
107831   int iReg;                  /* Register holding results */
107832
107833   assert( iTarget>0 );
107834   if( pX->op==TK_EQ ){
107835     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
107836   }else if( pX->op==TK_ISNULL ){
107837     iReg = iTarget;
107838     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
107839 #ifndef SQLITE_OMIT_SUBQUERY
107840   }else{
107841     int eType;
107842     int iTab;
107843     struct InLoop *pIn;
107844
107845     assert( pX->op==TK_IN );
107846     iReg = iTarget;
107847     eType = sqlite3FindInIndex(pParse, pX, 0);
107848     iTab = pX->iTable;
107849     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
107850     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
107851     if( pLevel->u.in.nIn==0 ){
107852       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107853     }
107854     pLevel->u.in.nIn++;
107855     pLevel->u.in.aInLoop =
107856        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
107857                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
107858     pIn = pLevel->u.in.aInLoop;
107859     if( pIn ){
107860       pIn += pLevel->u.in.nIn - 1;
107861       pIn->iCur = iTab;
107862       if( eType==IN_INDEX_ROWID ){
107863         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
107864       }else{
107865         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
107866       }
107867       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
107868     }else{
107869       pLevel->u.in.nIn = 0;
107870     }
107871 #endif
107872   }
107873   disableTerm(pLevel, pTerm);
107874   return iReg;
107875 }
107876
107877 /*
107878 ** Generate code that will evaluate all == and IN constraints for an
107879 ** index.
107880 **
107881 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
107882 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
107883 ** The index has as many as three equality constraints, but in this
107884 ** example, the third "c" value is an inequality.  So only two
107885 ** constraints are coded.  This routine will generate code to evaluate
107886 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
107887 ** in consecutive registers and the index of the first register is returned.
107888 **
107889 ** In the example above nEq==2.  But this subroutine works for any value
107890 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
107891 ** The only thing it does is allocate the pLevel->iMem memory cell and
107892 ** compute the affinity string.
107893 **
107894 ** This routine always allocates at least one memory cell and returns
107895 ** the index of that memory cell. The code that
107896 ** calls this routine will use that memory cell to store the termination
107897 ** key value of the loop.  If one or more IN operators appear, then
107898 ** this routine allocates an additional nEq memory cells for internal
107899 ** use.
107900 **
107901 ** Before returning, *pzAff is set to point to a buffer containing a
107902 ** copy of the column affinity string of the index allocated using
107903 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
107904 ** with equality constraints that use NONE affinity are set to
107905 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
107906 **
107907 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
107908 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
107909 **
107910 ** In the example above, the index on t1(a) has TEXT affinity. But since
107911 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
107912 ** no conversion should be attempted before using a t2.b value as part of
107913 ** a key to search the index. Hence the first byte in the returned affinity
107914 ** string in this example would be set to SQLITE_AFF_NONE.
107915 */
107916 static int codeAllEqualityTerms(
107917   Parse *pParse,        /* Parsing context */
107918   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
107919   WhereClause *pWC,     /* The WHERE clause */
107920   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
107921   int nExtraReg,        /* Number of extra registers to allocate */
107922   char **pzAff          /* OUT: Set to point to affinity string */
107923 ){
107924   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
107925   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
107926   Index *pIdx;                  /* The index being used for this loop */
107927   int iCur = pLevel->iTabCur;   /* The cursor of the table */
107928   WhereTerm *pTerm;             /* A single constraint term */
107929   int j;                        /* Loop counter */
107930   int regBase;                  /* Base register */
107931   int nReg;                     /* Number of registers to allocate */
107932   char *zAff;                   /* Affinity string to return */
107933
107934   /* This module is only called on query plans that use an index. */
107935   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
107936   pIdx = pLevel->plan.u.pIdx;
107937
107938   /* Figure out how many memory cells we will need then allocate them.
107939   */
107940   regBase = pParse->nMem + 1;
107941   nReg = pLevel->plan.nEq + nExtraReg;
107942   pParse->nMem += nReg;
107943
107944   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
107945   if( !zAff ){
107946     pParse->db->mallocFailed = 1;
107947   }
107948
107949   /* Evaluate the equality constraints
107950   */
107951   assert( pIdx->nColumn>=nEq );
107952   for(j=0; j<nEq; j++){
107953     int r1;
107954     int k = pIdx->aiColumn[j];
107955     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
107956     if( pTerm==0 ) break;
107957     /* The following true for indices with redundant columns.
107958     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
107959     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
107960     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107961     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
107962     if( r1!=regBase+j ){
107963       if( nReg==1 ){
107964         sqlite3ReleaseTempReg(pParse, regBase);
107965         regBase = r1;
107966       }else{
107967         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
107968       }
107969     }
107970     testcase( pTerm->eOperator & WO_ISNULL );
107971     testcase( pTerm->eOperator & WO_IN );
107972     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
107973       Expr *pRight = pTerm->pExpr->pRight;
107974       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
107975       if( zAff ){
107976         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
107977           zAff[j] = SQLITE_AFF_NONE;
107978         }
107979         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
107980           zAff[j] = SQLITE_AFF_NONE;
107981         }
107982       }
107983     }
107984   }
107985   *pzAff = zAff;
107986   return regBase;
107987 }
107988
107989 #ifndef SQLITE_OMIT_EXPLAIN
107990 /*
107991 ** This routine is a helper for explainIndexRange() below
107992 **
107993 ** pStr holds the text of an expression that we are building up one term
107994 ** at a time.  This routine adds a new term to the end of the expression.
107995 ** Terms are separated by AND so add the "AND" text for second and subsequent
107996 ** terms only.
107997 */
107998 static void explainAppendTerm(
107999   StrAccum *pStr,             /* The text expression being built */
108000   int iTerm,                  /* Index of this term.  First is zero */
108001   const char *zColumn,        /* Name of the column */
108002   const char *zOp             /* Name of the operator */
108003 ){
108004   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
108005   sqlite3StrAccumAppend(pStr, zColumn, -1);
108006   sqlite3StrAccumAppend(pStr, zOp, 1);
108007   sqlite3StrAccumAppend(pStr, "?", 1);
108008 }
108009
108010 /*
108011 ** Argument pLevel describes a strategy for scanning table pTab. This
108012 ** function returns a pointer to a string buffer containing a description
108013 ** of the subset of table rows scanned by the strategy in the form of an
108014 ** SQL expression. Or, if all rows are scanned, NULL is returned.
108015 **
108016 ** For example, if the query:
108017 **
108018 **   SELECT * FROM t1 WHERE a=1 AND b>2;
108019 **
108020 ** is run and there is an index on (a, b), then this function returns a
108021 ** string similar to:
108022 **
108023 **   "a=? AND b>?"
108024 **
108025 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
108026 ** It is the responsibility of the caller to free the buffer when it is
108027 ** no longer required.
108028 */
108029 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
108030   WherePlan *pPlan = &pLevel->plan;
108031   Index *pIndex = pPlan->u.pIdx;
108032   int nEq = pPlan->nEq;
108033   int i, j;
108034   Column *aCol = pTab->aCol;
108035   int *aiColumn = pIndex->aiColumn;
108036   StrAccum txt;
108037
108038   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
108039     return 0;
108040   }
108041   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
108042   txt.db = db;
108043   sqlite3StrAccumAppend(&txt, " (", 2);
108044   for(i=0; i<nEq; i++){
108045     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
108046   }
108047
108048   j = i;
108049   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
108050     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108051     explainAppendTerm(&txt, i++, z, ">");
108052   }
108053   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
108054     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108055     explainAppendTerm(&txt, i, z, "<");
108056   }
108057   sqlite3StrAccumAppend(&txt, ")", 1);
108058   return sqlite3StrAccumFinish(&txt);
108059 }
108060
108061 /*
108062 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
108063 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
108064 ** record is added to the output to describe the table scan strategy in
108065 ** pLevel.
108066 */
108067 static void explainOneScan(
108068   Parse *pParse,                  /* Parse context */
108069   SrcList *pTabList,              /* Table list this loop refers to */
108070   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
108071   int iLevel,                     /* Value for "level" column of output */
108072   int iFrom,                      /* Value for "from" column of output */
108073   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
108074 ){
108075   if( pParse->explain==2 ){
108076     u32 flags = pLevel->plan.wsFlags;
108077     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
108078     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
108079     sqlite3 *db = pParse->db;     /* Database handle */
108080     char *zMsg;                   /* Text to add to EQP output */
108081     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
108082     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
108083     int isSearch;                 /* True for a SEARCH. False for SCAN. */
108084
108085     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
108086
108087     isSearch = (pLevel->plan.nEq>0)
108088              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
108089              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
108090
108091     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
108092     if( pItem->pSelect ){
108093       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
108094     }else{
108095       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
108096     }
108097
108098     if( pItem->zAlias ){
108099       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
108100     }
108101     if( (flags & WHERE_INDEXED)!=0 ){
108102       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
108103       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
108104           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
108105           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
108106           ((flags & WHERE_TEMP_INDEX)?"":" "),
108107           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
108108           zWhere
108109       );
108110       sqlite3DbFree(db, zWhere);
108111     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
108112       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
108113
108114       if( flags&WHERE_ROWID_EQ ){
108115         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
108116       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
108117         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
108118       }else if( flags&WHERE_BTM_LIMIT ){
108119         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
108120       }else if( flags&WHERE_TOP_LIMIT ){
108121         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
108122       }
108123     }
108124 #ifndef SQLITE_OMIT_VIRTUALTABLE
108125     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
108126       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108127       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
108128                   pVtabIdx->idxNum, pVtabIdx->idxStr);
108129     }
108130 #endif
108131     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
108132       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
108133       nRow = 1;
108134     }else{
108135       nRow = (sqlite3_int64)pLevel->plan.nRow;
108136     }
108137     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
108138     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
108139   }
108140 }
108141 #else
108142 # define explainOneScan(u,v,w,x,y,z)
108143 #endif /* SQLITE_OMIT_EXPLAIN */
108144
108145
108146 /*
108147 ** Generate code for the start of the iLevel-th loop in the WHERE clause
108148 ** implementation described by pWInfo.
108149 */
108150 static Bitmask codeOneLoopStart(
108151   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
108152   int iLevel,          /* Which level of pWInfo->a[] should be coded */
108153   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
108154   Bitmask notReady     /* Which tables are currently available */
108155 ){
108156   int j, k;            /* Loop counters */
108157   int iCur;            /* The VDBE cursor for the table */
108158   int addrNxt;         /* Where to jump to continue with the next IN case */
108159   int omitTable;       /* True if we use the index only */
108160   int bRev;            /* True if we need to scan in reverse order */
108161   WhereLevel *pLevel;  /* The where level to be coded */
108162   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
108163   WhereTerm *pTerm;               /* A WHERE clause term */
108164   Parse *pParse;                  /* Parsing context */
108165   Vdbe *v;                        /* The prepared stmt under constructions */
108166   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
108167   int addrBrk;                    /* Jump here to break out of the loop */
108168   int addrCont;                   /* Jump here to continue with next cycle */
108169   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
108170   int iReleaseReg = 0;      /* Temp register to free before returning */
108171
108172   pParse = pWInfo->pParse;
108173   v = pParse->pVdbe;
108174   pWC = pWInfo->pWC;
108175   pLevel = &pWInfo->a[iLevel];
108176   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
108177   iCur = pTabItem->iCursor;
108178   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108179   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
108180            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
108181
108182   /* Create labels for the "break" and "continue" instructions
108183   ** for the current loop.  Jump to addrBrk to break out of a loop.
108184   ** Jump to cont to go immediately to the next iteration of the
108185   ** loop.
108186   **
108187   ** When there is an IN operator, we also have a "addrNxt" label that
108188   ** means to continue with the next IN value combination.  When
108189   ** there are no IN operators in the constraints, the "addrNxt" label
108190   ** is the same as "addrBrk".
108191   */
108192   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108193   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
108194
108195   /* If this is the right table of a LEFT OUTER JOIN, allocate and
108196   ** initialize a memory cell that records if this table matches any
108197   ** row of the left table of the join.
108198   */
108199   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
108200     pLevel->iLeftJoin = ++pParse->nMem;
108201     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
108202     VdbeComment((v, "init LEFT JOIN no-match flag"));
108203   }
108204
108205   /* Special case of a FROM clause subquery implemented as a co-routine */
108206   if( pTabItem->viaCoroutine ){
108207     int regYield = pTabItem->regReturn;
108208     sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
108209     pLevel->p2 =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
108210     VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
108211     sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
108212     pLevel->op = OP_Goto;
108213   }else
108214
108215 #ifndef SQLITE_OMIT_VIRTUALTABLE
108216   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108217     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
108218     **          to access the data.
108219     */
108220     int iReg;   /* P3 Value for OP_VFilter */
108221     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108222     int nConstraint = pVtabIdx->nConstraint;
108223     struct sqlite3_index_constraint_usage *aUsage =
108224                                                 pVtabIdx->aConstraintUsage;
108225     const struct sqlite3_index_constraint *aConstraint =
108226                                                 pVtabIdx->aConstraint;
108227
108228     sqlite3ExprCachePush(pParse);
108229     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
108230     for(j=1; j<=nConstraint; j++){
108231       for(k=0; k<nConstraint; k++){
108232         if( aUsage[k].argvIndex==j ){
108233           int iTerm = aConstraint[k].iTermOffset;
108234           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
108235           break;
108236         }
108237       }
108238       if( k==nConstraint ) break;
108239     }
108240     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
108241     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
108242     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
108243                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
108244     pVtabIdx->needToFreeIdxStr = 0;
108245     for(j=0; j<nConstraint; j++){
108246       if( aUsage[j].omit ){
108247         int iTerm = aConstraint[j].iTermOffset;
108248         disableTerm(pLevel, &pWC->a[iTerm]);
108249       }
108250     }
108251     pLevel->op = OP_VNext;
108252     pLevel->p1 = iCur;
108253     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108254     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
108255     sqlite3ExprCachePop(pParse, 1);
108256   }else
108257 #endif /* SQLITE_OMIT_VIRTUALTABLE */
108258
108259   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
108260     /* Case 1:  We can directly reference a single row using an
108261     **          equality comparison against the ROWID field.  Or
108262     **          we reference multiple rows using a "rowid IN (...)"
108263     **          construct.
108264     */
108265     iReleaseReg = sqlite3GetTempReg(pParse);
108266     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
108267     assert( pTerm!=0 );
108268     assert( pTerm->pExpr!=0 );
108269     assert( pTerm->leftCursor==iCur );
108270     assert( omitTable==0 );
108271     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108272     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
108273     addrNxt = pLevel->addrNxt;
108274     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
108275     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
108276     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108277     VdbeComment((v, "pk"));
108278     pLevel->op = OP_Noop;
108279   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
108280     /* Case 2:  We have an inequality comparison against the ROWID field.
108281     */
108282     int testOp = OP_Noop;
108283     int start;
108284     int memEndValue = 0;
108285     WhereTerm *pStart, *pEnd;
108286
108287     assert( omitTable==0 );
108288     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
108289     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
108290     if( bRev ){
108291       pTerm = pStart;
108292       pStart = pEnd;
108293       pEnd = pTerm;
108294     }
108295     if( pStart ){
108296       Expr *pX;             /* The expression that defines the start bound */
108297       int r1, rTemp;        /* Registers for holding the start boundary */
108298
108299       /* The following constant maps TK_xx codes into corresponding
108300       ** seek opcodes.  It depends on a particular ordering of TK_xx
108301       */
108302       const u8 aMoveOp[] = {
108303            /* TK_GT */  OP_SeekGt,
108304            /* TK_LE */  OP_SeekLe,
108305            /* TK_LT */  OP_SeekLt,
108306            /* TK_GE */  OP_SeekGe
108307       };
108308       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
108309       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
108310       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
108311
108312       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108313       pX = pStart->pExpr;
108314       assert( pX!=0 );
108315       assert( pStart->leftCursor==iCur );
108316       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
108317       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
108318       VdbeComment((v, "pk"));
108319       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
108320       sqlite3ReleaseTempReg(pParse, rTemp);
108321       disableTerm(pLevel, pStart);
108322     }else{
108323       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
108324     }
108325     if( pEnd ){
108326       Expr *pX;
108327       pX = pEnd->pExpr;
108328       assert( pX!=0 );
108329       assert( pEnd->leftCursor==iCur );
108330       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108331       memEndValue = ++pParse->nMem;
108332       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
108333       if( pX->op==TK_LT || pX->op==TK_GT ){
108334         testOp = bRev ? OP_Le : OP_Ge;
108335       }else{
108336         testOp = bRev ? OP_Lt : OP_Gt;
108337       }
108338       disableTerm(pLevel, pEnd);
108339     }
108340     start = sqlite3VdbeCurrentAddr(v);
108341     pLevel->op = bRev ? OP_Prev : OP_Next;
108342     pLevel->p1 = iCur;
108343     pLevel->p2 = start;
108344     if( pStart==0 && pEnd==0 ){
108345       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108346     }else{
108347       assert( pLevel->p5==0 );
108348     }
108349     if( testOp!=OP_Noop ){
108350       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108351       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
108352       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108353       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
108354       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
108355     }
108356   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
108357     /* Case 3: A scan using an index.
108358     **
108359     **         The WHERE clause may contain zero or more equality
108360     **         terms ("==" or "IN" operators) that refer to the N
108361     **         left-most columns of the index. It may also contain
108362     **         inequality constraints (>, <, >= or <=) on the indexed
108363     **         column that immediately follows the N equalities. Only
108364     **         the right-most column can be an inequality - the rest must
108365     **         use the "==" and "IN" operators. For example, if the
108366     **         index is on (x,y,z), then the following clauses are all
108367     **         optimized:
108368     **
108369     **            x=5
108370     **            x=5 AND y=10
108371     **            x=5 AND y<10
108372     **            x=5 AND y>5 AND y<10
108373     **            x=5 AND y=5 AND z<=10
108374     **
108375     **         The z<10 term of the following cannot be used, only
108376     **         the x=5 term:
108377     **
108378     **            x=5 AND z<10
108379     **
108380     **         N may be zero if there are inequality constraints.
108381     **         If there are no inequality constraints, then N is at
108382     **         least one.
108383     **
108384     **         This case is also used when there are no WHERE clause
108385     **         constraints but an index is selected anyway, in order
108386     **         to force the output order to conform to an ORDER BY.
108387     */
108388     static const u8 aStartOp[] = {
108389       0,
108390       0,
108391       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
108392       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
108393       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
108394       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
108395       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
108396       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
108397     };
108398     static const u8 aEndOp[] = {
108399       OP_Noop,             /* 0: (!end_constraints) */
108400       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
108401       OP_IdxLT             /* 2: (end_constraints && bRev) */
108402     };
108403     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
108404     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
108405     int regBase;                 /* Base register holding constraint values */
108406     int r1;                      /* Temp register */
108407     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
108408     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
108409     int startEq;                 /* True if range start uses ==, >= or <= */
108410     int endEq;                   /* True if range end uses ==, >= or <= */
108411     int start_constraints;       /* Start of range is constrained */
108412     int nConstraint;             /* Number of constraint terms */
108413     Index *pIdx;                 /* The index we will be using */
108414     int iIdxCur;                 /* The VDBE cursor for the index */
108415     int nExtraReg = 0;           /* Number of extra registers needed */
108416     int op;                      /* Instruction opcode */
108417     char *zStartAff;             /* Affinity for start of range constraint */
108418     char *zEndAff;               /* Affinity for end of range constraint */
108419
108420     pIdx = pLevel->plan.u.pIdx;
108421     iIdxCur = pLevel->iIdxCur;
108422     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
108423
108424     /* If this loop satisfies a sort order (pOrderBy) request that
108425     ** was passed to this function to implement a "SELECT min(x) ..."
108426     ** query, then the caller will only allow the loop to run for
108427     ** a single iteration. This means that the first row returned
108428     ** should not have a NULL value stored in 'x'. If column 'x' is
108429     ** the first one after the nEq equality constraints in the index,
108430     ** this requires some special handling.
108431     */
108432     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
108433      && (pLevel->plan.wsFlags&WHERE_ORDERED)
108434      && (pIdx->nColumn>nEq)
108435     ){
108436       /* assert( pOrderBy->nExpr==1 ); */
108437       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
108438       isMinQuery = 1;
108439       nExtraReg = 1;
108440     }
108441
108442     /* Find any inequality constraint terms for the start and end
108443     ** of the range.
108444     */
108445     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
108446       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
108447       nExtraReg = 1;
108448     }
108449     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
108450       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
108451       nExtraReg = 1;
108452     }
108453
108454     /* Generate code to evaluate all constraint terms using == or IN
108455     ** and store the values of those terms in an array of registers
108456     ** starting at regBase.
108457     */
108458     regBase = codeAllEqualityTerms(
108459         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
108460     );
108461     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
108462     addrNxt = pLevel->addrNxt;
108463
108464     /* If we are doing a reverse order scan on an ascending index, or
108465     ** a forward order scan on a descending index, interchange the
108466     ** start and end terms (pRangeStart and pRangeEnd).
108467     */
108468     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
108469      || (bRev && pIdx->nColumn==nEq)
108470     ){
108471       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
108472     }
108473
108474     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
108475     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
108476     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
108477     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
108478     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
108479     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
108480     start_constraints = pRangeStart || nEq>0;
108481
108482     /* Seek the index cursor to the start of the range. */
108483     nConstraint = nEq;
108484     if( pRangeStart ){
108485       Expr *pRight = pRangeStart->pExpr->pRight;
108486       sqlite3ExprCode(pParse, pRight, regBase+nEq);
108487       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
108488         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108489       }
108490       if( zStartAff ){
108491         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
108492           /* Since the comparison is to be performed with no conversions
108493           ** applied to the operands, set the affinity to apply to pRight to
108494           ** SQLITE_AFF_NONE.  */
108495           zStartAff[nEq] = SQLITE_AFF_NONE;
108496         }
108497         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
108498           zStartAff[nEq] = SQLITE_AFF_NONE;
108499         }
108500       }
108501       nConstraint++;
108502       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108503     }else if( isMinQuery ){
108504       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
108505       nConstraint++;
108506       startEq = 0;
108507       start_constraints = 1;
108508     }
108509     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
108510     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
108511     assert( op!=0 );
108512     testcase( op==OP_Rewind );
108513     testcase( op==OP_Last );
108514     testcase( op==OP_SeekGt );
108515     testcase( op==OP_SeekGe );
108516     testcase( op==OP_SeekLe );
108517     testcase( op==OP_SeekLt );
108518     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108519
108520     /* Load the value for the inequality constraint at the end of the
108521     ** range (if any).
108522     */
108523     nConstraint = nEq;
108524     if( pRangeEnd ){
108525       Expr *pRight = pRangeEnd->pExpr->pRight;
108526       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
108527       sqlite3ExprCode(pParse, pRight, regBase+nEq);
108528       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
108529         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108530       }
108531       if( zEndAff ){
108532         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
108533           /* Since the comparison is to be performed with no conversions
108534           ** applied to the operands, set the affinity to apply to pRight to
108535           ** SQLITE_AFF_NONE.  */
108536           zEndAff[nEq] = SQLITE_AFF_NONE;
108537         }
108538         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
108539           zEndAff[nEq] = SQLITE_AFF_NONE;
108540         }
108541       }
108542       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
108543       nConstraint++;
108544       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108545     }
108546     sqlite3DbFree(pParse->db, zStartAff);
108547     sqlite3DbFree(pParse->db, zEndAff);
108548
108549     /* Top of the loop body */
108550     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108551
108552     /* Check if the index cursor is past the end of the range. */
108553     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
108554     testcase( op==OP_Noop );
108555     testcase( op==OP_IdxGE );
108556     testcase( op==OP_IdxLT );
108557     if( op!=OP_Noop ){
108558       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108559       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
108560     }
108561
108562     /* If there are inequality constraints, check that the value
108563     ** of the table column that the inequality contrains is not NULL.
108564     ** If it is, jump to the next iteration of the loop.
108565     */
108566     r1 = sqlite3GetTempReg(pParse);
108567     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
108568     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
108569     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
108570       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
108571       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
108572     }
108573     sqlite3ReleaseTempReg(pParse, r1);
108574
108575     /* Seek the table cursor, if required */
108576     disableTerm(pLevel, pRangeStart);
108577     disableTerm(pLevel, pRangeEnd);
108578     if( !omitTable ){
108579       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108580       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
108581       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108582       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
108583     }
108584
108585     /* Record the instruction used to terminate the loop. Disable
108586     ** WHERE clause terms made redundant by the index range scan.
108587     */
108588     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
108589       pLevel->op = OP_Noop;
108590     }else if( bRev ){
108591       pLevel->op = OP_Prev;
108592     }else{
108593       pLevel->op = OP_Next;
108594     }
108595     pLevel->p1 = iIdxCur;
108596     if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
108597       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108598     }else{
108599       assert( pLevel->p5==0 );
108600     }
108601   }else
108602
108603 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
108604   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
108605     /* Case 4:  Two or more separately indexed terms connected by OR
108606     **
108607     ** Example:
108608     **
108609     **   CREATE TABLE t1(a,b,c,d);
108610     **   CREATE INDEX i1 ON t1(a);
108611     **   CREATE INDEX i2 ON t1(b);
108612     **   CREATE INDEX i3 ON t1(c);
108613     **
108614     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
108615     **
108616     ** In the example, there are three indexed terms connected by OR.
108617     ** The top of the loop looks like this:
108618     **
108619     **          Null       1                # Zero the rowset in reg 1
108620     **
108621     ** Then, for each indexed term, the following. The arguments to
108622     ** RowSetTest are such that the rowid of the current row is inserted
108623     ** into the RowSet. If it is already present, control skips the
108624     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
108625     **
108626     **        sqlite3WhereBegin(<term>)
108627     **          RowSetTest                  # Insert rowid into rowset
108628     **          Gosub      2 A
108629     **        sqlite3WhereEnd()
108630     **
108631     ** Following the above, code to terminate the loop. Label A, the target
108632     ** of the Gosub above, jumps to the instruction right after the Goto.
108633     **
108634     **          Null       1                # Zero the rowset in reg 1
108635     **          Goto       B                # The loop is finished.
108636     **
108637     **       A: <loop body>                 # Return data, whatever.
108638     **
108639     **          Return     2                # Jump back to the Gosub
108640     **
108641     **       B: <after the loop>
108642     **
108643     */
108644     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
108645     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
108646     Index *pCov = 0;             /* Potential covering index (or NULL) */
108647     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
108648
108649     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
108650     int regRowset = 0;                        /* Register for RowSet object */
108651     int regRowid = 0;                         /* Register holding rowid */
108652     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
108653     int iRetInit;                             /* Address of regReturn init */
108654     int untestedTerms = 0;             /* Some terms not completely tested */
108655     int ii;                            /* Loop counter */
108656     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
108657
108658     pTerm = pLevel->plan.u.pTerm;
108659     assert( pTerm!=0 );
108660     assert( pTerm->eOperator==WO_OR );
108661     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
108662     pOrWc = &pTerm->u.pOrInfo->wc;
108663     pLevel->op = OP_Return;
108664     pLevel->p1 = regReturn;
108665
108666     /* Set up a new SrcList in pOrTab containing the table being scanned
108667     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
108668     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
108669     */
108670     if( pWInfo->nLevel>1 ){
108671       int nNotReady;                 /* The number of notReady tables */
108672       struct SrcList_item *origSrc;     /* Original list of tables */
108673       nNotReady = pWInfo->nLevel - iLevel - 1;
108674       pOrTab = sqlite3StackAllocRaw(pParse->db,
108675                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
108676       if( pOrTab==0 ) return notReady;
108677       pOrTab->nAlloc = (i16)(nNotReady + 1);
108678       pOrTab->nSrc = pOrTab->nAlloc;
108679       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
108680       origSrc = pWInfo->pTabList->a;
108681       for(k=1; k<=nNotReady; k++){
108682         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
108683       }
108684     }else{
108685       pOrTab = pWInfo->pTabList;
108686     }
108687
108688     /* Initialize the rowset register to contain NULL. An SQL NULL is
108689     ** equivalent to an empty rowset.
108690     **
108691     ** Also initialize regReturn to contain the address of the instruction
108692     ** immediately following the OP_Return at the bottom of the loop. This
108693     ** is required in a few obscure LEFT JOIN cases where control jumps
108694     ** over the top of the loop into the body of it. In this case the
108695     ** correct response for the end-of-loop code (the OP_Return) is to
108696     ** fall through to the next instruction, just as an OP_Next does if
108697     ** called on an uninitialized cursor.
108698     */
108699     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108700       regRowset = ++pParse->nMem;
108701       regRowid = ++pParse->nMem;
108702       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
108703     }
108704     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
108705
108706     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
108707     ** Then for every term xN, evaluate as the subexpression: xN AND z
108708     ** That way, terms in y that are factored into the disjunction will
108709     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
108710     **
108711     ** Actually, each subexpression is converted to "xN AND w" where w is
108712     ** the "interesting" terms of z - terms that did not originate in the
108713     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
108714     ** indices.
108715     */
108716     if( pWC->nTerm>1 ){
108717       int iTerm;
108718       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
108719         Expr *pExpr = pWC->a[iTerm].pExpr;
108720         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
108721         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
108722         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
108723         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
108724         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
108725       }
108726       if( pAndExpr ){
108727         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
108728       }
108729     }
108730
108731     for(ii=0; ii<pOrWc->nTerm; ii++){
108732       WhereTerm *pOrTerm = &pOrWc->a[ii];
108733       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
108734         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
108735         Expr *pOrExpr = pOrTerm->pExpr;
108736         if( pAndExpr ){
108737           pAndExpr->pLeft = pOrExpr;
108738           pOrExpr = pAndExpr;
108739         }
108740         /* Loop through table entries that match term pOrTerm. */
108741         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
108742                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
108743                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
108744         assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
108745         if( pSubWInfo ){
108746           WhereLevel *pLvl;
108747           explainOneScan(
108748               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
108749           );
108750           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108751             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
108752             int r;
108753             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
108754                                          regRowid, 0);
108755             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
108756                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
108757           }
108758           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
108759
108760           /* The pSubWInfo->untestedTerms flag means that this OR term
108761           ** contained one or more AND term from a notReady table.  The
108762           ** terms from the notReady table could not be tested and will
108763           ** need to be tested later.
108764           */
108765           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
108766
108767           /* If all of the OR-connected terms are optimized using the same
108768           ** index, and the index is opened using the same cursor number
108769           ** by each call to sqlite3WhereBegin() made by this loop, it may
108770           ** be possible to use that index as a covering index.
108771           **
108772           ** If the call to sqlite3WhereBegin() above resulted in a scan that
108773           ** uses an index, and this is either the first OR-connected term
108774           ** processed or the index is the same as that used by all previous
108775           ** terms, set pCov to the candidate covering index. Otherwise, set
108776           ** pCov to NULL to indicate that no candidate covering index will
108777           ** be available.
108778           */
108779           pLvl = &pSubWInfo->a[0];
108780           if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
108781            && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
108782            && (ii==0 || pLvl->plan.u.pIdx==pCov)
108783           ){
108784             assert( pLvl->iIdxCur==iCovCur );
108785             pCov = pLvl->plan.u.pIdx;
108786           }else{
108787             pCov = 0;
108788           }
108789
108790           /* Finish the loop through table entries that match term pOrTerm. */
108791           sqlite3WhereEnd(pSubWInfo);
108792         }
108793       }
108794     }
108795     pLevel->u.pCovidx = pCov;
108796     if( pCov ) pLevel->iIdxCur = iCovCur;
108797     if( pAndExpr ){
108798       pAndExpr->pLeft = 0;
108799       sqlite3ExprDelete(pParse->db, pAndExpr);
108800     }
108801     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
108802     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
108803     sqlite3VdbeResolveLabel(v, iLoopBody);
108804
108805     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
108806     if( !untestedTerms ) disableTerm(pLevel, pTerm);
108807   }else
108808 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
108809
108810   {
108811     /* Case 5:  There is no usable index.  We must do a complete
108812     **          scan of the entire table.
108813     */
108814     static const u8 aStep[] = { OP_Next, OP_Prev };
108815     static const u8 aStart[] = { OP_Rewind, OP_Last };
108816     assert( bRev==0 || bRev==1 );
108817     assert( omitTable==0 );
108818     pLevel->op = aStep[bRev];
108819     pLevel->p1 = iCur;
108820     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
108821     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108822   }
108823   notReady &= ~getMask(pWC->pMaskSet, iCur);
108824
108825   /* Insert code to test every subexpression that can be completely
108826   ** computed using the current set of tables.
108827   **
108828   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
108829   ** the use of indices become tests that are evaluated against each row of
108830   ** the relevant input tables.
108831   */
108832   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
108833     Expr *pE;
108834     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
108835     testcase( pTerm->wtFlags & TERM_CODED );
108836     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
108837     if( (pTerm->prereqAll & notReady)!=0 ){
108838       testcase( pWInfo->untestedTerms==0
108839                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
108840       pWInfo->untestedTerms = 1;
108841       continue;
108842     }
108843     pE = pTerm->pExpr;
108844     assert( pE!=0 );
108845     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
108846       continue;
108847     }
108848     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
108849     pTerm->wtFlags |= TERM_CODED;
108850   }
108851
108852   /* For a LEFT OUTER JOIN, generate code that will record the fact that
108853   ** at least one row of the right table has matched the left table.
108854   */
108855   if( pLevel->iLeftJoin ){
108856     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
108857     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
108858     VdbeComment((v, "record LEFT JOIN hit"));
108859     sqlite3ExprCacheClear(pParse);
108860     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
108861       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
108862       testcase( pTerm->wtFlags & TERM_CODED );
108863       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
108864       if( (pTerm->prereqAll & notReady)!=0 ){
108865         assert( pWInfo->untestedTerms );
108866         continue;
108867       }
108868       assert( pTerm->pExpr );
108869       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
108870       pTerm->wtFlags |= TERM_CODED;
108871     }
108872   }
108873   sqlite3ReleaseTempReg(pParse, iReleaseReg);
108874
108875   return notReady;
108876 }
108877
108878 #if defined(SQLITE_TEST)
108879 /*
108880 ** The following variable holds a text description of query plan generated
108881 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
108882 ** overwrites the previous.  This information is used for testing and
108883 ** analysis only.
108884 */
108885 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
108886 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
108887
108888 #endif /* SQLITE_TEST */
108889
108890
108891 /*
108892 ** Free a WhereInfo structure
108893 */
108894 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
108895   if( ALWAYS(pWInfo) ){
108896     int i;
108897     for(i=0; i<pWInfo->nLevel; i++){
108898       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
108899       if( pInfo ){
108900         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
108901         if( pInfo->needToFreeIdxStr ){
108902           sqlite3_free(pInfo->idxStr);
108903         }
108904         sqlite3DbFree(db, pInfo);
108905       }
108906       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
108907         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
108908         if( pIdx ){
108909           sqlite3DbFree(db, pIdx->zColAff);
108910           sqlite3DbFree(db, pIdx);
108911         }
108912       }
108913     }
108914     whereClauseClear(pWInfo->pWC);
108915     sqlite3DbFree(db, pWInfo);
108916   }
108917 }
108918
108919
108920 /*
108921 ** Generate the beginning of the loop used for WHERE clause processing.
108922 ** The return value is a pointer to an opaque structure that contains
108923 ** information needed to terminate the loop.  Later, the calling routine
108924 ** should invoke sqlite3WhereEnd() with the return value of this function
108925 ** in order to complete the WHERE clause processing.
108926 **
108927 ** If an error occurs, this routine returns NULL.
108928 **
108929 ** The basic idea is to do a nested loop, one loop for each table in
108930 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
108931 ** same as a SELECT with only a single table in the FROM clause.)  For
108932 ** example, if the SQL is this:
108933 **
108934 **       SELECT * FROM t1, t2, t3 WHERE ...;
108935 **
108936 ** Then the code generated is conceptually like the following:
108937 **
108938 **      foreach row1 in t1 do       \    Code generated
108939 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
108940 **          foreach row3 in t3 do   /
108941 **            ...
108942 **          end                     \    Code generated
108943 **        end                        |-- by sqlite3WhereEnd()
108944 **      end                         /
108945 **
108946 ** Note that the loops might not be nested in the order in which they
108947 ** appear in the FROM clause if a different order is better able to make
108948 ** use of indices.  Note also that when the IN operator appears in
108949 ** the WHERE clause, it might result in additional nested loops for
108950 ** scanning through all values on the right-hand side of the IN.
108951 **
108952 ** There are Btree cursors associated with each table.  t1 uses cursor
108953 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
108954 ** And so forth.  This routine generates code to open those VDBE cursors
108955 ** and sqlite3WhereEnd() generates the code to close them.
108956 **
108957 ** The code that sqlite3WhereBegin() generates leaves the cursors named
108958 ** in pTabList pointing at their appropriate entries.  The [...] code
108959 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
108960 ** data from the various tables of the loop.
108961 **
108962 ** If the WHERE clause is empty, the foreach loops must each scan their
108963 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
108964 ** the tables have indices and there are terms in the WHERE clause that
108965 ** refer to those indices, a complete table scan can be avoided and the
108966 ** code will run much faster.  Most of the work of this routine is checking
108967 ** to see if there are indices that can be used to speed up the loop.
108968 **
108969 ** Terms of the WHERE clause are also used to limit which rows actually
108970 ** make it to the "..." in the middle of the loop.  After each "foreach",
108971 ** terms of the WHERE clause that use only terms in that loop and outer
108972 ** loops are evaluated and if false a jump is made around all subsequent
108973 ** inner loops (or around the "..." if the test occurs within the inner-
108974 ** most loop)
108975 **
108976 ** OUTER JOINS
108977 **
108978 ** An outer join of tables t1 and t2 is conceptally coded as follows:
108979 **
108980 **    foreach row1 in t1 do
108981 **      flag = 0
108982 **      foreach row2 in t2 do
108983 **        start:
108984 **          ...
108985 **          flag = 1
108986 **      end
108987 **      if flag==0 then
108988 **        move the row2 cursor to a null row
108989 **        goto start
108990 **      fi
108991 **    end
108992 **
108993 ** ORDER BY CLAUSE PROCESSING
108994 **
108995 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
108996 ** if there is one.  If there is no ORDER BY clause or if this routine
108997 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
108998 **
108999 ** If an index can be used so that the natural output order of the table
109000 ** scan is correct for the ORDER BY clause, then that index is used and
109001 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr.  This
109002 ** is an optimization that prevents an unnecessary sort of the result set
109003 ** if an index appropriate for the ORDER BY clause already exists.
109004 **
109005 ** If the where clause loops cannot be arranged to provide the correct
109006 ** output order, then WhereInfo.nOBSat is 0.
109007 */
109008 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109009   Parse *pParse,        /* The parser context */
109010   SrcList *pTabList,    /* A list of all tables to be scanned */
109011   Expr *pWhere,         /* The WHERE clause */
109012   ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
109013   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
109014   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
109015   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
109016 ){
109017   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
109018   int nTabList;              /* Number of elements in pTabList */
109019   WhereInfo *pWInfo;         /* Will become the return value of this function */
109020   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
109021   Bitmask notReady;          /* Cursors that are not yet positioned */
109022   WhereBestIdx sWBI;         /* Best index search context */
109023   WhereMaskSet *pMaskSet;    /* The expression mask set */
109024   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
109025   int iFrom;                 /* First unused FROM clause element */
109026   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
109027   int ii;                    /* Loop counter */
109028   sqlite3 *db;               /* Database connection */
109029
109030
109031   /* Variable initialization */
109032   memset(&sWBI, 0, sizeof(sWBI));
109033   sWBI.pParse = pParse;
109034
109035   /* The number of tables in the FROM clause is limited by the number of
109036   ** bits in a Bitmask
109037   */
109038   testcase( pTabList->nSrc==BMS );
109039   if( pTabList->nSrc>BMS ){
109040     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
109041     return 0;
109042   }
109043
109044   /* This function normally generates a nested loop for all tables in
109045   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
109046   ** only generate code for the first table in pTabList and assume that
109047   ** any cursors associated with subsequent tables are uninitialized.
109048   */
109049   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
109050
109051   /* Allocate and initialize the WhereInfo structure that will become the
109052   ** return value. A single allocation is used to store the WhereInfo
109053   ** struct, the contents of WhereInfo.a[], the WhereClause structure
109054   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
109055   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
109056   ** some architectures. Hence the ROUND8() below.
109057   */
109058   db = pParse->db;
109059   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109060   pWInfo = sqlite3DbMallocZero(db,
109061       nByteWInfo +
109062       sizeof(WhereClause) +
109063       sizeof(WhereMaskSet)
109064   );
109065   if( db->mallocFailed ){
109066     sqlite3DbFree(db, pWInfo);
109067     pWInfo = 0;
109068     goto whereBeginError;
109069   }
109070   pWInfo->nLevel = nTabList;
109071   pWInfo->pParse = pParse;
109072   pWInfo->pTabList = pTabList;
109073   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
109074   pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
109075   pWInfo->wctrlFlags = wctrlFlags;
109076   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109077   pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
109078   sWBI.aLevel = pWInfo->a;
109079
109080   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109081   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109082   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109083
109084   /* Split the WHERE clause into separate subexpressions where each
109085   ** subexpression is separated by an AND operator.
109086   */
109087   initMaskSet(pMaskSet);
109088   whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
109089   sqlite3ExprCodeConstants(pParse, pWhere);
109090   whereSplit(sWBI.pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
109091
109092   /* Special case: a WHERE clause that is constant.  Evaluate the
109093   ** expression and either jump over all of the code or fall thru.
109094   */
109095   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109096     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109097     pWhere = 0;
109098   }
109099
109100   /* Assign a bit from the bitmask to every term in the FROM clause.
109101   **
109102   ** When assigning bitmask values to FROM clause cursors, it must be
109103   ** the case that if X is the bitmask for the N-th FROM clause term then
109104   ** the bitmask for all FROM clause terms to the left of the N-th term
109105   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
109106   ** its Expr.iRightJoinTable value to find the bitmask of the right table
109107   ** of the join.  Subtracting one from the right table bitmask gives a
109108   ** bitmask for all tables to the left of the join.  Knowing the bitmask
109109   ** for all tables to the left of a left join is important.  Ticket #3015.
109110   **
109111   ** Configure the WhereClause.vmask variable so that bits that correspond
109112   ** to virtual table cursors are set. This is used to selectively disable
109113   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
109114   ** with virtual tables.
109115   **
109116   ** Note that bitmasks are created for all pTabList->nSrc tables in
109117   ** pTabList, not just the first nTabList tables.  nTabList is normally
109118   ** equal to pTabList->nSrc but might be shortened to 1 if the
109119   ** WHERE_ONETABLE_ONLY flag is set.
109120   */
109121   assert( sWBI.pWC->vmask==0 && pMaskSet->n==0 );
109122   for(ii=0; ii<pTabList->nSrc; ii++){
109123     createMask(pMaskSet, pTabList->a[ii].iCursor);
109124 #ifndef SQLITE_OMIT_VIRTUALTABLE
109125     if( ALWAYS(pTabList->a[ii].pTab) && IsVirtual(pTabList->a[ii].pTab) ){
109126       sWBI.pWC->vmask |= ((Bitmask)1 << ii);
109127     }
109128 #endif
109129   }
109130 #ifndef NDEBUG
109131   {
109132     Bitmask toTheLeft = 0;
109133     for(ii=0; ii<pTabList->nSrc; ii++){
109134       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
109135       assert( (m-1)==toTheLeft );
109136       toTheLeft |= m;
109137     }
109138   }
109139 #endif
109140
109141   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
109142   ** add new virtual terms onto the end of the WHERE clause.  We do not
109143   ** want to analyze these virtual terms, so start analyzing at the end
109144   ** and work forward so that the added virtual terms are never processed.
109145   */
109146   exprAnalyzeAll(pTabList, sWBI.pWC);
109147   if( db->mallocFailed ){
109148     goto whereBeginError;
109149   }
109150
109151   /* Check if the DISTINCT qualifier, if there is one, is redundant.
109152   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
109153   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
109154   */
109155   if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
109156     pDistinct = 0;
109157     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109158   }
109159
109160   /* Chose the best index to use for each table in the FROM clause.
109161   **
109162   ** This loop fills in the following fields:
109163   **
109164   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
109165   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
109166   **   pWInfo->a[].nEq       The number of == and IN constraints
109167   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
109168   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
109169   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
109170   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
109171   **
109172   ** This loop also figures out the nesting order of tables in the FROM
109173   ** clause.
109174   */
109175   sWBI.notValid = ~(Bitmask)0;
109176   sWBI.pOrderBy = pOrderBy;
109177   sWBI.n = nTabList;
109178   sWBI.pDistinct = pDistinct;
109179   andFlags = ~0;
109180   WHERETRACE(("*** Optimizer Start ***\n"));
109181   for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
109182     WhereCost bestPlan;         /* Most efficient plan seen so far */
109183     Index *pIdx;                /* Index for FROM table at pTabItem */
109184     int j;                      /* For looping over FROM tables */
109185     int bestJ = -1;             /* The value of j */
109186     Bitmask m;                  /* Bitmask value for j or bestJ */
109187     int isOptimal;              /* Iterator for optimal/non-optimal search */
109188     int nUnconstrained;         /* Number tables without INDEXED BY */
109189     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
109190
109191     memset(&bestPlan, 0, sizeof(bestPlan));
109192     bestPlan.rCost = SQLITE_BIG_DBL;
109193     WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
109194
109195     /* Loop through the remaining entries in the FROM clause to find the
109196     ** next nested loop. The loop tests all FROM clause entries
109197     ** either once or twice.
109198     **
109199     ** The first test is always performed if there are two or more entries
109200     ** remaining and never performed if there is only one FROM clause entry
109201     ** to choose from.  The first test looks for an "optimal" scan.  In
109202     ** this context an optimal scan is one that uses the same strategy
109203     ** for the given FROM clause entry as would be selected if the entry
109204     ** were used as the innermost nested loop.  In other words, a table
109205     ** is chosen such that the cost of running that table cannot be reduced
109206     ** by waiting for other tables to run first.  This "optimal" test works
109207     ** by first assuming that the FROM clause is on the inner loop and finding
109208     ** its query plan, then checking to see if that query plan uses any
109209     ** other FROM clause terms that are sWBI.notValid.  If no notValid terms
109210     ** are used then the "optimal" query plan works.
109211     **
109212     ** Note that the WhereCost.nRow parameter for an optimal scan might
109213     ** not be as small as it would be if the table really were the innermost
109214     ** join.  The nRow value can be reduced by WHERE clause constraints
109215     ** that do not use indices.  But this nRow reduction only happens if the
109216     ** table really is the innermost join.
109217     **
109218     ** The second loop iteration is only performed if no optimal scan
109219     ** strategies were found by the first iteration. This second iteration
109220     ** is used to search for the lowest cost scan overall.
109221     **
109222     ** Previous versions of SQLite performed only the second iteration -
109223     ** the next outermost loop was always that with the lowest overall
109224     ** cost. However, this meant that SQLite could select the wrong plan
109225     ** for scripts such as the following:
109226     **
109227     **   CREATE TABLE t1(a, b);
109228     **   CREATE TABLE t2(c, d);
109229     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
109230     **
109231     ** The best strategy is to iterate through table t1 first. However it
109232     ** is not possible to determine this with a simple greedy algorithm.
109233     ** Since the cost of a linear scan through table t2 is the same
109234     ** as the cost of a linear scan through table t1, a simple greedy
109235     ** algorithm may choose to use t2 for the outer loop, which is a much
109236     ** costlier approach.
109237     */
109238     nUnconstrained = 0;
109239     notIndexed = 0;
109240     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
109241       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109242         int doNotReorder;    /* True if this table should not be reordered */
109243
109244         doNotReorder =  (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0;
109245         if( j!=iFrom && doNotReorder ) break;
109246         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109247         if( (m & sWBI.notValid)==0 ){
109248           if( j==iFrom ) iFrom++;
109249           continue;
109250         }
109251         sWBI.notReady = (isOptimal ? m : sWBI.notValid);
109252         if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
109253
109254         WHERETRACE(("   === trying table %d (%s) with isOptimal=%d ===\n",
109255                     j, sWBI.pSrc->pTab->zName, isOptimal));
109256         assert( sWBI.pSrc->pTab );
109257 #ifndef SQLITE_OMIT_VIRTUALTABLE
109258         if( IsVirtual(sWBI.pSrc->pTab) ){
109259           sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
109260           bestVirtualIndex(&sWBI);
109261         }else
109262 #endif
109263         {
109264           bestBtreeIndex(&sWBI);
109265         }
109266         assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
109267
109268         /* If an INDEXED BY clause is present, then the plan must use that
109269         ** index if it uses any index at all */
109270         assert( sWBI.pSrc->pIndex==0
109271                   || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
109272                   || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
109273
109274         if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
109275           notIndexed |= m;
109276         }
109277         if( isOptimal ){
109278           pWInfo->a[j].rOptCost = sWBI.cost.rCost;
109279         }else if( iFrom<nTabList-1 ){
109280           /* If two or more tables have nearly the same outer loop cost,
109281           ** very different inner loop (optimal) cost, we want to choose
109282           ** for the outer loop that table which benefits the least from
109283           ** being in the inner loop.  The following code scales the
109284           ** outer loop cost estimate to accomplish that. */
109285           WHERETRACE(("   scaling cost from %.1f to %.1f\n",
109286                       sWBI.cost.rCost,
109287                       sWBI.cost.rCost/pWInfo->a[j].rOptCost));
109288           sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
109289         }
109290
109291         /* Conditions under which this table becomes the best so far:
109292         **
109293         **   (1) The table must not depend on other tables that have not
109294         **       yet run.  (In other words, it must not depend on tables
109295         **       in inner loops.)
109296         **
109297         **   (2) (This rule was removed on 2012-11-09.  The scaling of the
109298         **       cost using the optimal scan cost made this rule obsolete.)
109299         **
109300         **   (3) All tables have an INDEXED BY clause or this table lacks an
109301         **       INDEXED BY clause or this table uses the specific
109302         **       index specified by its INDEXED BY clause.  This rule ensures
109303         **       that a best-so-far is always selected even if an impossible
109304         **       combination of INDEXED BY clauses are given.  The error
109305         **       will be detected and relayed back to the application later.
109306         **       The NEVER() comes about because rule (2) above prevents
109307         **       An indexable full-table-scan from reaching rule (3).
109308         **
109309         **   (4) The plan cost must be lower than prior plans, where "cost"
109310         **       is defined by the compareCost() function above.
109311         */
109312         if( (sWBI.cost.used&sWBI.notValid)==0                    /* (1) */
109313             && (nUnconstrained==0 || sWBI.pSrc->pIndex==0        /* (3) */
109314                 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
109315             && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan))   /* (4) */
109316         ){
109317           WHERETRACE(("   === table %d (%s) is best so far\n"
109318                       "       cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
109319                       j, sWBI.pSrc->pTab->zName,
109320                       sWBI.cost.rCost, sWBI.cost.plan.nRow,
109321                       sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
109322           bestPlan = sWBI.cost;
109323           bestJ = j;
109324         }
109325         if( doNotReorder ) break;
109326       }
109327     }
109328     assert( bestJ>=0 );
109329     assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
109330     WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
109331                 "    cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
109332                 bestJ, pTabList->a[bestJ].pTab->zName,
109333                 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
109334                 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
109335     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
109336       assert( pWInfo->eDistinct==0 );
109337       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109338     }
109339     andFlags &= bestPlan.plan.wsFlags;
109340     pLevel->plan = bestPlan.plan;
109341     pLevel->iTabCur = pTabList->a[bestJ].iCursor;
109342     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
109343     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
109344     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
109345       if( (wctrlFlags & WHERE_ONETABLE_ONLY)
109346        && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
109347       ){
109348         pLevel->iIdxCur = iIdxCur;
109349       }else{
109350         pLevel->iIdxCur = pParse->nTab++;
109351       }
109352     }else{
109353       pLevel->iIdxCur = -1;
109354     }
109355     sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
109356     pLevel->iFrom = (u8)bestJ;
109357     if( bestPlan.plan.nRow>=(double)1 ){
109358       pParse->nQueryLoop *= bestPlan.plan.nRow;
109359     }
109360
109361     /* Check that if the table scanned by this loop iteration had an
109362     ** INDEXED BY clause attached to it, that the named index is being
109363     ** used for the scan. If not, then query compilation has failed.
109364     ** Return an error.
109365     */
109366     pIdx = pTabList->a[bestJ].pIndex;
109367     if( pIdx ){
109368       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
109369         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
109370         goto whereBeginError;
109371       }else{
109372         /* If an INDEXED BY clause is used, the bestIndex() function is
109373         ** guaranteed to find the index specified in the INDEXED BY clause
109374         ** if it find an index at all. */
109375         assert( bestPlan.plan.u.pIdx==pIdx );
109376       }
109377     }
109378   }
109379   WHERETRACE(("*** Optimizer Finished ***\n"));
109380   if( pParse->nErr || db->mallocFailed ){
109381     goto whereBeginError;
109382   }
109383   if( nTabList ){
109384     pLevel--;
109385     pWInfo->nOBSat = pLevel->plan.nOBSat;
109386   }else{
109387     pWInfo->nOBSat = 0;
109388   }
109389
109390   /* If the total query only selects a single row, then the ORDER BY
109391   ** clause is irrelevant.
109392   */
109393   if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
109394     assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
109395     pWInfo->nOBSat = pOrderBy->nExpr;
109396   }
109397
109398   /* If the caller is an UPDATE or DELETE statement that is requesting
109399   ** to use a one-pass algorithm, determine if this is appropriate.
109400   ** The one-pass algorithm only works if the WHERE clause constraints
109401   ** the statement to update a single row.
109402   */
109403   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
109404   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
109405     pWInfo->okOnePass = 1;
109406     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
109407   }
109408
109409   /* Open all tables in the pTabList and any indices selected for
109410   ** searching those tables.
109411   */
109412   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
109413   notReady = ~(Bitmask)0;
109414   pWInfo->nRowOut = (double)1;
109415   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
109416     Table *pTab;     /* Table to open */
109417     int iDb;         /* Index of database containing table/index */
109418     struct SrcList_item *pTabItem;
109419
109420     pTabItem = &pTabList->a[pLevel->iFrom];
109421     pTab = pTabItem->pTab;
109422     pWInfo->nRowOut *= pLevel->plan.nRow;
109423     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109424     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
109425       /* Do nothing */
109426     }else
109427 #ifndef SQLITE_OMIT_VIRTUALTABLE
109428     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
109429       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109430       int iCur = pTabItem->iCursor;
109431       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
109432     }else if( IsVirtual(pTab) ){
109433       /* noop */
109434     }else
109435 #endif
109436     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
109437          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
109438       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
109439       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
109440       testcase( pTab->nCol==BMS-1 );
109441       testcase( pTab->nCol==BMS );
109442       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
109443         Bitmask b = pTabItem->colUsed;
109444         int n = 0;
109445         for(; b; b=b>>1, n++){}
109446         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
109447                             SQLITE_INT_TO_PTR(n), P4_INT32);
109448         assert( n<=pTab->nCol );
109449       }
109450     }else{
109451       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109452     }
109453 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
109454     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
109455       constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
109456     }else
109457 #endif
109458     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
109459       Index *pIx = pLevel->plan.u.pIdx;
109460       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
109461       int iIndexCur = pLevel->iIdxCur;
109462       assert( pIx->pSchema==pTab->pSchema );
109463       assert( iIndexCur>=0 );
109464       sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
109465                         (char*)pKey, P4_KEYINFO_HANDOFF);
109466       VdbeComment((v, "%s", pIx->zName));
109467     }
109468     sqlite3CodeVerifySchema(pParse, iDb);
109469     notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
109470   }
109471   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
109472   if( db->mallocFailed ) goto whereBeginError;
109473
109474   /* Generate the code to do the search.  Each iteration of the for
109475   ** loop below generates code for a single nested loop of the VM
109476   ** program.
109477   */
109478   notReady = ~(Bitmask)0;
109479   for(ii=0; ii<nTabList; ii++){
109480     pLevel = &pWInfo->a[ii];
109481     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
109482     notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
109483     pWInfo->iContinue = pLevel->addrCont;
109484   }
109485
109486 #ifdef SQLITE_TEST  /* For testing and debugging use only */
109487   /* Record in the query plan information about the current table
109488   ** and the index used to access it (if any).  If the table itself
109489   ** is not used, its name is just '{}'.  If no index is used
109490   ** the index is listed as "{}".  If the primary key is used the
109491   ** index name is '*'.
109492   */
109493   for(ii=0; ii<nTabList; ii++){
109494     char *z;
109495     int n;
109496     int w;
109497     struct SrcList_item *pTabItem;
109498
109499     pLevel = &pWInfo->a[ii];
109500     w = pLevel->plan.wsFlags;
109501     pTabItem = &pTabList->a[pLevel->iFrom];
109502     z = pTabItem->zAlias;
109503     if( z==0 ) z = pTabItem->pTab->zName;
109504     n = sqlite3Strlen30(z);
109505     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
109506       if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109507         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
109508         nQPlan += 2;
109509       }else{
109510         memcpy(&sqlite3_query_plan[nQPlan], z, n);
109511         nQPlan += n;
109512       }
109513       sqlite3_query_plan[nQPlan++] = ' ';
109514     }
109515     testcase( w & WHERE_ROWID_EQ );
109516     testcase( w & WHERE_ROWID_RANGE );
109517     if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
109518       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
109519       nQPlan += 2;
109520     }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109521       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
109522       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
109523         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
109524         nQPlan += n;
109525         sqlite3_query_plan[nQPlan++] = ' ';
109526       }
109527     }else{
109528       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
109529       nQPlan += 3;
109530     }
109531   }
109532   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
109533     sqlite3_query_plan[--nQPlan] = 0;
109534   }
109535   sqlite3_query_plan[nQPlan] = 0;
109536   nQPlan = 0;
109537 #endif /* SQLITE_TEST // Testing and debugging use only */
109538
109539   /* Record the continuation address in the WhereInfo structure.  Then
109540   ** clean up and return.
109541   */
109542   return pWInfo;
109543
109544   /* Jump here if malloc fails */
109545 whereBeginError:
109546   if( pWInfo ){
109547     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
109548     whereInfoFree(db, pWInfo);
109549   }
109550   return 0;
109551 }
109552
109553 /*
109554 ** Generate the end of the WHERE loop.  See comments on
109555 ** sqlite3WhereBegin() for additional information.
109556 */
109557 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
109558   Parse *pParse = pWInfo->pParse;
109559   Vdbe *v = pParse->pVdbe;
109560   int i;
109561   WhereLevel *pLevel;
109562   SrcList *pTabList = pWInfo->pTabList;
109563   sqlite3 *db = pParse->db;
109564
109565   /* Generate loop termination code.
109566   */
109567   sqlite3ExprCacheClear(pParse);
109568   for(i=pWInfo->nLevel-1; i>=0; i--){
109569     pLevel = &pWInfo->a[i];
109570     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
109571     if( pLevel->op!=OP_Noop ){
109572       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
109573       sqlite3VdbeChangeP5(v, pLevel->p5);
109574     }
109575     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
109576       struct InLoop *pIn;
109577       int j;
109578       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
109579       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
109580         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
109581         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
109582         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
109583       }
109584       sqlite3DbFree(db, pLevel->u.in.aInLoop);
109585     }
109586     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
109587     if( pLevel->iLeftJoin ){
109588       int addr;
109589       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
109590       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
109591            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
109592       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
109593         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
109594       }
109595       if( pLevel->iIdxCur>=0 ){
109596         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
109597       }
109598       if( pLevel->op==OP_Return ){
109599         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
109600       }else{
109601         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
109602       }
109603       sqlite3VdbeJumpHere(v, addr);
109604     }
109605   }
109606
109607   /* The "break" point is here, just past the end of the outer loop.
109608   ** Set it.
109609   */
109610   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
109611
109612   /* Close all of the cursors that were opened by sqlite3WhereBegin.
109613   */
109614   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
109615   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
109616     Index *pIdx = 0;
109617     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
109618     Table *pTab = pTabItem->pTab;
109619     assert( pTab!=0 );
109620     if( (pTab->tabFlags & TF_Ephemeral)==0
109621      && pTab->pSelect==0
109622      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
109623     ){
109624       int ws = pLevel->plan.wsFlags;
109625       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
109626         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
109627       }
109628       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
109629         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
109630       }
109631     }
109632
109633     /* If this scan uses an index, make code substitutions to read data
109634     ** from the index in preference to the table. Sometimes, this means
109635     ** the table need never be read from. This is a performance boost,
109636     ** as the vdbe level waits until the table is read before actually
109637     ** seeking the table cursor to the record corresponding to the current
109638     ** position in the index.
109639     **
109640     ** Calls to the code generator in between sqlite3WhereBegin and
109641     ** sqlite3WhereEnd will have created code that references the table
109642     ** directly.  This loop scans all that code looking for opcodes
109643     ** that reference the table and converts them into opcodes that
109644     ** reference the index.
109645     */
109646     if( pLevel->plan.wsFlags & WHERE_INDEXED ){
109647       pIdx = pLevel->plan.u.pIdx;
109648     }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
109649       pIdx = pLevel->u.pCovidx;
109650     }
109651     if( pIdx && !db->mallocFailed){
109652       int k, j, last;
109653       VdbeOp *pOp;
109654
109655       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
109656       last = sqlite3VdbeCurrentAddr(v);
109657       for(k=pWInfo->iTop; k<last; k++, pOp++){
109658         if( pOp->p1!=pLevel->iTabCur ) continue;
109659         if( pOp->opcode==OP_Column ){
109660           for(j=0; j<pIdx->nColumn; j++){
109661             if( pOp->p2==pIdx->aiColumn[j] ){
109662               pOp->p2 = j;
109663               pOp->p1 = pLevel->iIdxCur;
109664               break;
109665             }
109666           }
109667           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
109668                || j<pIdx->nColumn );
109669         }else if( pOp->opcode==OP_Rowid ){
109670           pOp->p1 = pLevel->iIdxCur;
109671           pOp->opcode = OP_IdxRowid;
109672         }
109673       }
109674     }
109675   }
109676
109677   /* Final cleanup
109678   */
109679   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
109680   whereInfoFree(db, pWInfo);
109681   return;
109682 }
109683
109684 /************** End of where.c ***********************************************/
109685 /************** Begin file parse.c *******************************************/
109686 /* Driver template for the LEMON parser generator.
109687 ** The author disclaims copyright to this source code.
109688 **
109689 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
109690 ** The only modifications are the addition of a couple of NEVER()
109691 ** macros to disable tests that are needed in the case of a general
109692 ** LALR(1) grammar but which are always false in the
109693 ** specific grammar used by SQLite.
109694 */
109695 /* First off, code is included that follows the "include" declaration
109696 ** in the input grammar file. */
109697 /* #include <stdio.h> */
109698
109699
109700 /*
109701 ** Disable all error recovery processing in the parser push-down
109702 ** automaton.
109703 */
109704 #define YYNOERRORRECOVERY 1
109705
109706 /*
109707 ** Make yytestcase() the same as testcase()
109708 */
109709 #define yytestcase(X) testcase(X)
109710
109711 /*
109712 ** An instance of this structure holds information about the
109713 ** LIMIT clause of a SELECT statement.
109714 */
109715 struct LimitVal {
109716   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
109717   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
109718 };
109719
109720 /*
109721 ** An instance of this structure is used to store the LIKE,
109722 ** GLOB, NOT LIKE, and NOT GLOB operators.
109723 */
109724 struct LikeOp {
109725   Token eOperator;  /* "like" or "glob" or "regexp" */
109726   int bNot;         /* True if the NOT keyword is present */
109727 };
109728
109729 /*
109730 ** An instance of the following structure describes the event of a
109731 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
109732 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
109733 **
109734 **      UPDATE ON (a,b,c)
109735 **
109736 ** Then the "b" IdList records the list "a,b,c".
109737 */
109738 struct TrigEvent { int a; IdList * b; };
109739
109740 /*
109741 ** An instance of this structure holds the ATTACH key and the key type.
109742 */
109743 struct AttachKey { int type;  Token key; };
109744
109745 /*
109746 ** One or more VALUES claues
109747 */
109748 struct ValueList {
109749   ExprList *pList;
109750   Select *pSelect;
109751 };
109752
109753
109754   /* This is a utility routine used to set the ExprSpan.zStart and
109755   ** ExprSpan.zEnd values of pOut so that the span covers the complete
109756   ** range of text beginning with pStart and going to the end of pEnd.
109757   */
109758   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
109759     pOut->zStart = pStart->z;
109760     pOut->zEnd = &pEnd->z[pEnd->n];
109761   }
109762
109763   /* Construct a new Expr object from a single identifier.  Use the
109764   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
109765   ** that created the expression.
109766   */
109767   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
109768     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
109769     pOut->zStart = pValue->z;
109770     pOut->zEnd = &pValue->z[pValue->n];
109771   }
109772
109773   /* This routine constructs a binary expression node out of two ExprSpan
109774   ** objects and uses the result to populate a new ExprSpan object.
109775   */
109776   static void spanBinaryExpr(
109777     ExprSpan *pOut,     /* Write the result here */
109778     Parse *pParse,      /* The parsing context.  Errors accumulate here */
109779     int op,             /* The binary operation */
109780     ExprSpan *pLeft,    /* The left operand */
109781     ExprSpan *pRight    /* The right operand */
109782   ){
109783     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
109784     pOut->zStart = pLeft->zStart;
109785     pOut->zEnd = pRight->zEnd;
109786   }
109787
109788   /* Construct an expression node for a unary postfix operator
109789   */
109790   static void spanUnaryPostfix(
109791     ExprSpan *pOut,        /* Write the new expression node here */
109792     Parse *pParse,         /* Parsing context to record errors */
109793     int op,                /* The operator */
109794     ExprSpan *pOperand,    /* The operand */
109795     Token *pPostOp         /* The operand token for setting the span */
109796   ){
109797     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
109798     pOut->zStart = pOperand->zStart;
109799     pOut->zEnd = &pPostOp->z[pPostOp->n];
109800   }
109801
109802   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
109803   ** unary TK_ISNULL or TK_NOTNULL expression. */
109804   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
109805     sqlite3 *db = pParse->db;
109806     if( db->mallocFailed==0 && pY->op==TK_NULL ){
109807       pA->op = (u8)op;
109808       sqlite3ExprDelete(db, pA->pRight);
109809       pA->pRight = 0;
109810     }
109811   }
109812
109813   /* Construct an expression node for a unary prefix operator
109814   */
109815   static void spanUnaryPrefix(
109816     ExprSpan *pOut,        /* Write the new expression node here */
109817     Parse *pParse,         /* Parsing context to record errors */
109818     int op,                /* The operator */
109819     ExprSpan *pOperand,    /* The operand */
109820     Token *pPreOp         /* The operand token for setting the span */
109821   ){
109822     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
109823     pOut->zStart = pPreOp->z;
109824     pOut->zEnd = pOperand->zEnd;
109825   }
109826 /* Next is all token values, in a form suitable for use by makeheaders.
109827 ** This section will be null unless lemon is run with the -m switch.
109828 */
109829 /*
109830 ** These constants (all generated automatically by the parser generator)
109831 ** specify the various kinds of tokens (terminals) that the parser
109832 ** understands.
109833 **
109834 ** Each symbol here is a terminal symbol in the grammar.
109835 */
109836 /* Make sure the INTERFACE macro is defined.
109837 */
109838 #ifndef INTERFACE
109839 # define INTERFACE 1
109840 #endif
109841 /* The next thing included is series of defines which control
109842 ** various aspects of the generated parser.
109843 **    YYCODETYPE         is the data type used for storing terminal
109844 **                       and nonterminal numbers.  "unsigned char" is
109845 **                       used if there are fewer than 250 terminals
109846 **                       and nonterminals.  "int" is used otherwise.
109847 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
109848 **                       to no legal terminal or nonterminal number.  This
109849 **                       number is used to fill in empty slots of the hash
109850 **                       table.
109851 **    YYFALLBACK         If defined, this indicates that one or more tokens
109852 **                       have fall-back values which should be used if the
109853 **                       original value of the token will not parse.
109854 **    YYACTIONTYPE       is the data type used for storing terminal
109855 **                       and nonterminal numbers.  "unsigned char" is
109856 **                       used if there are fewer than 250 rules and
109857 **                       states combined.  "int" is used otherwise.
109858 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
109859 **                       directly to the parser from the tokenizer.
109860 **    YYMINORTYPE        is the data type used for all minor tokens.
109861 **                       This is typically a union of many types, one of
109862 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
109863 **                       for base tokens is called "yy0".
109864 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
109865 **                       zero the stack is dynamically sized using realloc()
109866 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
109867 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
109868 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
109869 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
109870 **    YYNSTATE           the combined number of states.
109871 **    YYNRULE            the number of rules in the grammar
109872 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
109873 **                       defined, then do no error processing.
109874 */
109875 #define YYCODETYPE unsigned char
109876 #define YYNOCODE 251
109877 #define YYACTIONTYPE unsigned short int
109878 #define YYWILDCARD 67
109879 #define sqlite3ParserTOKENTYPE Token
109880 typedef union {
109881   int yyinit;
109882   sqlite3ParserTOKENTYPE yy0;
109883   struct LimitVal yy64;
109884   Expr* yy122;
109885   Select* yy159;
109886   IdList* yy180;
109887   struct {int value; int mask;} yy207;
109888   u8 yy258;
109889   struct LikeOp yy318;
109890   TriggerStep* yy327;
109891   ExprSpan yy342;
109892   SrcList* yy347;
109893   int yy392;
109894   struct TrigEvent yy410;
109895   ExprList* yy442;
109896   struct ValueList yy487;
109897 } YYMINORTYPE;
109898 #ifndef YYSTACKDEPTH
109899 #define YYSTACKDEPTH 100
109900 #endif
109901 #define sqlite3ParserARG_SDECL Parse *pParse;
109902 #define sqlite3ParserARG_PDECL ,Parse *pParse
109903 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
109904 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
109905 #define YYNSTATE 627
109906 #define YYNRULE 327
109907 #define YYFALLBACK 1
109908 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
109909 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
109910 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
109911
109912 /* The yyzerominor constant is used to initialize instances of
109913 ** YYMINORTYPE objects to zero. */
109914 static const YYMINORTYPE yyzerominor = { 0 };
109915
109916 /* Define the yytestcase() macro to be a no-op if is not already defined
109917 ** otherwise.
109918 **
109919 ** Applications can choose to define yytestcase() in the %include section
109920 ** to a macro that can assist in verifying code coverage.  For production
109921 ** code the yytestcase() macro should be turned off.  But it is useful
109922 ** for testing.
109923 */
109924 #ifndef yytestcase
109925 # define yytestcase(X)
109926 #endif
109927
109928
109929 /* Next are the tables used to determine what action to take based on the
109930 ** current state and lookahead token.  These tables are used to implement
109931 ** functions that take a state number and lookahead value and return an
109932 ** action integer.
109933 **
109934 ** Suppose the action integer is N.  Then the action is determined as
109935 ** follows
109936 **
109937 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
109938 **                                      token onto the stack and goto state N.
109939 **
109940 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
109941 **
109942 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
109943 **
109944 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
109945 **
109946 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
109947 **                                      slots in the yy_action[] table.
109948 **
109949 ** The action table is constructed as a single large table named yy_action[].
109950 ** Given state S and lookahead X, the action is computed as
109951 **
109952 **      yy_action[ yy_shift_ofst[S] + X ]
109953 **
109954 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
109955 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
109956 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
109957 ** and that yy_default[S] should be used instead.
109958 **
109959 ** The formula above is for computing the action when the lookahead is
109960 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
109961 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
109962 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
109963 ** YY_SHIFT_USE_DFLT.
109964 **
109965 ** The following are the tables generated in this section:
109966 **
109967 **  yy_action[]        A single table containing all actions.
109968 **  yy_lookahead[]     A table containing the lookahead for each entry in
109969 **                     yy_action.  Used to detect hash collisions.
109970 **  yy_shift_ofst[]    For each state, the offset into yy_action for
109971 **                     shifting terminals.
109972 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
109973 **                     shifting non-terminals after a reduce.
109974 **  yy_default[]       Default action for each state.
109975 */
109976 #define YY_ACTTAB_COUNT (1564)
109977 static const YYACTIONTYPE yy_action[] = {
109978  /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
109979  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
109980  /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
109981  /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
109982  /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
109983  /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
109984  /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
109985  /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
109986  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
109987  /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
109988  /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
109989  /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
109990  /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
109991  /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
109992  /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
109993  /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
109994  /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
109995  /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
109996  /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
109997  /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
109998  /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
109999  /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110000  /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
110001  /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
110002  /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
110003  /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
110004  /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
110005  /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
110006  /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
110007  /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
110008  /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
110009  /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
110010  /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
110011  /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
110012  /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
110013  /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
110014  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110015  /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
110016  /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
110017  /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
110018  /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
110019  /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
110020  /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110021  /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
110022  /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
110023  /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
110024  /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
110025  /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
110026  /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
110027  /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
110028  /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
110029  /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
110030  /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
110031  /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
110032  /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
110033  /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
110034  /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
110035  /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110036  /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110037  /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
110038  /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
110039  /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
110040  /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
110041  /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
110042  /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
110043  /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
110044  /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
110045  /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
110046  /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
110047  /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
110048  /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
110049  /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
110050  /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
110051  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110052  /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
110053  /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
110054  /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
110055  /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
110056  /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
110057  /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110058  /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
110059  /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
110060  /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
110061  /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
110062  /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
110063  /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
110064  /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
110065  /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
110066  /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
110067  /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
110068  /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
110069  /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
110070  /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
110071  /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
110072  /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110073  /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110074  /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
110075  /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
110076  /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
110077  /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
110078  /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
110079  /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
110080  /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
110081  /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
110082  /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
110083  /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
110084  /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
110085  /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
110086  /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
110087  /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
110088  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110089  /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
110090  /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
110091  /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
110092  /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
110093  /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
110094  /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110095  /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
110096  /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
110097  /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
110098  /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
110099  /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
110100  /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
110101  /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
110102  /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
110103  /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
110104  /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
110105  /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
110106  /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
110107  /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
110108  /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
110109  /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
110110  /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
110111  /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
110112  /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
110113  /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
110114  /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
110115  /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
110116  /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
110117  /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
110118  /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
110119  /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
110120  /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
110121  /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
110122  /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
110123  /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
110124  /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
110125  /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
110126  /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
110127  /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
110128  /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
110129  /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
110130  /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
110131  /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
110132  /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
110133  /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
110134  /*  1560 */   295,  498,  956,  488,
110135 };
110136 static const YYCODETYPE yy_lookahead[] = {
110137  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
110138  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
110139  /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
110140  /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
110141  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
110142  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110143  /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
110144  /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
110145  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110146  /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
110147  /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
110148  /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
110149  /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
110150  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
110151  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
110152  /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
110153  /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
110154  /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
110155  /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
110156  /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
110157  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110158  /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110159  /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
110160  /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
110161  /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
110162  /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
110163  /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
110164  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110165  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
110166  /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
110167  /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
110168  /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
110169  /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
110170  /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
110171  /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
110172  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
110173  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110174  /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
110175  /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
110176  /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
110177  /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
110178  /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
110179  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110180  /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
110181  /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
110182  /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
110183  /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
110184  /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
110185  /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
110186  /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
110187  /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
110188  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
110189  /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
110190  /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
110191  /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
110192  /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
110193  /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
110194  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110195  /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110196  /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
110197  /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
110198  /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
110199  /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
110200  /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
110201  /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110202  /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
110203  /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
110204  /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
110205  /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
110206  /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
110207  /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
110208  /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
110209  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
110210  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110211  /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
110212  /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
110213  /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
110214  /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
110215  /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
110216  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110217  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
110218  /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
110219  /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
110220  /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
110221  /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
110222  /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
110223  /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
110224  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
110225  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
110226  /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
110227  /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
110228  /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
110229  /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
110230  /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
110231  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110232  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110233  /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
110234  /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
110235  /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
110236  /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
110237  /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
110238  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110239  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
110240  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
110241  /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
110242  /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
110243  /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
110244  /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
110245  /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
110246  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
110247  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110248  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
110249  /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
110250  /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
110251  /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
110252  /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
110253  /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110254  /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
110255  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
110256  /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
110257  /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
110258  /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
110259  /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
110260  /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
110261  /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
110262  /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
110263  /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
110264  /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
110265  /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
110266  /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
110267  /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
110268  /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
110269  /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
110270  /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
110271  /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
110272  /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
110273  /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
110274  /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
110275  /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
110276  /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
110277  /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
110278  /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
110279  /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
110280  /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
110281  /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
110282  /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
110283  /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
110284  /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
110285  /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
110286  /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
110287  /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
110288  /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
110289  /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
110290  /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
110291  /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
110292  /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
110293  /*  1560 */   195,  182,  250,  186,
110294 };
110295 #define YY_SHIFT_USE_DFLT (-70)
110296 #define YY_SHIFT_COUNT (416)
110297 #define YY_SHIFT_MIN   (-69)
110298 #define YY_SHIFT_MAX   (1487)
110299 static const short yy_shift_ofst[] = {
110300  /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
110301  /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
110302  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110303  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110304  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
110305  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110306  /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
110307  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
110308  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
110309  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
110310  /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
110311  /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110312  /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
110313  /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
110314  /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
110315  /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110316  /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110317  /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110318  /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
110319  /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
110320  /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
110321  /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
110322  /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
110323  /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
110324  /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
110325  /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
110326  /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
110327  /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
110328  /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
110329  /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
110330  /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
110331  /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
110332  /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
110333  /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
110334  /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
110335  /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
110336  /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
110337  /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
110338  /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
110339  /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
110340  /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
110341  /*   410 */    92,   75,   45,  114,   25,   11,    5,
110342 };
110343 #define YY_REDUCE_USE_DFLT (-169)
110344 #define YY_REDUCE_COUNT (308)
110345 #define YY_REDUCE_MIN   (-168)
110346 #define YY_REDUCE_MAX   (1391)
110347 static const short yy_reduce_ofst[] = {
110348  /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
110349  /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
110350  /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
110351  /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
110352  /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
110353  /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
110354  /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
110355  /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110356  /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110357  /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110358  /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
110359  /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
110360  /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
110361  /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
110362  /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
110363  /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
110364  /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
110365  /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
110366  /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
110367  /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
110368  /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
110369  /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
110370  /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
110371  /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
110372  /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
110373  /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
110374  /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
110375  /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
110376  /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
110377  /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
110378  /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
110379 };
110380 static const YYACTIONTYPE yy_default[] = {
110381  /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
110382  /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
110383  /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110384  /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110385  /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110386  /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110387  /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
110388  /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
110389  /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
110390  /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
110391  /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
110392  /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110393  /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
110394  /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
110395  /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110396  /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
110397  /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110398  /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110399  /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
110400  /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110401  /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
110402  /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
110403  /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
110404  /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
110405  /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
110406  /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
110407  /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
110408  /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
110409  /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
110410  /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
110411  /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
110412  /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
110413  /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
110414  /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
110415  /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
110416  /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
110417  /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
110418  /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110419  /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110420  /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
110421  /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
110422  /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
110423  /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
110424  /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
110425  /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
110426  /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
110427  /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
110428  /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
110429  /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
110430  /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
110431  /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
110432  /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
110433  /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
110434  /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
110435  /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
110436  /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
110437  /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
110438  /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
110439  /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
110440  /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
110441  /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
110442  /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
110443  /*   620 */   665,  639,  636,  635,  631,  630,  628,
110444 };
110445
110446 /* The next table maps tokens into fallback tokens.  If a construct
110447 ** like the following:
110448 **
110449 **      %fallback ID X Y Z.
110450 **
110451 ** appears in the grammar, then ID becomes a fallback token for X, Y,
110452 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
110453 ** but it does not parse, the type of the token is changed to ID and
110454 ** the parse is retried before an error is thrown.
110455 */
110456 #ifdef YYFALLBACK
110457 static const YYCODETYPE yyFallback[] = {
110458     0,  /*          $ => nothing */
110459     0,  /*       SEMI => nothing */
110460    26,  /*    EXPLAIN => ID */
110461    26,  /*      QUERY => ID */
110462    26,  /*       PLAN => ID */
110463    26,  /*      BEGIN => ID */
110464     0,  /* TRANSACTION => nothing */
110465    26,  /*   DEFERRED => ID */
110466    26,  /*  IMMEDIATE => ID */
110467    26,  /*  EXCLUSIVE => ID */
110468     0,  /*     COMMIT => nothing */
110469    26,  /*        END => ID */
110470    26,  /*   ROLLBACK => ID */
110471    26,  /*  SAVEPOINT => ID */
110472    26,  /*    RELEASE => ID */
110473     0,  /*         TO => nothing */
110474     0,  /*      TABLE => nothing */
110475     0,  /*     CREATE => nothing */
110476    26,  /*         IF => ID */
110477     0,  /*        NOT => nothing */
110478     0,  /*     EXISTS => nothing */
110479    26,  /*       TEMP => ID */
110480     0,  /*         LP => nothing */
110481     0,  /*         RP => nothing */
110482     0,  /*         AS => nothing */
110483     0,  /*      COMMA => nothing */
110484     0,  /*         ID => nothing */
110485     0,  /*    INDEXED => nothing */
110486    26,  /*      ABORT => ID */
110487    26,  /*     ACTION => ID */
110488    26,  /*      AFTER => ID */
110489    26,  /*    ANALYZE => ID */
110490    26,  /*        ASC => ID */
110491    26,  /*     ATTACH => ID */
110492    26,  /*     BEFORE => ID */
110493    26,  /*         BY => ID */
110494    26,  /*    CASCADE => ID */
110495    26,  /*       CAST => ID */
110496    26,  /*   COLUMNKW => ID */
110497    26,  /*   CONFLICT => ID */
110498    26,  /*   DATABASE => ID */
110499    26,  /*       DESC => ID */
110500    26,  /*     DETACH => ID */
110501    26,  /*       EACH => ID */
110502    26,  /*       FAIL => ID */
110503    26,  /*        FOR => ID */
110504    26,  /*     IGNORE => ID */
110505    26,  /*  INITIALLY => ID */
110506    26,  /*    INSTEAD => ID */
110507    26,  /*    LIKE_KW => ID */
110508    26,  /*      MATCH => ID */
110509    26,  /*         NO => ID */
110510    26,  /*        KEY => ID */
110511    26,  /*         OF => ID */
110512    26,  /*     OFFSET => ID */
110513    26,  /*     PRAGMA => ID */
110514    26,  /*      RAISE => ID */
110515    26,  /*    REPLACE => ID */
110516    26,  /*   RESTRICT => ID */
110517    26,  /*        ROW => ID */
110518    26,  /*    TRIGGER => ID */
110519    26,  /*     VACUUM => ID */
110520    26,  /*       VIEW => ID */
110521    26,  /*    VIRTUAL => ID */
110522    26,  /*    REINDEX => ID */
110523    26,  /*     RENAME => ID */
110524    26,  /*   CTIME_KW => ID */
110525 };
110526 #endif /* YYFALLBACK */
110527
110528 /* The following structure represents a single element of the
110529 ** parser's stack.  Information stored includes:
110530 **
110531 **   +  The state number for the parser at this level of the stack.
110532 **
110533 **   +  The value of the token stored at this level of the stack.
110534 **      (In other words, the "major" token.)
110535 **
110536 **   +  The semantic value stored at this level of the stack.  This is
110537 **      the information used by the action routines in the grammar.
110538 **      It is sometimes called the "minor" token.
110539 */
110540 struct yyStackEntry {
110541   YYACTIONTYPE stateno;  /* The state-number */
110542   YYCODETYPE major;      /* The major token value.  This is the code
110543                          ** number for the token at this stack level */
110544   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
110545                          ** is the value of the token  */
110546 };
110547 typedef struct yyStackEntry yyStackEntry;
110548
110549 /* The state of the parser is completely contained in an instance of
110550 ** the following structure */
110551 struct yyParser {
110552   int yyidx;                    /* Index of top element in stack */
110553 #ifdef YYTRACKMAXSTACKDEPTH
110554   int yyidxMax;                 /* Maximum value of yyidx */
110555 #endif
110556   int yyerrcnt;                 /* Shifts left before out of the error */
110557   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
110558 #if YYSTACKDEPTH<=0
110559   int yystksz;                  /* Current side of the stack */
110560   yyStackEntry *yystack;        /* The parser's stack */
110561 #else
110562   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
110563 #endif
110564 };
110565 typedef struct yyParser yyParser;
110566
110567 #ifndef NDEBUG
110568 /* #include <stdio.h> */
110569 static FILE *yyTraceFILE = 0;
110570 static char *yyTracePrompt = 0;
110571 #endif /* NDEBUG */
110572
110573 #ifndef NDEBUG
110574 /*
110575 ** Turn parser tracing on by giving a stream to which to write the trace
110576 ** and a prompt to preface each trace message.  Tracing is turned off
110577 ** by making either argument NULL
110578 **
110579 ** Inputs:
110580 ** <ul>
110581 ** <li> A FILE* to which trace output should be written.
110582 **      If NULL, then tracing is turned off.
110583 ** <li> A prefix string written at the beginning of every
110584 **      line of trace output.  If NULL, then tracing is
110585 **      turned off.
110586 ** </ul>
110587 **
110588 ** Outputs:
110589 ** None.
110590 */
110591 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
110592   yyTraceFILE = TraceFILE;
110593   yyTracePrompt = zTracePrompt;
110594   if( yyTraceFILE==0 ) yyTracePrompt = 0;
110595   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
110596 }
110597 #endif /* NDEBUG */
110598
110599 #ifndef NDEBUG
110600 /* For tracing shifts, the names of all terminals and nonterminals
110601 ** are required.  The following table supplies these names */
110602 static const char *const yyTokenName[] = {
110603   "$",             "SEMI",          "EXPLAIN",       "QUERY",
110604   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
110605   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
110606   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
110607   "TABLE",         "CREATE",        "IF",            "NOT",
110608   "EXISTS",        "TEMP",          "LP",            "RP",
110609   "AS",            "COMMA",         "ID",            "INDEXED",
110610   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
110611   "ASC",           "ATTACH",        "BEFORE",        "BY",
110612   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
110613   "DATABASE",      "DESC",          "DETACH",        "EACH",
110614   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
110615   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
110616   "KEY",           "OF",            "OFFSET",        "PRAGMA",
110617   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
110618   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
110619   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
110620   "OR",            "AND",           "IS",            "BETWEEN",
110621   "IN",            "ISNULL",        "NOTNULL",       "NE",
110622   "EQ",            "GT",            "LE",            "LT",
110623   "GE",            "ESCAPE",        "BITAND",        "BITOR",
110624   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
110625   "STAR",          "SLASH",         "REM",           "CONCAT",
110626   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
110627   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
110628   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
110629   "ON",            "INSERT",        "DELETE",        "UPDATE",
110630   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
110631   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
110632   "SELECT",        "DISTINCT",      "DOT",           "FROM",
110633   "JOIN",          "USING",         "ORDER",         "GROUP",
110634   "HAVING",        "LIMIT",         "WHERE",         "INTO",
110635   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
110636   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
110637   "THEN",          "ELSE",          "INDEX",         "ALTER",
110638   "ADD",           "error",         "input",         "cmdlist",
110639   "ecmd",          "explain",       "cmdx",          "cmd",
110640   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
110641   "create_table",  "create_table_args",  "createkw",      "temp",
110642   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
110643   "select",        "column",        "columnid",      "type",
110644   "carglist",      "id",            "ids",           "typetoken",
110645   "typename",      "signed",        "plus_num",      "minus_num",
110646   "ccons",         "term",          "expr",          "onconf",
110647   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",
110648   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
110649   "conslist",      "tconscomma",    "tcons",         "idxlist",
110650   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
110651   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
110652   "distinct",      "selcollist",    "from",          "where_opt",
110653   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
110654   "sclp",          "as",            "seltablist",    "stl_prefix",
110655   "joinop",        "indexed_opt",   "on_opt",        "using_opt",
110656   "joinop2",       "inscollist",    "sortlist",      "nexprlist",
110657   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",
110658   "exprlist",      "likeop",        "between_op",    "in_op",
110659   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",
110660   "collate",       "nmnum",         "number",        "trigger_decl",
110661   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
110662   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
110663   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
110664   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
110665   "lp",            "anylist",
110666 };
110667 #endif /* NDEBUG */
110668
110669 #ifndef NDEBUG
110670 /* For tracing reduce actions, the names of all rules are required.
110671 */
110672 static const char *const yyRuleName[] = {
110673  /*   0 */ "input ::= cmdlist",
110674  /*   1 */ "cmdlist ::= cmdlist ecmd",
110675  /*   2 */ "cmdlist ::= ecmd",
110676  /*   3 */ "ecmd ::= SEMI",
110677  /*   4 */ "ecmd ::= explain cmdx SEMI",
110678  /*   5 */ "explain ::=",
110679  /*   6 */ "explain ::= EXPLAIN",
110680  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
110681  /*   8 */ "cmdx ::= cmd",
110682  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
110683  /*  10 */ "trans_opt ::=",
110684  /*  11 */ "trans_opt ::= TRANSACTION",
110685  /*  12 */ "trans_opt ::= TRANSACTION nm",
110686  /*  13 */ "transtype ::=",
110687  /*  14 */ "transtype ::= DEFERRED",
110688  /*  15 */ "transtype ::= IMMEDIATE",
110689  /*  16 */ "transtype ::= EXCLUSIVE",
110690  /*  17 */ "cmd ::= COMMIT trans_opt",
110691  /*  18 */ "cmd ::= END trans_opt",
110692  /*  19 */ "cmd ::= ROLLBACK trans_opt",
110693  /*  20 */ "savepoint_opt ::= SAVEPOINT",
110694  /*  21 */ "savepoint_opt ::=",
110695  /*  22 */ "cmd ::= SAVEPOINT nm",
110696  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
110697  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
110698  /*  25 */ "cmd ::= create_table create_table_args",
110699  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
110700  /*  27 */ "createkw ::= CREATE",
110701  /*  28 */ "ifnotexists ::=",
110702  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
110703  /*  30 */ "temp ::= TEMP",
110704  /*  31 */ "temp ::=",
110705  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
110706  /*  33 */ "create_table_args ::= AS select",
110707  /*  34 */ "columnlist ::= columnlist COMMA column",
110708  /*  35 */ "columnlist ::= column",
110709  /*  36 */ "column ::= columnid type carglist",
110710  /*  37 */ "columnid ::= nm",
110711  /*  38 */ "id ::= ID",
110712  /*  39 */ "id ::= INDEXED",
110713  /*  40 */ "ids ::= ID|STRING",
110714  /*  41 */ "nm ::= id",
110715  /*  42 */ "nm ::= STRING",
110716  /*  43 */ "nm ::= JOIN_KW",
110717  /*  44 */ "type ::=",
110718  /*  45 */ "type ::= typetoken",
110719  /*  46 */ "typetoken ::= typename",
110720  /*  47 */ "typetoken ::= typename LP signed RP",
110721  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
110722  /*  49 */ "typename ::= ids",
110723  /*  50 */ "typename ::= typename ids",
110724  /*  51 */ "signed ::= plus_num",
110725  /*  52 */ "signed ::= minus_num",
110726  /*  53 */ "carglist ::= carglist ccons",
110727  /*  54 */ "carglist ::=",
110728  /*  55 */ "ccons ::= CONSTRAINT nm",
110729  /*  56 */ "ccons ::= DEFAULT term",
110730  /*  57 */ "ccons ::= DEFAULT LP expr RP",
110731  /*  58 */ "ccons ::= DEFAULT PLUS term",
110732  /*  59 */ "ccons ::= DEFAULT MINUS term",
110733  /*  60 */ "ccons ::= DEFAULT id",
110734  /*  61 */ "ccons ::= NULL onconf",
110735  /*  62 */ "ccons ::= NOT NULL onconf",
110736  /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
110737  /*  64 */ "ccons ::= UNIQUE onconf",
110738  /*  65 */ "ccons ::= CHECK LP expr RP",
110739  /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
110740  /*  67 */ "ccons ::= defer_subclause",
110741  /*  68 */ "ccons ::= COLLATE ids",
110742  /*  69 */ "autoinc ::=",
110743  /*  70 */ "autoinc ::= AUTOINCR",
110744  /*  71 */ "refargs ::=",
110745  /*  72 */ "refargs ::= refargs refarg",
110746  /*  73 */ "refarg ::= MATCH nm",
110747  /*  74 */ "refarg ::= ON INSERT refact",
110748  /*  75 */ "refarg ::= ON DELETE refact",
110749  /*  76 */ "refarg ::= ON UPDATE refact",
110750  /*  77 */ "refact ::= SET NULL",
110751  /*  78 */ "refact ::= SET DEFAULT",
110752  /*  79 */ "refact ::= CASCADE",
110753  /*  80 */ "refact ::= RESTRICT",
110754  /*  81 */ "refact ::= NO ACTION",
110755  /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
110756  /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
110757  /*  84 */ "init_deferred_pred_opt ::=",
110758  /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
110759  /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
110760  /*  87 */ "conslist_opt ::=",
110761  /*  88 */ "conslist_opt ::= COMMA conslist",
110762  /*  89 */ "conslist ::= conslist tconscomma tcons",
110763  /*  90 */ "conslist ::= tcons",
110764  /*  91 */ "tconscomma ::= COMMA",
110765  /*  92 */ "tconscomma ::=",
110766  /*  93 */ "tcons ::= CONSTRAINT nm",
110767  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
110768  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
110769  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
110770  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
110771  /*  98 */ "defer_subclause_opt ::=",
110772  /*  99 */ "defer_subclause_opt ::= defer_subclause",
110773  /* 100 */ "onconf ::=",
110774  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
110775  /* 102 */ "orconf ::=",
110776  /* 103 */ "orconf ::= OR resolvetype",
110777  /* 104 */ "resolvetype ::= raisetype",
110778  /* 105 */ "resolvetype ::= IGNORE",
110779  /* 106 */ "resolvetype ::= REPLACE",
110780  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
110781  /* 108 */ "ifexists ::= IF EXISTS",
110782  /* 109 */ "ifexists ::=",
110783  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
110784  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
110785  /* 112 */ "cmd ::= select",
110786  /* 113 */ "select ::= oneselect",
110787  /* 114 */ "select ::= select multiselect_op oneselect",
110788  /* 115 */ "multiselect_op ::= UNION",
110789  /* 116 */ "multiselect_op ::= UNION ALL",
110790  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
110791  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
110792  /* 119 */ "distinct ::= DISTINCT",
110793  /* 120 */ "distinct ::= ALL",
110794  /* 121 */ "distinct ::=",
110795  /* 122 */ "sclp ::= selcollist COMMA",
110796  /* 123 */ "sclp ::=",
110797  /* 124 */ "selcollist ::= sclp expr as",
110798  /* 125 */ "selcollist ::= sclp STAR",
110799  /* 126 */ "selcollist ::= sclp nm DOT STAR",
110800  /* 127 */ "as ::= AS nm",
110801  /* 128 */ "as ::= ids",
110802  /* 129 */ "as ::=",
110803  /* 130 */ "from ::=",
110804  /* 131 */ "from ::= FROM seltablist",
110805  /* 132 */ "stl_prefix ::= seltablist joinop",
110806  /* 133 */ "stl_prefix ::=",
110807  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
110808  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
110809  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
110810  /* 137 */ "dbnm ::=",
110811  /* 138 */ "dbnm ::= DOT nm",
110812  /* 139 */ "fullname ::= nm dbnm",
110813  /* 140 */ "joinop ::= COMMA|JOIN",
110814  /* 141 */ "joinop ::= JOIN_KW JOIN",
110815  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
110816  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
110817  /* 144 */ "on_opt ::= ON expr",
110818  /* 145 */ "on_opt ::=",
110819  /* 146 */ "indexed_opt ::=",
110820  /* 147 */ "indexed_opt ::= INDEXED BY nm",
110821  /* 148 */ "indexed_opt ::= NOT INDEXED",
110822  /* 149 */ "using_opt ::= USING LP inscollist RP",
110823  /* 150 */ "using_opt ::=",
110824  /* 151 */ "orderby_opt ::=",
110825  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
110826  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
110827  /* 154 */ "sortlist ::= expr sortorder",
110828  /* 155 */ "sortorder ::= ASC",
110829  /* 156 */ "sortorder ::= DESC",
110830  /* 157 */ "sortorder ::=",
110831  /* 158 */ "groupby_opt ::=",
110832  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
110833  /* 160 */ "having_opt ::=",
110834  /* 161 */ "having_opt ::= HAVING expr",
110835  /* 162 */ "limit_opt ::=",
110836  /* 163 */ "limit_opt ::= LIMIT expr",
110837  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
110838  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
110839  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
110840  /* 167 */ "where_opt ::=",
110841  /* 168 */ "where_opt ::= WHERE expr",
110842  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
110843  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
110844  /* 171 */ "setlist ::= nm EQ expr",
110845  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
110846  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
110847  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
110848  /* 175 */ "insert_cmd ::= INSERT orconf",
110849  /* 176 */ "insert_cmd ::= REPLACE",
110850  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
110851  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
110852  /* 179 */ "inscollist_opt ::=",
110853  /* 180 */ "inscollist_opt ::= LP inscollist RP",
110854  /* 181 */ "inscollist ::= inscollist COMMA nm",
110855  /* 182 */ "inscollist ::= nm",
110856  /* 183 */ "expr ::= term",
110857  /* 184 */ "expr ::= LP expr RP",
110858  /* 185 */ "term ::= NULL",
110859  /* 186 */ "expr ::= id",
110860  /* 187 */ "expr ::= JOIN_KW",
110861  /* 188 */ "expr ::= nm DOT nm",
110862  /* 189 */ "expr ::= nm DOT nm DOT nm",
110863  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
110864  /* 191 */ "term ::= STRING",
110865  /* 192 */ "expr ::= REGISTER",
110866  /* 193 */ "expr ::= VARIABLE",
110867  /* 194 */ "expr ::= expr COLLATE ids",
110868  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
110869  /* 196 */ "expr ::= ID LP distinct exprlist RP",
110870  /* 197 */ "expr ::= ID LP STAR RP",
110871  /* 198 */ "term ::= CTIME_KW",
110872  /* 199 */ "expr ::= expr AND expr",
110873  /* 200 */ "expr ::= expr OR expr",
110874  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
110875  /* 202 */ "expr ::= expr EQ|NE expr",
110876  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
110877  /* 204 */ "expr ::= expr PLUS|MINUS expr",
110878  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
110879  /* 206 */ "expr ::= expr CONCAT expr",
110880  /* 207 */ "likeop ::= LIKE_KW",
110881  /* 208 */ "likeop ::= NOT LIKE_KW",
110882  /* 209 */ "likeop ::= MATCH",
110883  /* 210 */ "likeop ::= NOT MATCH",
110884  /* 211 */ "expr ::= expr likeop expr",
110885  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
110886  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
110887  /* 214 */ "expr ::= expr NOT NULL",
110888  /* 215 */ "expr ::= expr IS expr",
110889  /* 216 */ "expr ::= expr IS NOT expr",
110890  /* 217 */ "expr ::= NOT expr",
110891  /* 218 */ "expr ::= BITNOT expr",
110892  /* 219 */ "expr ::= MINUS expr",
110893  /* 220 */ "expr ::= PLUS expr",
110894  /* 221 */ "between_op ::= BETWEEN",
110895  /* 222 */ "between_op ::= NOT BETWEEN",
110896  /* 223 */ "expr ::= expr between_op expr AND expr",
110897  /* 224 */ "in_op ::= IN",
110898  /* 225 */ "in_op ::= NOT IN",
110899  /* 226 */ "expr ::= expr in_op LP exprlist RP",
110900  /* 227 */ "expr ::= LP select RP",
110901  /* 228 */ "expr ::= expr in_op LP select RP",
110902  /* 229 */ "expr ::= expr in_op nm dbnm",
110903  /* 230 */ "expr ::= EXISTS LP select RP",
110904  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
110905  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
110906  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
110907  /* 234 */ "case_else ::= ELSE expr",
110908  /* 235 */ "case_else ::=",
110909  /* 236 */ "case_operand ::= expr",
110910  /* 237 */ "case_operand ::=",
110911  /* 238 */ "exprlist ::= nexprlist",
110912  /* 239 */ "exprlist ::=",
110913  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
110914  /* 241 */ "nexprlist ::= expr",
110915  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
110916  /* 243 */ "uniqueflag ::= UNIQUE",
110917  /* 244 */ "uniqueflag ::=",
110918  /* 245 */ "idxlist_opt ::=",
110919  /* 246 */ "idxlist_opt ::= LP idxlist RP",
110920  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
110921  /* 248 */ "idxlist ::= nm collate sortorder",
110922  /* 249 */ "collate ::=",
110923  /* 250 */ "collate ::= COLLATE ids",
110924  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
110925  /* 252 */ "cmd ::= VACUUM",
110926  /* 253 */ "cmd ::= VACUUM nm",
110927  /* 254 */ "cmd ::= PRAGMA nm dbnm",
110928  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
110929  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
110930  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
110931  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
110932  /* 259 */ "nmnum ::= plus_num",
110933  /* 260 */ "nmnum ::= nm",
110934  /* 261 */ "nmnum ::= ON",
110935  /* 262 */ "nmnum ::= DELETE",
110936  /* 263 */ "nmnum ::= DEFAULT",
110937  /* 264 */ "plus_num ::= PLUS number",
110938  /* 265 */ "plus_num ::= number",
110939  /* 266 */ "minus_num ::= MINUS number",
110940  /* 267 */ "number ::= INTEGER|FLOAT",
110941  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
110942  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
110943  /* 270 */ "trigger_time ::= BEFORE",
110944  /* 271 */ "trigger_time ::= AFTER",
110945  /* 272 */ "trigger_time ::= INSTEAD OF",
110946  /* 273 */ "trigger_time ::=",
110947  /* 274 */ "trigger_event ::= DELETE|INSERT",
110948  /* 275 */ "trigger_event ::= UPDATE",
110949  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
110950  /* 277 */ "foreach_clause ::=",
110951  /* 278 */ "foreach_clause ::= FOR EACH ROW",
110952  /* 279 */ "when_clause ::=",
110953  /* 280 */ "when_clause ::= WHEN expr",
110954  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
110955  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
110956  /* 283 */ "trnm ::= nm",
110957  /* 284 */ "trnm ::= nm DOT nm",
110958  /* 285 */ "tridxby ::=",
110959  /* 286 */ "tridxby ::= INDEXED BY nm",
110960  /* 287 */ "tridxby ::= NOT INDEXED",
110961  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
110962  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
110963  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
110964  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
110965  /* 292 */ "trigger_cmd ::= select",
110966  /* 293 */ "expr ::= RAISE LP IGNORE RP",
110967  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
110968  /* 295 */ "raisetype ::= ROLLBACK",
110969  /* 296 */ "raisetype ::= ABORT",
110970  /* 297 */ "raisetype ::= FAIL",
110971  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
110972  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
110973  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
110974  /* 301 */ "key_opt ::=",
110975  /* 302 */ "key_opt ::= KEY expr",
110976  /* 303 */ "database_kw_opt ::= DATABASE",
110977  /* 304 */ "database_kw_opt ::=",
110978  /* 305 */ "cmd ::= REINDEX",
110979  /* 306 */ "cmd ::= REINDEX nm dbnm",
110980  /* 307 */ "cmd ::= ANALYZE",
110981  /* 308 */ "cmd ::= ANALYZE nm dbnm",
110982  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
110983  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
110984  /* 311 */ "add_column_fullname ::= fullname",
110985  /* 312 */ "kwcolumn_opt ::=",
110986  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
110987  /* 314 */ "cmd ::= create_vtab",
110988  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
110989  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
110990  /* 317 */ "vtabarglist ::= vtabarg",
110991  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
110992  /* 319 */ "vtabarg ::=",
110993  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
110994  /* 321 */ "vtabargtoken ::= ANY",
110995  /* 322 */ "vtabargtoken ::= lp anylist RP",
110996  /* 323 */ "lp ::= LP",
110997  /* 324 */ "anylist ::=",
110998  /* 325 */ "anylist ::= anylist LP anylist RP",
110999  /* 326 */ "anylist ::= anylist ANY",
111000 };
111001 #endif /* NDEBUG */
111002
111003
111004 #if YYSTACKDEPTH<=0
111005 /*
111006 ** Try to increase the size of the parser stack.
111007 */
111008 static void yyGrowStack(yyParser *p){
111009   int newSize;
111010   yyStackEntry *pNew;
111011
111012   newSize = p->yystksz*2 + 100;
111013   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
111014   if( pNew ){
111015     p->yystack = pNew;
111016     p->yystksz = newSize;
111017 #ifndef NDEBUG
111018     if( yyTraceFILE ){
111019       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
111020               yyTracePrompt, p->yystksz);
111021     }
111022 #endif
111023   }
111024 }
111025 #endif
111026
111027 /*
111028 ** This function allocates a new parser.
111029 ** The only argument is a pointer to a function which works like
111030 ** malloc.
111031 **
111032 ** Inputs:
111033 ** A pointer to the function used to allocate memory.
111034 **
111035 ** Outputs:
111036 ** A pointer to a parser.  This pointer is used in subsequent calls
111037 ** to sqlite3Parser and sqlite3ParserFree.
111038 */
111039 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
111040   yyParser *pParser;
111041   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
111042   if( pParser ){
111043     pParser->yyidx = -1;
111044 #ifdef YYTRACKMAXSTACKDEPTH
111045     pParser->yyidxMax = 0;
111046 #endif
111047 #if YYSTACKDEPTH<=0
111048     pParser->yystack = NULL;
111049     pParser->yystksz = 0;
111050     yyGrowStack(pParser);
111051 #endif
111052   }
111053   return pParser;
111054 }
111055
111056 /* The following function deletes the value associated with a
111057 ** symbol.  The symbol can be either a terminal or nonterminal.
111058 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
111059 ** the value.
111060 */
111061 static void yy_destructor(
111062   yyParser *yypParser,    /* The parser */
111063   YYCODETYPE yymajor,     /* Type code for object to destroy */
111064   YYMINORTYPE *yypminor   /* The object to be destroyed */
111065 ){
111066   sqlite3ParserARG_FETCH;
111067   switch( yymajor ){
111068     /* Here is inserted the actions which take place when a
111069     ** terminal or non-terminal is destroyed.  This can happen
111070     ** when the symbol is popped from the stack during a
111071     ** reduce or during error processing or when a parser is
111072     ** being destroyed before it is finished parsing.
111073     **
111074     ** Note: during a reduce, the only symbols destroyed are those
111075     ** which appear on the RHS of the rule, but which are not used
111076     ** inside the C code.
111077     */
111078     case 160: /* select */
111079     case 194: /* oneselect */
111080 {
111081 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
111082 }
111083       break;
111084     case 173: /* term */
111085     case 174: /* expr */
111086 {
111087 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
111088 }
111089       break;
111090     case 178: /* idxlist_opt */
111091     case 187: /* idxlist */
111092     case 197: /* selcollist */
111093     case 200: /* groupby_opt */
111094     case 202: /* orderby_opt */
111095     case 204: /* sclp */
111096     case 214: /* sortlist */
111097     case 215: /* nexprlist */
111098     case 216: /* setlist */
111099     case 220: /* exprlist */
111100     case 225: /* case_exprlist */
111101 {
111102 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
111103 }
111104       break;
111105     case 193: /* fullname */
111106     case 198: /* from */
111107     case 206: /* seltablist */
111108     case 207: /* stl_prefix */
111109 {
111110 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
111111 }
111112       break;
111113     case 199: /* where_opt */
111114     case 201: /* having_opt */
111115     case 210: /* on_opt */
111116     case 224: /* case_operand */
111117     case 226: /* case_else */
111118     case 236: /* when_clause */
111119     case 241: /* key_opt */
111120 {
111121 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
111122 }
111123       break;
111124     case 211: /* using_opt */
111125     case 213: /* inscollist */
111126     case 218: /* inscollist_opt */
111127 {
111128 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
111129 }
111130       break;
111131     case 219: /* valuelist */
111132 {
111133
111134   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
111135   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
111136
111137 }
111138       break;
111139     case 232: /* trigger_cmd_list */
111140     case 237: /* trigger_cmd */
111141 {
111142 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
111143 }
111144       break;
111145     case 234: /* trigger_event */
111146 {
111147 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
111148 }
111149       break;
111150     default:  break;   /* If no destructor action specified: do nothing */
111151   }
111152 }
111153
111154 /*
111155 ** Pop the parser's stack once.
111156 **
111157 ** If there is a destructor routine associated with the token which
111158 ** is popped from the stack, then call it.
111159 **
111160 ** Return the major token number for the symbol popped.
111161 */
111162 static int yy_pop_parser_stack(yyParser *pParser){
111163   YYCODETYPE yymajor;
111164   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
111165
111166   /* There is no mechanism by which the parser stack can be popped below
111167   ** empty in SQLite.  */
111168   if( NEVER(pParser->yyidx<0) ) return 0;
111169 #ifndef NDEBUG
111170   if( yyTraceFILE && pParser->yyidx>=0 ){
111171     fprintf(yyTraceFILE,"%sPopping %s\n",
111172       yyTracePrompt,
111173       yyTokenName[yytos->major]);
111174   }
111175 #endif
111176   yymajor = yytos->major;
111177   yy_destructor(pParser, yymajor, &yytos->minor);
111178   pParser->yyidx--;
111179   return yymajor;
111180 }
111181
111182 /*
111183 ** Deallocate and destroy a parser.  Destructors are all called for
111184 ** all stack elements before shutting the parser down.
111185 **
111186 ** Inputs:
111187 ** <ul>
111188 ** <li>  A pointer to the parser.  This should be a pointer
111189 **       obtained from sqlite3ParserAlloc.
111190 ** <li>  A pointer to a function used to reclaim memory obtained
111191 **       from malloc.
111192 ** </ul>
111193 */
111194 SQLITE_PRIVATE void sqlite3ParserFree(
111195   void *p,                    /* The parser to be deleted */
111196   void (*freeProc)(void*)     /* Function used to reclaim memory */
111197 ){
111198   yyParser *pParser = (yyParser*)p;
111199   /* In SQLite, we never try to destroy a parser that was not successfully
111200   ** created in the first place. */
111201   if( NEVER(pParser==0) ) return;
111202   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
111203 #if YYSTACKDEPTH<=0
111204   free(pParser->yystack);
111205 #endif
111206   (*freeProc)((void*)pParser);
111207 }
111208
111209 /*
111210 ** Return the peak depth of the stack for a parser.
111211 */
111212 #ifdef YYTRACKMAXSTACKDEPTH
111213 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
111214   yyParser *pParser = (yyParser*)p;
111215   return pParser->yyidxMax;
111216 }
111217 #endif
111218
111219 /*
111220 ** Find the appropriate action for a parser given the terminal
111221 ** look-ahead token iLookAhead.
111222 **
111223 ** If the look-ahead token is YYNOCODE, then check to see if the action is
111224 ** independent of the look-ahead.  If it is, return the action, otherwise
111225 ** return YY_NO_ACTION.
111226 */
111227 static int yy_find_shift_action(
111228   yyParser *pParser,        /* The parser */
111229   YYCODETYPE iLookAhead     /* The look-ahead token */
111230 ){
111231   int i;
111232   int stateno = pParser->yystack[pParser->yyidx].stateno;
111233
111234   if( stateno>YY_SHIFT_COUNT
111235    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
111236     return yy_default[stateno];
111237   }
111238   assert( iLookAhead!=YYNOCODE );
111239   i += iLookAhead;
111240   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
111241     if( iLookAhead>0 ){
111242 #ifdef YYFALLBACK
111243       YYCODETYPE iFallback;            /* Fallback token */
111244       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
111245              && (iFallback = yyFallback[iLookAhead])!=0 ){
111246 #ifndef NDEBUG
111247         if( yyTraceFILE ){
111248           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
111249              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
111250         }
111251 #endif
111252         return yy_find_shift_action(pParser, iFallback);
111253       }
111254 #endif
111255 #ifdef YYWILDCARD
111256       {
111257         int j = i - iLookAhead + YYWILDCARD;
111258         if(
111259 #if YY_SHIFT_MIN+YYWILDCARD<0
111260           j>=0 &&
111261 #endif
111262 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
111263           j<YY_ACTTAB_COUNT &&
111264 #endif
111265           yy_lookahead[j]==YYWILDCARD
111266         ){
111267 #ifndef NDEBUG
111268           if( yyTraceFILE ){
111269             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
111270                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
111271           }
111272 #endif /* NDEBUG */
111273           return yy_action[j];
111274         }
111275       }
111276 #endif /* YYWILDCARD */
111277     }
111278     return yy_default[stateno];
111279   }else{
111280     return yy_action[i];
111281   }
111282 }
111283
111284 /*
111285 ** Find the appropriate action for a parser given the non-terminal
111286 ** look-ahead token iLookAhead.
111287 **
111288 ** If the look-ahead token is YYNOCODE, then check to see if the action is
111289 ** independent of the look-ahead.  If it is, return the action, otherwise
111290 ** return YY_NO_ACTION.
111291 */
111292 static int yy_find_reduce_action(
111293   int stateno,              /* Current state number */
111294   YYCODETYPE iLookAhead     /* The look-ahead token */
111295 ){
111296   int i;
111297 #ifdef YYERRORSYMBOL
111298   if( stateno>YY_REDUCE_COUNT ){
111299     return yy_default[stateno];
111300   }
111301 #else
111302   assert( stateno<=YY_REDUCE_COUNT );
111303 #endif
111304   i = yy_reduce_ofst[stateno];
111305   assert( i!=YY_REDUCE_USE_DFLT );
111306   assert( iLookAhead!=YYNOCODE );
111307   i += iLookAhead;
111308 #ifdef YYERRORSYMBOL
111309   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
111310     return yy_default[stateno];
111311   }
111312 #else
111313   assert( i>=0 && i<YY_ACTTAB_COUNT );
111314   assert( yy_lookahead[i]==iLookAhead );
111315 #endif
111316   return yy_action[i];
111317 }
111318
111319 /*
111320 ** The following routine is called if the stack overflows.
111321 */
111322 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
111323    sqlite3ParserARG_FETCH;
111324    yypParser->yyidx--;
111325 #ifndef NDEBUG
111326    if( yyTraceFILE ){
111327      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
111328    }
111329 #endif
111330    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111331    /* Here code is inserted which will execute if the parser
111332    ** stack every overflows */
111333
111334   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
111335   sqlite3ErrorMsg(pParse, "parser stack overflow");
111336    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
111337 }
111338
111339 /*
111340 ** Perform a shift action.
111341 */
111342 static void yy_shift(
111343   yyParser *yypParser,          /* The parser to be shifted */
111344   int yyNewState,               /* The new state to shift in */
111345   int yyMajor,                  /* The major token to shift in */
111346   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
111347 ){
111348   yyStackEntry *yytos;
111349   yypParser->yyidx++;
111350 #ifdef YYTRACKMAXSTACKDEPTH
111351   if( yypParser->yyidx>yypParser->yyidxMax ){
111352     yypParser->yyidxMax = yypParser->yyidx;
111353   }
111354 #endif
111355 #if YYSTACKDEPTH>0
111356   if( yypParser->yyidx>=YYSTACKDEPTH ){
111357     yyStackOverflow(yypParser, yypMinor);
111358     return;
111359   }
111360 #else
111361   if( yypParser->yyidx>=yypParser->yystksz ){
111362     yyGrowStack(yypParser);
111363     if( yypParser->yyidx>=yypParser->yystksz ){
111364       yyStackOverflow(yypParser, yypMinor);
111365       return;
111366     }
111367   }
111368 #endif
111369   yytos = &yypParser->yystack[yypParser->yyidx];
111370   yytos->stateno = (YYACTIONTYPE)yyNewState;
111371   yytos->major = (YYCODETYPE)yyMajor;
111372   yytos->minor = *yypMinor;
111373 #ifndef NDEBUG
111374   if( yyTraceFILE && yypParser->yyidx>0 ){
111375     int i;
111376     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
111377     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
111378     for(i=1; i<=yypParser->yyidx; i++)
111379       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
111380     fprintf(yyTraceFILE,"\n");
111381   }
111382 #endif
111383 }
111384
111385 /* The following table contains information about every rule that
111386 ** is used during the reduce.
111387 */
111388 static const struct {
111389   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
111390   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
111391 } yyRuleInfo[] = {
111392   { 142, 1 },
111393   { 143, 2 },
111394   { 143, 1 },
111395   { 144, 1 },
111396   { 144, 3 },
111397   { 145, 0 },
111398   { 145, 1 },
111399   { 145, 3 },
111400   { 146, 1 },
111401   { 147, 3 },
111402   { 149, 0 },
111403   { 149, 1 },
111404   { 149, 2 },
111405   { 148, 0 },
111406   { 148, 1 },
111407   { 148, 1 },
111408   { 148, 1 },
111409   { 147, 2 },
111410   { 147, 2 },
111411   { 147, 2 },
111412   { 151, 1 },
111413   { 151, 0 },
111414   { 147, 2 },
111415   { 147, 3 },
111416   { 147, 5 },
111417   { 147, 2 },
111418   { 152, 6 },
111419   { 154, 1 },
111420   { 156, 0 },
111421   { 156, 3 },
111422   { 155, 1 },
111423   { 155, 0 },
111424   { 153, 4 },
111425   { 153, 2 },
111426   { 158, 3 },
111427   { 158, 1 },
111428   { 161, 3 },
111429   { 162, 1 },
111430   { 165, 1 },
111431   { 165, 1 },
111432   { 166, 1 },
111433   { 150, 1 },
111434   { 150, 1 },
111435   { 150, 1 },
111436   { 163, 0 },
111437   { 163, 1 },
111438   { 167, 1 },
111439   { 167, 4 },
111440   { 167, 6 },
111441   { 168, 1 },
111442   { 168, 2 },
111443   { 169, 1 },
111444   { 169, 1 },
111445   { 164, 2 },
111446   { 164, 0 },
111447   { 172, 2 },
111448   { 172, 2 },
111449   { 172, 4 },
111450   { 172, 3 },
111451   { 172, 3 },
111452   { 172, 2 },
111453   { 172, 2 },
111454   { 172, 3 },
111455   { 172, 5 },
111456   { 172, 2 },
111457   { 172, 4 },
111458   { 172, 4 },
111459   { 172, 1 },
111460   { 172, 2 },
111461   { 177, 0 },
111462   { 177, 1 },
111463   { 179, 0 },
111464   { 179, 2 },
111465   { 181, 2 },
111466   { 181, 3 },
111467   { 181, 3 },
111468   { 181, 3 },
111469   { 182, 2 },
111470   { 182, 2 },
111471   { 182, 1 },
111472   { 182, 1 },
111473   { 182, 2 },
111474   { 180, 3 },
111475   { 180, 2 },
111476   { 183, 0 },
111477   { 183, 2 },
111478   { 183, 2 },
111479   { 159, 0 },
111480   { 159, 2 },
111481   { 184, 3 },
111482   { 184, 1 },
111483   { 185, 1 },
111484   { 185, 0 },
111485   { 186, 2 },
111486   { 186, 7 },
111487   { 186, 5 },
111488   { 186, 5 },
111489   { 186, 10 },
111490   { 188, 0 },
111491   { 188, 1 },
111492   { 175, 0 },
111493   { 175, 3 },
111494   { 189, 0 },
111495   { 189, 2 },
111496   { 190, 1 },
111497   { 190, 1 },
111498   { 190, 1 },
111499   { 147, 4 },
111500   { 192, 2 },
111501   { 192, 0 },
111502   { 147, 8 },
111503   { 147, 4 },
111504   { 147, 1 },
111505   { 160, 1 },
111506   { 160, 3 },
111507   { 195, 1 },
111508   { 195, 2 },
111509   { 195, 1 },
111510   { 194, 9 },
111511   { 196, 1 },
111512   { 196, 1 },
111513   { 196, 0 },
111514   { 204, 2 },
111515   { 204, 0 },
111516   { 197, 3 },
111517   { 197, 2 },
111518   { 197, 4 },
111519   { 205, 2 },
111520   { 205, 1 },
111521   { 205, 0 },
111522   { 198, 0 },
111523   { 198, 2 },
111524   { 207, 2 },
111525   { 207, 0 },
111526   { 206, 7 },
111527   { 206, 7 },
111528   { 206, 7 },
111529   { 157, 0 },
111530   { 157, 2 },
111531   { 193, 2 },
111532   { 208, 1 },
111533   { 208, 2 },
111534   { 208, 3 },
111535   { 208, 4 },
111536   { 210, 2 },
111537   { 210, 0 },
111538   { 209, 0 },
111539   { 209, 3 },
111540   { 209, 2 },
111541   { 211, 4 },
111542   { 211, 0 },
111543   { 202, 0 },
111544   { 202, 3 },
111545   { 214, 4 },
111546   { 214, 2 },
111547   { 176, 1 },
111548   { 176, 1 },
111549   { 176, 0 },
111550   { 200, 0 },
111551   { 200, 3 },
111552   { 201, 0 },
111553   { 201, 2 },
111554   { 203, 0 },
111555   { 203, 2 },
111556   { 203, 4 },
111557   { 203, 4 },
111558   { 147, 5 },
111559   { 199, 0 },
111560   { 199, 2 },
111561   { 147, 7 },
111562   { 216, 5 },
111563   { 216, 3 },
111564   { 147, 5 },
111565   { 147, 5 },
111566   { 147, 6 },
111567   { 217, 2 },
111568   { 217, 1 },
111569   { 219, 4 },
111570   { 219, 5 },
111571   { 218, 0 },
111572   { 218, 3 },
111573   { 213, 3 },
111574   { 213, 1 },
111575   { 174, 1 },
111576   { 174, 3 },
111577   { 173, 1 },
111578   { 174, 1 },
111579   { 174, 1 },
111580   { 174, 3 },
111581   { 174, 5 },
111582   { 173, 1 },
111583   { 173, 1 },
111584   { 174, 1 },
111585   { 174, 1 },
111586   { 174, 3 },
111587   { 174, 6 },
111588   { 174, 5 },
111589   { 174, 4 },
111590   { 173, 1 },
111591   { 174, 3 },
111592   { 174, 3 },
111593   { 174, 3 },
111594   { 174, 3 },
111595   { 174, 3 },
111596   { 174, 3 },
111597   { 174, 3 },
111598   { 174, 3 },
111599   { 221, 1 },
111600   { 221, 2 },
111601   { 221, 1 },
111602   { 221, 2 },
111603   { 174, 3 },
111604   { 174, 5 },
111605   { 174, 2 },
111606   { 174, 3 },
111607   { 174, 3 },
111608   { 174, 4 },
111609   { 174, 2 },
111610   { 174, 2 },
111611   { 174, 2 },
111612   { 174, 2 },
111613   { 222, 1 },
111614   { 222, 2 },
111615   { 174, 5 },
111616   { 223, 1 },
111617   { 223, 2 },
111618   { 174, 5 },
111619   { 174, 3 },
111620   { 174, 5 },
111621   { 174, 4 },
111622   { 174, 4 },
111623   { 174, 5 },
111624   { 225, 5 },
111625   { 225, 4 },
111626   { 226, 2 },
111627   { 226, 0 },
111628   { 224, 1 },
111629   { 224, 0 },
111630   { 220, 1 },
111631   { 220, 0 },
111632   { 215, 3 },
111633   { 215, 1 },
111634   { 147, 11 },
111635   { 227, 1 },
111636   { 227, 0 },
111637   { 178, 0 },
111638   { 178, 3 },
111639   { 187, 5 },
111640   { 187, 3 },
111641   { 228, 0 },
111642   { 228, 2 },
111643   { 147, 4 },
111644   { 147, 1 },
111645   { 147, 2 },
111646   { 147, 3 },
111647   { 147, 5 },
111648   { 147, 6 },
111649   { 147, 5 },
111650   { 147, 6 },
111651   { 229, 1 },
111652   { 229, 1 },
111653   { 229, 1 },
111654   { 229, 1 },
111655   { 229, 1 },
111656   { 170, 2 },
111657   { 170, 1 },
111658   { 171, 2 },
111659   { 230, 1 },
111660   { 147, 5 },
111661   { 231, 11 },
111662   { 233, 1 },
111663   { 233, 1 },
111664   { 233, 2 },
111665   { 233, 0 },
111666   { 234, 1 },
111667   { 234, 1 },
111668   { 234, 3 },
111669   { 235, 0 },
111670   { 235, 3 },
111671   { 236, 0 },
111672   { 236, 2 },
111673   { 232, 3 },
111674   { 232, 2 },
111675   { 238, 1 },
111676   { 238, 3 },
111677   { 239, 0 },
111678   { 239, 3 },
111679   { 239, 2 },
111680   { 237, 7 },
111681   { 237, 5 },
111682   { 237, 5 },
111683   { 237, 5 },
111684   { 237, 1 },
111685   { 174, 4 },
111686   { 174, 6 },
111687   { 191, 1 },
111688   { 191, 1 },
111689   { 191, 1 },
111690   { 147, 4 },
111691   { 147, 6 },
111692   { 147, 3 },
111693   { 241, 0 },
111694   { 241, 2 },
111695   { 240, 1 },
111696   { 240, 0 },
111697   { 147, 1 },
111698   { 147, 3 },
111699   { 147, 1 },
111700   { 147, 3 },
111701   { 147, 6 },
111702   { 147, 6 },
111703   { 242, 1 },
111704   { 243, 0 },
111705   { 243, 1 },
111706   { 147, 1 },
111707   { 147, 4 },
111708   { 244, 8 },
111709   { 245, 1 },
111710   { 245, 3 },
111711   { 246, 0 },
111712   { 246, 2 },
111713   { 247, 1 },
111714   { 247, 3 },
111715   { 248, 1 },
111716   { 249, 0 },
111717   { 249, 4 },
111718   { 249, 2 },
111719 };
111720
111721 static void yy_accept(yyParser*);  /* Forward Declaration */
111722
111723 /*
111724 ** Perform a reduce action and the shift that must immediately
111725 ** follow the reduce.
111726 */
111727 static void yy_reduce(
111728   yyParser *yypParser,         /* The parser */
111729   int yyruleno                 /* Number of the rule by which to reduce */
111730 ){
111731   int yygoto;                     /* The next state */
111732   int yyact;                      /* The next action */
111733   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
111734   yyStackEntry *yymsp;            /* The top of the parser's stack */
111735   int yysize;                     /* Amount to pop the stack */
111736   sqlite3ParserARG_FETCH;
111737   yymsp = &yypParser->yystack[yypParser->yyidx];
111738 #ifndef NDEBUG
111739   if( yyTraceFILE && yyruleno>=0
111740         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
111741     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
111742       yyRuleName[yyruleno]);
111743   }
111744 #endif /* NDEBUG */
111745
111746   /* Silence complaints from purify about yygotominor being uninitialized
111747   ** in some cases when it is copied into the stack after the following
111748   ** switch.  yygotominor is uninitialized when a rule reduces that does
111749   ** not set the value of its left-hand side nonterminal.  Leaving the
111750   ** value of the nonterminal uninitialized is utterly harmless as long
111751   ** as the value is never used.  So really the only thing this code
111752   ** accomplishes is to quieten purify.
111753   **
111754   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
111755   ** without this code, their parser segfaults.  I'm not sure what there
111756   ** parser is doing to make this happen.  This is the second bug report
111757   ** from wireshark this week.  Clearly they are stressing Lemon in ways
111758   ** that it has not been previously stressed...  (SQLite ticket #2172)
111759   */
111760   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
111761   yygotominor = yyzerominor;
111762
111763
111764   switch( yyruleno ){
111765   /* Beginning here are the reduction cases.  A typical example
111766   ** follows:
111767   **   case 0:
111768   **  #line <lineno> <grammarfile>
111769   **     { ... }           // User supplied code
111770   **  #line <lineno> <thisfile>
111771   **     break;
111772   */
111773       case 5: /* explain ::= */
111774 { sqlite3BeginParse(pParse, 0); }
111775         break;
111776       case 6: /* explain ::= EXPLAIN */
111777 { sqlite3BeginParse(pParse, 1); }
111778         break;
111779       case 7: /* explain ::= EXPLAIN QUERY PLAN */
111780 { sqlite3BeginParse(pParse, 2); }
111781         break;
111782       case 8: /* cmdx ::= cmd */
111783 { sqlite3FinishCoding(pParse); }
111784         break;
111785       case 9: /* cmd ::= BEGIN transtype trans_opt */
111786 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
111787         break;
111788       case 13: /* transtype ::= */
111789 {yygotominor.yy392 = TK_DEFERRED;}
111790         break;
111791       case 14: /* transtype ::= DEFERRED */
111792       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
111793       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
111794       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
111795       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
111796 {yygotominor.yy392 = yymsp[0].major;}
111797         break;
111798       case 17: /* cmd ::= COMMIT trans_opt */
111799       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
111800 {sqlite3CommitTransaction(pParse);}
111801         break;
111802       case 19: /* cmd ::= ROLLBACK trans_opt */
111803 {sqlite3RollbackTransaction(pParse);}
111804         break;
111805       case 22: /* cmd ::= SAVEPOINT nm */
111806 {
111807   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
111808 }
111809         break;
111810       case 23: /* cmd ::= RELEASE savepoint_opt nm */
111811 {
111812   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
111813 }
111814         break;
111815       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
111816 {
111817   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
111818 }
111819         break;
111820       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
111821 {
111822    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
111823 }
111824         break;
111825       case 27: /* createkw ::= CREATE */
111826 {
111827   pParse->db->lookaside.bEnabled = 0;
111828   yygotominor.yy0 = yymsp[0].minor.yy0;
111829 }
111830         break;
111831       case 28: /* ifnotexists ::= */
111832       case 31: /* temp ::= */ yytestcase(yyruleno==31);
111833       case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
111834       case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
111835       case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
111836       case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
111837       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
111838       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
111839       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
111840       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
111841       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
111842       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
111843 {yygotominor.yy392 = 0;}
111844         break;
111845       case 29: /* ifnotexists ::= IF NOT EXISTS */
111846       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
111847       case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
111848       case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
111849       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
111850       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
111851       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
111852       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
111853 {yygotominor.yy392 = 1;}
111854         break;
111855       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
111856 {
111857   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
111858 }
111859         break;
111860       case 33: /* create_table_args ::= AS select */
111861 {
111862   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
111863   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
111864 }
111865         break;
111866       case 36: /* column ::= columnid type carglist */
111867 {
111868   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
111869   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
111870 }
111871         break;
111872       case 37: /* columnid ::= nm */
111873 {
111874   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
111875   yygotominor.yy0 = yymsp[0].minor.yy0;
111876   pParse->constraintName.n = 0;
111877 }
111878         break;
111879       case 38: /* id ::= ID */
111880       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
111881       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
111882       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
111883       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
111884       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
111885       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
111886       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
111887       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
111888       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
111889       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
111890       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
111891       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
111892       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
111893       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
111894       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
111895       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
111896       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
111897       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
111898       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
111899       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
111900       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
111901       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
111902 {yygotominor.yy0 = yymsp[0].minor.yy0;}
111903         break;
111904       case 45: /* type ::= typetoken */
111905 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
111906         break;
111907       case 47: /* typetoken ::= typename LP signed RP */
111908 {
111909   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
111910   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
111911 }
111912         break;
111913       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
111914 {
111915   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
111916   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
111917 }
111918         break;
111919       case 50: /* typename ::= typename ids */
111920 {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);}
111921         break;
111922       case 55: /* ccons ::= CONSTRAINT nm */
111923       case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
111924 {pParse->constraintName = yymsp[0].minor.yy0;}
111925         break;
111926       case 56: /* ccons ::= DEFAULT term */
111927       case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
111928 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
111929         break;
111930       case 57: /* ccons ::= DEFAULT LP expr RP */
111931 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
111932         break;
111933       case 59: /* ccons ::= DEFAULT MINUS term */
111934 {
111935   ExprSpan v;
111936   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
111937   v.zStart = yymsp[-1].minor.yy0.z;
111938   v.zEnd = yymsp[0].minor.yy342.zEnd;
111939   sqlite3AddDefaultValue(pParse,&v);
111940 }
111941         break;
111942       case 60: /* ccons ::= DEFAULT id */
111943 {
111944   ExprSpan v;
111945   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
111946   sqlite3AddDefaultValue(pParse,&v);
111947 }
111948         break;
111949       case 62: /* ccons ::= NOT NULL onconf */
111950 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
111951         break;
111952       case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
111953 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
111954         break;
111955       case 64: /* ccons ::= UNIQUE onconf */
111956 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
111957         break;
111958       case 65: /* ccons ::= CHECK LP expr RP */
111959 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
111960         break;
111961       case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
111962 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
111963         break;
111964       case 67: /* ccons ::= defer_subclause */
111965 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
111966         break;
111967       case 68: /* ccons ::= COLLATE ids */
111968 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
111969         break;
111970       case 71: /* refargs ::= */
111971 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
111972         break;
111973       case 72: /* refargs ::= refargs refarg */
111974 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
111975         break;
111976       case 73: /* refarg ::= MATCH nm */
111977       case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
111978 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
111979         break;
111980       case 75: /* refarg ::= ON DELETE refact */
111981 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
111982         break;
111983       case 76: /* refarg ::= ON UPDATE refact */
111984 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
111985         break;
111986       case 77: /* refact ::= SET NULL */
111987 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
111988         break;
111989       case 78: /* refact ::= SET DEFAULT */
111990 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
111991         break;
111992       case 79: /* refact ::= CASCADE */
111993 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
111994         break;
111995       case 80: /* refact ::= RESTRICT */
111996 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
111997         break;
111998       case 81: /* refact ::= NO ACTION */
111999 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
112000         break;
112001       case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
112002       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
112003       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
112004       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
112005 {yygotominor.yy392 = yymsp[0].minor.yy392;}
112006         break;
112007       case 87: /* conslist_opt ::= */
112008 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
112009         break;
112010       case 88: /* conslist_opt ::= COMMA conslist */
112011 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
112012         break;
112013       case 91: /* tconscomma ::= COMMA */
112014 {pParse->constraintName.n = 0;}
112015         break;
112016       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
112017 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
112018         break;
112019       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
112020 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
112021         break;
112022       case 96: /* tcons ::= CHECK LP expr RP onconf */
112023 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
112024         break;
112025       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
112026 {
112027     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
112028     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
112029 }
112030         break;
112031       case 100: /* onconf ::= */
112032 {yygotominor.yy392 = OE_Default;}
112033         break;
112034       case 102: /* orconf ::= */
112035 {yygotominor.yy258 = OE_Default;}
112036         break;
112037       case 103: /* orconf ::= OR resolvetype */
112038 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
112039         break;
112040       case 105: /* resolvetype ::= IGNORE */
112041 {yygotominor.yy392 = OE_Ignore;}
112042         break;
112043       case 106: /* resolvetype ::= REPLACE */
112044 {yygotominor.yy392 = OE_Replace;}
112045         break;
112046       case 107: /* cmd ::= DROP TABLE ifexists fullname */
112047 {
112048   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
112049 }
112050         break;
112051       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
112052 {
112053   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);
112054 }
112055         break;
112056       case 111: /* cmd ::= DROP VIEW ifexists fullname */
112057 {
112058   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
112059 }
112060         break;
112061       case 112: /* cmd ::= select */
112062 {
112063   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
112064   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
112065   sqlite3ExplainBegin(pParse->pVdbe);
112066   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
112067   sqlite3ExplainFinish(pParse->pVdbe);
112068   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
112069 }
112070         break;
112071       case 113: /* select ::= oneselect */
112072 {yygotominor.yy159 = yymsp[0].minor.yy159;}
112073         break;
112074       case 114: /* select ::= select multiselect_op oneselect */
112075 {
112076   if( yymsp[0].minor.yy159 ){
112077     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
112078     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
112079   }else{
112080     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
112081   }
112082   yygotominor.yy159 = yymsp[0].minor.yy159;
112083 }
112084         break;
112085       case 116: /* multiselect_op ::= UNION ALL */
112086 {yygotominor.yy392 = TK_ALL;}
112087         break;
112088       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
112089 {
112090   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.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
112091 }
112092         break;
112093       case 122: /* sclp ::= selcollist COMMA */
112094       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
112095 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
112096         break;
112097       case 123: /* sclp ::= */
112098       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
112099       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
112100       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
112101       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
112102 {yygotominor.yy442 = 0;}
112103         break;
112104       case 124: /* selcollist ::= sclp expr as */
112105 {
112106    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
112107    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
112108    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
112109 }
112110         break;
112111       case 125: /* selcollist ::= sclp STAR */
112112 {
112113   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
112114   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
112115 }
112116         break;
112117       case 126: /* selcollist ::= sclp nm DOT STAR */
112118 {
112119   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
112120   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112121   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
112122   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
112123 }
112124         break;
112125       case 129: /* as ::= */
112126 {yygotominor.yy0.n = 0;}
112127         break;
112128       case 130: /* from ::= */
112129 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
112130         break;
112131       case 131: /* from ::= FROM seltablist */
112132 {
112133   yygotominor.yy347 = yymsp[0].minor.yy347;
112134   sqlite3SrcListShiftJoinType(yygotominor.yy347);
112135 }
112136         break;
112137       case 132: /* stl_prefix ::= seltablist joinop */
112138 {
112139    yygotominor.yy347 = yymsp[-1].minor.yy347;
112140    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
112141 }
112142         break;
112143       case 133: /* stl_prefix ::= */
112144 {yygotominor.yy347 = 0;}
112145         break;
112146       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
112147 {
112148   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);
112149   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
112150 }
112151         break;
112152       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
112153 {
112154     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);
112155   }
112156         break;
112157       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
112158 {
112159     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
112160       yygotominor.yy347 = yymsp[-4].minor.yy347;
112161     }else{
112162       Select *pSubquery;
112163       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
112164       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
112165       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
112166     }
112167   }
112168         break;
112169       case 137: /* dbnm ::= */
112170       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
112171 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
112172         break;
112173       case 139: /* fullname ::= nm dbnm */
112174 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
112175         break;
112176       case 140: /* joinop ::= COMMA|JOIN */
112177 { yygotominor.yy392 = JT_INNER; }
112178         break;
112179       case 141: /* joinop ::= JOIN_KW JOIN */
112180 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
112181         break;
112182       case 142: /* joinop ::= JOIN_KW nm JOIN */
112183 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
112184         break;
112185       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
112186 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
112187         break;
112188       case 144: /* on_opt ::= ON expr */
112189       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
112190       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
112191       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
112192       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
112193 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
112194         break;
112195       case 145: /* on_opt ::= */
112196       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
112197       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
112198       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
112199       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
112200 {yygotominor.yy122 = 0;}
112201         break;
112202       case 148: /* indexed_opt ::= NOT INDEXED */
112203 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
112204         break;
112205       case 149: /* using_opt ::= USING LP inscollist RP */
112206       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
112207 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
112208         break;
112209       case 150: /* using_opt ::= */
112210       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
112211 {yygotominor.yy180 = 0;}
112212         break;
112213       case 152: /* orderby_opt ::= ORDER BY sortlist */
112214       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
112215       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
112216 {yygotominor.yy442 = yymsp[0].minor.yy442;}
112217         break;
112218       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
112219 {
112220   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
112221   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
112222 }
112223         break;
112224       case 154: /* sortlist ::= expr sortorder */
112225 {
112226   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
112227   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
112228 }
112229         break;
112230       case 155: /* sortorder ::= ASC */
112231       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
112232 {yygotominor.yy392 = SQLITE_SO_ASC;}
112233         break;
112234       case 156: /* sortorder ::= DESC */
112235 {yygotominor.yy392 = SQLITE_SO_DESC;}
112236         break;
112237       case 162: /* limit_opt ::= */
112238 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
112239         break;
112240       case 163: /* limit_opt ::= LIMIT expr */
112241 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
112242         break;
112243       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
112244 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
112245         break;
112246       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
112247 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
112248         break;
112249       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
112250 {
112251   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
112252   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
112253 }
112254         break;
112255       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
112256 {
112257   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
112258   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
112259   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
112260 }
112261         break;
112262       case 170: /* setlist ::= setlist COMMA nm EQ expr */
112263 {
112264   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
112265   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
112266 }
112267         break;
112268       case 171: /* setlist ::= nm EQ expr */
112269 {
112270   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
112271   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
112272 }
112273         break;
112274       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
112275 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
112276         break;
112277       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
112278 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
112279         break;
112280       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
112281 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
112282         break;
112283       case 175: /* insert_cmd ::= INSERT orconf */
112284 {yygotominor.yy258 = yymsp[0].minor.yy258;}
112285         break;
112286       case 176: /* insert_cmd ::= REPLACE */
112287 {yygotominor.yy258 = OE_Replace;}
112288         break;
112289       case 177: /* valuelist ::= VALUES LP nexprlist RP */
112290 {
112291   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
112292   yygotominor.yy487.pSelect = 0;
112293 }
112294         break;
112295       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
112296 {
112297   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
112298   if( yymsp[-4].minor.yy487.pList ){
112299     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
112300     yymsp[-4].minor.yy487.pList = 0;
112301   }
112302   yygotominor.yy487.pList = 0;
112303   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
112304     sqlite3SelectDelete(pParse->db, pRight);
112305     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
112306     yygotominor.yy487.pSelect = 0;
112307   }else{
112308     pRight->op = TK_ALL;
112309     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
112310     pRight->selFlags |= SF_Values;
112311     pRight->pPrior->selFlags |= SF_Values;
112312     yygotominor.yy487.pSelect = pRight;
112313   }
112314 }
112315         break;
112316       case 181: /* inscollist ::= inscollist COMMA nm */
112317 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
112318         break;
112319       case 182: /* inscollist ::= nm */
112320 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
112321         break;
112322       case 183: /* expr ::= term */
112323 {yygotominor.yy342 = yymsp[0].minor.yy342;}
112324         break;
112325       case 184: /* expr ::= LP expr RP */
112326 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
112327         break;
112328       case 185: /* term ::= NULL */
112329       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
112330       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
112331 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
112332         break;
112333       case 186: /* expr ::= id */
112334       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
112335 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
112336         break;
112337       case 188: /* expr ::= nm DOT nm */
112338 {
112339   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112340   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
112341   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
112342   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
112343 }
112344         break;
112345       case 189: /* expr ::= nm DOT nm DOT nm */
112346 {
112347   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
112348   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112349   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
112350   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
112351   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
112352   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
112353 }
112354         break;
112355       case 192: /* expr ::= REGISTER */
112356 {
112357   /* When doing a nested parse, one can include terms in an expression
112358   ** that look like this:   #1 #2 ...  These terms refer to registers
112359   ** in the virtual machine.  #N is the N-th register. */
112360   if( pParse->nested==0 ){
112361     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
112362     yygotominor.yy342.pExpr = 0;
112363   }else{
112364     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
112365     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
112366   }
112367   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112368 }
112369         break;
112370       case 193: /* expr ::= VARIABLE */
112371 {
112372   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
112373   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
112374   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112375 }
112376         break;
112377       case 194: /* expr ::= expr COLLATE ids */
112378 {
112379   yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
112380   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
112381   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112382 }
112383         break;
112384       case 195: /* expr ::= CAST LP expr AS typetoken RP */
112385 {
112386   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
112387   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
112388 }
112389         break;
112390       case 196: /* expr ::= ID LP distinct exprlist RP */
112391 {
112392   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
112393     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
112394   }
112395   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
112396   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
112397   if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
112398     yygotominor.yy342.pExpr->flags |= EP_Distinct;
112399   }
112400 }
112401         break;
112402       case 197: /* expr ::= ID LP STAR RP */
112403 {
112404   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
112405   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
112406 }
112407         break;
112408       case 198: /* term ::= CTIME_KW */
112409 {
112410   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
112411   ** treated as functions that return constants */
112412   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
112413   if( yygotominor.yy342.pExpr ){
112414     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
112415   }
112416   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112417 }
112418         break;
112419       case 199: /* expr ::= expr AND expr */
112420       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
112421       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
112422       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
112423       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
112424       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
112425       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
112426       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
112427 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
112428         break;
112429       case 207: /* likeop ::= LIKE_KW */
112430       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
112431 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
112432         break;
112433       case 208: /* likeop ::= NOT LIKE_KW */
112434       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
112435 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
112436         break;
112437       case 211: /* expr ::= expr likeop expr */
112438 {
112439   ExprList *pList;
112440   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
112441   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
112442   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
112443   if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112444   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
112445   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112446   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
112447 }
112448         break;
112449       case 212: /* expr ::= expr likeop expr ESCAPE expr */
112450 {
112451   ExprList *pList;
112452   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
112453   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
112454   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
112455   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
112456   if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112457   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112458   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112459   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
112460 }
112461         break;
112462       case 213: /* expr ::= expr ISNULL|NOTNULL */
112463 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
112464         break;
112465       case 214: /* expr ::= expr NOT NULL */
112466 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
112467         break;
112468       case 215: /* expr ::= expr IS expr */
112469 {
112470   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
112471   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
112472 }
112473         break;
112474       case 216: /* expr ::= expr IS NOT expr */
112475 {
112476   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
112477   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
112478 }
112479         break;
112480       case 217: /* expr ::= NOT expr */
112481       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
112482 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112483         break;
112484       case 219: /* expr ::= MINUS expr */
112485 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112486         break;
112487       case 220: /* expr ::= PLUS expr */
112488 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112489         break;
112490       case 223: /* expr ::= expr between_op expr AND expr */
112491 {
112492   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
112493   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
112494   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
112495   if( yygotominor.yy342.pExpr ){
112496     yygotominor.yy342.pExpr->x.pList = pList;
112497   }else{
112498     sqlite3ExprListDelete(pParse->db, pList);
112499   }
112500   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112501   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112502   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112503 }
112504         break;
112505       case 226: /* expr ::= expr in_op LP exprlist RP */
112506 {
112507     if( yymsp[-1].minor.yy442==0 ){
112508       /* Expressions of the form
112509       **
112510       **      expr1 IN ()
112511       **      expr1 NOT IN ()
112512       **
112513       ** simplify to constants 0 (false) and 1 (true), respectively,
112514       ** regardless of the value of expr1.
112515       */
112516       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
112517       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
112518     }else{
112519       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
112520       if( yygotominor.yy342.pExpr ){
112521         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
112522         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112523       }else{
112524         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
112525       }
112526       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112527     }
112528     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112529     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112530   }
112531         break;
112532       case 227: /* expr ::= LP select RP */
112533 {
112534     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
112535     if( yygotominor.yy342.pExpr ){
112536       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
112537       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
112538       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112539     }else{
112540       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
112541     }
112542     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
112543     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112544   }
112545         break;
112546       case 228: /* expr ::= expr in_op LP select RP */
112547 {
112548     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
112549     if( yygotominor.yy342.pExpr ){
112550       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
112551       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
112552       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112553     }else{
112554       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
112555     }
112556     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112557     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112558     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112559   }
112560         break;
112561       case 229: /* expr ::= expr in_op nm dbnm */
112562 {
112563     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
112564     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
112565     if( yygotominor.yy342.pExpr ){
112566       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
112567       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
112568       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112569     }else{
112570       sqlite3SrcListDelete(pParse->db, pSrc);
112571     }
112572     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112573     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
112574     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];
112575   }
112576         break;
112577       case 230: /* expr ::= EXISTS LP select RP */
112578 {
112579     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
112580     if( p ){
112581       p->x.pSelect = yymsp[-1].minor.yy159;
112582       ExprSetProperty(p, EP_xIsSelect);
112583       sqlite3ExprSetHeight(pParse, p);
112584     }else{
112585       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
112586     }
112587     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
112588     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112589   }
112590         break;
112591       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
112592 {
112593   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
112594   if( yygotominor.yy342.pExpr ){
112595     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
112596     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112597   }else{
112598     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
112599   }
112600   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
112601   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112602 }
112603         break;
112604       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
112605 {
112606   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
112607   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
112608 }
112609         break;
112610       case 233: /* case_exprlist ::= WHEN expr THEN expr */
112611 {
112612   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
112613   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
112614 }
112615         break;
112616       case 240: /* nexprlist ::= nexprlist COMMA expr */
112617 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
112618         break;
112619       case 241: /* nexprlist ::= expr */
112620 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
112621         break;
112622       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
112623 {
112624   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
112625                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
112626                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
112627 }
112628         break;
112629       case 243: /* uniqueflag ::= UNIQUE */
112630       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
112631 {yygotominor.yy392 = OE_Abort;}
112632         break;
112633       case 244: /* uniqueflag ::= */
112634 {yygotominor.yy392 = OE_None;}
112635         break;
112636       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
112637 {
112638   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
112639   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
112640   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
112641   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
112642   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
112643 }
112644         break;
112645       case 248: /* idxlist ::= nm collate sortorder */
112646 {
112647   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
112648   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
112649   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
112650   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
112651   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
112652 }
112653         break;
112654       case 249: /* collate ::= */
112655 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
112656         break;
112657       case 251: /* cmd ::= DROP INDEX ifexists fullname */
112658 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
112659         break;
112660       case 252: /* cmd ::= VACUUM */
112661       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
112662 {sqlite3Vacuum(pParse);}
112663         break;
112664       case 254: /* cmd ::= PRAGMA nm dbnm */
112665 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
112666         break;
112667       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
112668 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
112669         break;
112670       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
112671 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
112672         break;
112673       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
112674 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
112675         break;
112676       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
112677 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
112678         break;
112679       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
112680 {
112681   Token all;
112682   all.z = yymsp[-3].minor.yy0.z;
112683   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
112684   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
112685 }
112686         break;
112687       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
112688 {
112689   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);
112690   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
112691 }
112692         break;
112693       case 270: /* trigger_time ::= BEFORE */
112694       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
112695 { yygotominor.yy392 = TK_BEFORE; }
112696         break;
112697       case 271: /* trigger_time ::= AFTER */
112698 { yygotominor.yy392 = TK_AFTER;  }
112699         break;
112700       case 272: /* trigger_time ::= INSTEAD OF */
112701 { yygotominor.yy392 = TK_INSTEAD;}
112702         break;
112703       case 274: /* trigger_event ::= DELETE|INSERT */
112704       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
112705 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
112706         break;
112707       case 276: /* trigger_event ::= UPDATE OF inscollist */
112708 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
112709         break;
112710       case 279: /* when_clause ::= */
112711       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
112712 { yygotominor.yy122 = 0; }
112713         break;
112714       case 280: /* when_clause ::= WHEN expr */
112715       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
112716 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
112717         break;
112718       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
112719 {
112720   assert( yymsp[-2].minor.yy327!=0 );
112721   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
112722   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
112723   yygotominor.yy327 = yymsp[-2].minor.yy327;
112724 }
112725         break;
112726       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
112727 {
112728   assert( yymsp[-1].minor.yy327!=0 );
112729   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
112730   yygotominor.yy327 = yymsp[-1].minor.yy327;
112731 }
112732         break;
112733       case 284: /* trnm ::= nm DOT nm */
112734 {
112735   yygotominor.yy0 = yymsp[0].minor.yy0;
112736   sqlite3ErrorMsg(pParse,
112737         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
112738         "statements within triggers");
112739 }
112740         break;
112741       case 286: /* tridxby ::= INDEXED BY nm */
112742 {
112743   sqlite3ErrorMsg(pParse,
112744         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
112745         "within triggers");
112746 }
112747         break;
112748       case 287: /* tridxby ::= NOT INDEXED */
112749 {
112750   sqlite3ErrorMsg(pParse,
112751         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
112752         "within triggers");
112753 }
112754         break;
112755       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
112756 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
112757         break;
112758       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
112759 {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);}
112760         break;
112761       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
112762 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
112763         break;
112764       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
112765 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
112766         break;
112767       case 292: /* trigger_cmd ::= select */
112768 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
112769         break;
112770       case 293: /* expr ::= RAISE LP IGNORE RP */
112771 {
112772   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
112773   if( yygotominor.yy342.pExpr ){
112774     yygotominor.yy342.pExpr->affinity = OE_Ignore;
112775   }
112776   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
112777   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112778 }
112779         break;
112780       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
112781 {
112782   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
112783   if( yygotominor.yy342.pExpr ) {
112784     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
112785   }
112786   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
112787   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112788 }
112789         break;
112790       case 295: /* raisetype ::= ROLLBACK */
112791 {yygotominor.yy392 = OE_Rollback;}
112792         break;
112793       case 297: /* raisetype ::= FAIL */
112794 {yygotominor.yy392 = OE_Fail;}
112795         break;
112796       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
112797 {
112798   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
112799 }
112800         break;
112801       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
112802 {
112803   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
112804 }
112805         break;
112806       case 300: /* cmd ::= DETACH database_kw_opt expr */
112807 {
112808   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
112809 }
112810         break;
112811       case 305: /* cmd ::= REINDEX */
112812 {sqlite3Reindex(pParse, 0, 0);}
112813         break;
112814       case 306: /* cmd ::= REINDEX nm dbnm */
112815 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
112816         break;
112817       case 307: /* cmd ::= ANALYZE */
112818 {sqlite3Analyze(pParse, 0, 0);}
112819         break;
112820       case 308: /* cmd ::= ANALYZE nm dbnm */
112821 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
112822         break;
112823       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
112824 {
112825   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
112826 }
112827         break;
112828       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
112829 {
112830   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
112831 }
112832         break;
112833       case 311: /* add_column_fullname ::= fullname */
112834 {
112835   pParse->db->lookaside.bEnabled = 0;
112836   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
112837 }
112838         break;
112839       case 314: /* cmd ::= create_vtab */
112840 {sqlite3VtabFinishParse(pParse,0);}
112841         break;
112842       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
112843 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
112844         break;
112845       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
112846 {
112847     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
112848 }
112849         break;
112850       case 319: /* vtabarg ::= */
112851 {sqlite3VtabArgInit(pParse);}
112852         break;
112853       case 321: /* vtabargtoken ::= ANY */
112854       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
112855       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
112856 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
112857         break;
112858       default:
112859       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
112860       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
112861       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
112862       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
112863       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
112864       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
112865       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
112866       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
112867       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
112868       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
112869       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
112870       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
112871       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
112872       /* (44) type ::= */ yytestcase(yyruleno==44);
112873       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
112874       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
112875       /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
112876       /* (54) carglist ::= */ yytestcase(yyruleno==54);
112877       /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
112878       /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
112879       /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
112880       /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
112881       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
112882       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
112883       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
112884       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
112885       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
112886       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
112887       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
112888       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
112889       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
112890       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
112891       /* (324) anylist ::= */ yytestcase(yyruleno==324);
112892       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
112893       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
112894         break;
112895   };
112896   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
112897   yygoto = yyRuleInfo[yyruleno].lhs;
112898   yysize = yyRuleInfo[yyruleno].nrhs;
112899   yypParser->yyidx -= yysize;
112900   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
112901   if( yyact < YYNSTATE ){
112902 #ifdef NDEBUG
112903     /* If we are not debugging and the reduce action popped at least
112904     ** one element off the stack, then we can push the new element back
112905     ** onto the stack here, and skip the stack overflow test in yy_shift().
112906     ** That gives a significant speed improvement. */
112907     if( yysize ){
112908       yypParser->yyidx++;
112909       yymsp -= yysize-1;
112910       yymsp->stateno = (YYACTIONTYPE)yyact;
112911       yymsp->major = (YYCODETYPE)yygoto;
112912       yymsp->minor = yygotominor;
112913     }else
112914 #endif
112915     {
112916       yy_shift(yypParser,yyact,yygoto,&yygotominor);
112917     }
112918   }else{
112919     assert( yyact == YYNSTATE + YYNRULE + 1 );
112920     yy_accept(yypParser);
112921   }
112922 }
112923
112924 /*
112925 ** The following code executes when the parse fails
112926 */
112927 #ifndef YYNOERRORRECOVERY
112928 static void yy_parse_failed(
112929   yyParser *yypParser           /* The parser */
112930 ){
112931   sqlite3ParserARG_FETCH;
112932 #ifndef NDEBUG
112933   if( yyTraceFILE ){
112934     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
112935   }
112936 #endif
112937   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
112938   /* Here code is inserted which will be executed whenever the
112939   ** parser fails */
112940   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
112941 }
112942 #endif /* YYNOERRORRECOVERY */
112943
112944 /*
112945 ** The following code executes when a syntax error first occurs.
112946 */
112947 static void yy_syntax_error(
112948   yyParser *yypParser,           /* The parser */
112949   int yymajor,                   /* The major type of the error token */
112950   YYMINORTYPE yyminor            /* The minor type of the error token */
112951 ){
112952   sqlite3ParserARG_FETCH;
112953 #define TOKEN (yyminor.yy0)
112954
112955   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
112956   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
112957   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
112958   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
112959 }
112960
112961 /*
112962 ** The following is executed when the parser accepts
112963 */
112964 static void yy_accept(
112965   yyParser *yypParser           /* The parser */
112966 ){
112967   sqlite3ParserARG_FETCH;
112968 #ifndef NDEBUG
112969   if( yyTraceFILE ){
112970     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
112971   }
112972 #endif
112973   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
112974   /* Here code is inserted which will be executed whenever the
112975   ** parser accepts */
112976   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
112977 }
112978
112979 /* The main parser program.
112980 ** The first argument is a pointer to a structure obtained from
112981 ** "sqlite3ParserAlloc" which describes the current state of the parser.
112982 ** The second argument is the major token number.  The third is
112983 ** the minor token.  The fourth optional argument is whatever the
112984 ** user wants (and specified in the grammar) and is available for
112985 ** use by the action routines.
112986 **
112987 ** Inputs:
112988 ** <ul>
112989 ** <li> A pointer to the parser (an opaque structure.)
112990 ** <li> The major token number.
112991 ** <li> The minor token number.
112992 ** <li> An option argument of a grammar-specified type.
112993 ** </ul>
112994 **
112995 ** Outputs:
112996 ** None.
112997 */
112998 SQLITE_PRIVATE void sqlite3Parser(
112999   void *yyp,                   /* The parser */
113000   int yymajor,                 /* The major token code number */
113001   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
113002   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
113003 ){
113004   YYMINORTYPE yyminorunion;
113005   int yyact;            /* The parser action. */
113006 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
113007   int yyendofinput;     /* True if we are at the end of input */
113008 #endif
113009 #ifdef YYERRORSYMBOL
113010   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
113011 #endif
113012   yyParser *yypParser;  /* The parser */
113013
113014   /* (re)initialize the parser, if necessary */
113015   yypParser = (yyParser*)yyp;
113016   if( yypParser->yyidx<0 ){
113017 #if YYSTACKDEPTH<=0
113018     if( yypParser->yystksz <=0 ){
113019       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
113020       yyminorunion = yyzerominor;
113021       yyStackOverflow(yypParser, &yyminorunion);
113022       return;
113023     }
113024 #endif
113025     yypParser->yyidx = 0;
113026     yypParser->yyerrcnt = -1;
113027     yypParser->yystack[0].stateno = 0;
113028     yypParser->yystack[0].major = 0;
113029   }
113030   yyminorunion.yy0 = yyminor;
113031 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
113032   yyendofinput = (yymajor==0);
113033 #endif
113034   sqlite3ParserARG_STORE;
113035
113036 #ifndef NDEBUG
113037   if( yyTraceFILE ){
113038     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
113039   }
113040 #endif
113041
113042   do{
113043     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
113044     if( yyact<YYNSTATE ){
113045       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
113046       yypParser->yyerrcnt--;
113047       yymajor = YYNOCODE;
113048     }else if( yyact < YYNSTATE + YYNRULE ){
113049       yy_reduce(yypParser,yyact-YYNSTATE);
113050     }else{
113051       assert( yyact == YY_ERROR_ACTION );
113052 #ifdef YYERRORSYMBOL
113053       int yymx;
113054 #endif
113055 #ifndef NDEBUG
113056       if( yyTraceFILE ){
113057         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
113058       }
113059 #endif
113060 #ifdef YYERRORSYMBOL
113061       /* A syntax error has occurred.
113062       ** The response to an error depends upon whether or not the
113063       ** grammar defines an error token "ERROR".
113064       **
113065       ** This is what we do if the grammar does define ERROR:
113066       **
113067       **  * Call the %syntax_error function.
113068       **
113069       **  * Begin popping the stack until we enter a state where
113070       **    it is legal to shift the error symbol, then shift
113071       **    the error symbol.
113072       **
113073       **  * Set the error count to three.
113074       **
113075       **  * Begin accepting and shifting new tokens.  No new error
113076       **    processing will occur until three tokens have been
113077       **    shifted successfully.
113078       **
113079       */
113080       if( yypParser->yyerrcnt<0 ){
113081         yy_syntax_error(yypParser,yymajor,yyminorunion);
113082       }
113083       yymx = yypParser->yystack[yypParser->yyidx].major;
113084       if( yymx==YYERRORSYMBOL || yyerrorhit ){
113085 #ifndef NDEBUG
113086         if( yyTraceFILE ){
113087           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
113088              yyTracePrompt,yyTokenName[yymajor]);
113089         }
113090 #endif
113091         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
113092         yymajor = YYNOCODE;
113093       }else{
113094          while(
113095           yypParser->yyidx >= 0 &&
113096           yymx != YYERRORSYMBOL &&
113097           (yyact = yy_find_reduce_action(
113098                         yypParser->yystack[yypParser->yyidx].stateno,
113099                         YYERRORSYMBOL)) >= YYNSTATE
113100         ){
113101           yy_pop_parser_stack(yypParser);
113102         }
113103         if( yypParser->yyidx < 0 || yymajor==0 ){
113104           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113105           yy_parse_failed(yypParser);
113106           yymajor = YYNOCODE;
113107         }else if( yymx!=YYERRORSYMBOL ){
113108           YYMINORTYPE u2;
113109           u2.YYERRSYMDT = 0;
113110           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
113111         }
113112       }
113113       yypParser->yyerrcnt = 3;
113114       yyerrorhit = 1;
113115 #elif defined(YYNOERRORRECOVERY)
113116       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
113117       ** do any kind of error recovery.  Instead, simply invoke the syntax
113118       ** error routine and continue going as if nothing had happened.
113119       **
113120       ** Applications can set this macro (for example inside %include) if
113121       ** they intend to abandon the parse upon the first syntax error seen.
113122       */
113123       yy_syntax_error(yypParser,yymajor,yyminorunion);
113124       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113125       yymajor = YYNOCODE;
113126
113127 #else  /* YYERRORSYMBOL is not defined */
113128       /* This is what we do if the grammar does not define ERROR:
113129       **
113130       **  * Report an error message, and throw away the input token.
113131       **
113132       **  * If the input token is $, then fail the parse.
113133       **
113134       ** As before, subsequent error messages are suppressed until
113135       ** three input tokens have been successfully shifted.
113136       */
113137       if( yypParser->yyerrcnt<=0 ){
113138         yy_syntax_error(yypParser,yymajor,yyminorunion);
113139       }
113140       yypParser->yyerrcnt = 3;
113141       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113142       if( yyendofinput ){
113143         yy_parse_failed(yypParser);
113144       }
113145       yymajor = YYNOCODE;
113146 #endif
113147     }
113148   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
113149   return;
113150 }
113151
113152 /************** End of parse.c ***********************************************/
113153 /************** Begin file tokenize.c ****************************************/
113154 /*
113155 ** 2001 September 15
113156 **
113157 ** The author disclaims copyright to this source code.  In place of
113158 ** a legal notice, here is a blessing:
113159 **
113160 **    May you do good and not evil.
113161 **    May you find forgiveness for yourself and forgive others.
113162 **    May you share freely, never taking more than you give.
113163 **
113164 *************************************************************************
113165 ** An tokenizer for SQL
113166 **
113167 ** This file contains C code that splits an SQL input string up into
113168 ** individual tokens and sends those tokens one-by-one over to the
113169 ** parser for analysis.
113170 */
113171 /* #include <stdlib.h> */
113172
113173 /*
113174 ** The charMap() macro maps alphabetic characters into their
113175 ** lower-case ASCII equivalent.  On ASCII machines, this is just
113176 ** an upper-to-lower case map.  On EBCDIC machines we also need
113177 ** to adjust the encoding.  Only alphabetic characters and underscores
113178 ** need to be translated.
113179 */
113180 #ifdef SQLITE_ASCII
113181 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
113182 #endif
113183 #ifdef SQLITE_EBCDIC
113184 # define charMap(X) ebcdicToAscii[(unsigned char)X]
113185 const unsigned char ebcdicToAscii[] = {
113186 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
113187    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
113188    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
113189    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
113190    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
113191    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
113192    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
113193    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
113194    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
113195    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
113196    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
113197    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
113198    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
113199    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
113200    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
113201    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
113202    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
113203 };
113204 #endif
113205
113206 /*
113207 ** The sqlite3KeywordCode function looks up an identifier to determine if
113208 ** it is a keyword.  If it is a keyword, the token code of that keyword is
113209 ** returned.  If the input is not a keyword, TK_ID is returned.
113210 **
113211 ** The implementation of this routine was generated by a program,
113212 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
113213 ** The output of the mkkeywordhash.c program is written into a file
113214 ** named keywordhash.h and then included into this source file by
113215 ** the #include below.
113216 */
113217 /************** Include keywordhash.h in the middle of tokenize.c ************/
113218 /************** Begin file keywordhash.h *************************************/
113219 /***** This file contains automatically generated code ******
113220 **
113221 ** The code in this file has been automatically generated by
113222 **
113223 **   sqlite/tool/mkkeywordhash.c
113224 **
113225 ** The code in this file implements a function that determines whether
113226 ** or not a given identifier is really an SQL keyword.  The same thing
113227 ** might be implemented more directly using a hand-written hash table.
113228 ** But by using this automatically generated code, the size of the code
113229 ** is substantially reduced.  This is important for embedded applications
113230 ** on platforms with limited memory.
113231 */
113232 /* Hash score: 175 */
113233 static int keywordCode(const char *z, int n){
113234   /* zText[] encodes 811 bytes of keywords in 541 bytes */
113235   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
113236   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
113237   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
113238   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
113239   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
113240   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
113241   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
113242   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
113243   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
113244   /*   INITIALLY                                                          */
113245   static const char zText[540] = {
113246     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
113247     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
113248     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
113249     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
113250     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
113251     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
113252     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
113253     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
113254     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
113255     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
113256     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
113257     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
113258     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
113259     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
113260     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
113261     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
113262     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
113263     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
113264     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
113265     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
113266     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
113267     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
113268     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
113269     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
113270     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
113271     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
113272     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
113273     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
113274     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
113275     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
113276   };
113277   static const unsigned char aHash[127] = {
113278       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
113279       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
113280      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
113281        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
113282        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
113283       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
113284       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
113285       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
113286       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
113287       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
113288   };
113289   static const unsigned char aNext[121] = {
113290        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
113291        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
113292        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
113293        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
113294        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
113295       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
113296       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
113297        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
113298      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
113299       35,  64,   0,   0,
113300   };
113301   static const unsigned char aLen[121] = {
113302        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
113303        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
113304       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
113305        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
113306        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
113307        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
113308        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
113309        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
113310        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
113311        6,   4,   9,   3,
113312   };
113313   static const unsigned short int aOffset[121] = {
113314        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
113315       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
113316       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
113317      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
113318      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
113319      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
113320      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
113321      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
113322      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
113323      521, 527, 531, 536,
113324   };
113325   static const unsigned char aCode[121] = {
113326     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
113327     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
113328     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
113329     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
113330     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
113331     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
113332     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
113333     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
113334     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
113335     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
113336     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
113337     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
113338     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
113339     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
113340     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
113341     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
113342     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
113343     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
113344     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
113345     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
113346     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
113347     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
113348     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
113349     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
113350     TK_ALL,
113351   };
113352   int h, i;
113353   if( n<2 ) return TK_ID;
113354   h = ((charMap(z[0])*4) ^
113355       (charMap(z[n-1])*3) ^
113356       n) % 127;
113357   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
113358     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
113359       testcase( i==0 ); /* REINDEX */
113360       testcase( i==1 ); /* INDEXED */
113361       testcase( i==2 ); /* INDEX */
113362       testcase( i==3 ); /* DESC */
113363       testcase( i==4 ); /* ESCAPE */
113364       testcase( i==5 ); /* EACH */
113365       testcase( i==6 ); /* CHECK */
113366       testcase( i==7 ); /* KEY */
113367       testcase( i==8 ); /* BEFORE */
113368       testcase( i==9 ); /* FOREIGN */
113369       testcase( i==10 ); /* FOR */
113370       testcase( i==11 ); /* IGNORE */
113371       testcase( i==12 ); /* REGEXP */
113372       testcase( i==13 ); /* EXPLAIN */
113373       testcase( i==14 ); /* INSTEAD */
113374       testcase( i==15 ); /* ADD */
113375       testcase( i==16 ); /* DATABASE */
113376       testcase( i==17 ); /* AS */
113377       testcase( i==18 ); /* SELECT */
113378       testcase( i==19 ); /* TABLE */
113379       testcase( i==20 ); /* LEFT */
113380       testcase( i==21 ); /* THEN */
113381       testcase( i==22 ); /* END */
113382       testcase( i==23 ); /* DEFERRABLE */
113383       testcase( i==24 ); /* ELSE */
113384       testcase( i==25 ); /* EXCEPT */
113385       testcase( i==26 ); /* TRANSACTION */
113386       testcase( i==27 ); /* ACTION */
113387       testcase( i==28 ); /* ON */
113388       testcase( i==29 ); /* NATURAL */
113389       testcase( i==30 ); /* ALTER */
113390       testcase( i==31 ); /* RAISE */
113391       testcase( i==32 ); /* EXCLUSIVE */
113392       testcase( i==33 ); /* EXISTS */
113393       testcase( i==34 ); /* SAVEPOINT */
113394       testcase( i==35 ); /* INTERSECT */
113395       testcase( i==36 ); /* TRIGGER */
113396       testcase( i==37 ); /* REFERENCES */
113397       testcase( i==38 ); /* CONSTRAINT */
113398       testcase( i==39 ); /* INTO */
113399       testcase( i==40 ); /* OFFSET */
113400       testcase( i==41 ); /* OF */
113401       testcase( i==42 ); /* SET */
113402       testcase( i==43 ); /* TEMPORARY */
113403       testcase( i==44 ); /* TEMP */
113404       testcase( i==45 ); /* OR */
113405       testcase( i==46 ); /* UNIQUE */
113406       testcase( i==47 ); /* QUERY */
113407       testcase( i==48 ); /* ATTACH */
113408       testcase( i==49 ); /* HAVING */
113409       testcase( i==50 ); /* GROUP */
113410       testcase( i==51 ); /* UPDATE */
113411       testcase( i==52 ); /* BEGIN */
113412       testcase( i==53 ); /* INNER */
113413       testcase( i==54 ); /* RELEASE */
113414       testcase( i==55 ); /* BETWEEN */
113415       testcase( i==56 ); /* NOTNULL */
113416       testcase( i==57 ); /* NOT */
113417       testcase( i==58 ); /* NO */
113418       testcase( i==59 ); /* NULL */
113419       testcase( i==60 ); /* LIKE */
113420       testcase( i==61 ); /* CASCADE */
113421       testcase( i==62 ); /* ASC */
113422       testcase( i==63 ); /* DELETE */
113423       testcase( i==64 ); /* CASE */
113424       testcase( i==65 ); /* COLLATE */
113425       testcase( i==66 ); /* CREATE */
113426       testcase( i==67 ); /* CURRENT_DATE */
113427       testcase( i==68 ); /* DETACH */
113428       testcase( i==69 ); /* IMMEDIATE */
113429       testcase( i==70 ); /* JOIN */
113430       testcase( i==71 ); /* INSERT */
113431       testcase( i==72 ); /* MATCH */
113432       testcase( i==73 ); /* PLAN */
113433       testcase( i==74 ); /* ANALYZE */
113434       testcase( i==75 ); /* PRAGMA */
113435       testcase( i==76 ); /* ABORT */
113436       testcase( i==77 ); /* VALUES */
113437       testcase( i==78 ); /* VIRTUAL */
113438       testcase( i==79 ); /* LIMIT */
113439       testcase( i==80 ); /* WHEN */
113440       testcase( i==81 ); /* WHERE */
113441       testcase( i==82 ); /* RENAME */
113442       testcase( i==83 ); /* AFTER */
113443       testcase( i==84 ); /* REPLACE */
113444       testcase( i==85 ); /* AND */
113445       testcase( i==86 ); /* DEFAULT */
113446       testcase( i==87 ); /* AUTOINCREMENT */
113447       testcase( i==88 ); /* TO */
113448       testcase( i==89 ); /* IN */
113449       testcase( i==90 ); /* CAST */
113450       testcase( i==91 ); /* COLUMN */
113451       testcase( i==92 ); /* COMMIT */
113452       testcase( i==93 ); /* CONFLICT */
113453       testcase( i==94 ); /* CROSS */
113454       testcase( i==95 ); /* CURRENT_TIMESTAMP */
113455       testcase( i==96 ); /* CURRENT_TIME */
113456       testcase( i==97 ); /* PRIMARY */
113457       testcase( i==98 ); /* DEFERRED */
113458       testcase( i==99 ); /* DISTINCT */
113459       testcase( i==100 ); /* IS */
113460       testcase( i==101 ); /* DROP */
113461       testcase( i==102 ); /* FAIL */
113462       testcase( i==103 ); /* FROM */
113463       testcase( i==104 ); /* FULL */
113464       testcase( i==105 ); /* GLOB */
113465       testcase( i==106 ); /* BY */
113466       testcase( i==107 ); /* IF */
113467       testcase( i==108 ); /* ISNULL */
113468       testcase( i==109 ); /* ORDER */
113469       testcase( i==110 ); /* RESTRICT */
113470       testcase( i==111 ); /* OUTER */
113471       testcase( i==112 ); /* RIGHT */
113472       testcase( i==113 ); /* ROLLBACK */
113473       testcase( i==114 ); /* ROW */
113474       testcase( i==115 ); /* UNION */
113475       testcase( i==116 ); /* USING */
113476       testcase( i==117 ); /* VACUUM */
113477       testcase( i==118 ); /* VIEW */
113478       testcase( i==119 ); /* INITIALLY */
113479       testcase( i==120 ); /* ALL */
113480       return aCode[i];
113481     }
113482   }
113483   return TK_ID;
113484 }
113485 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
113486   return keywordCode((char*)z, n);
113487 }
113488 #define SQLITE_N_KEYWORD 121
113489
113490 /************** End of keywordhash.h *****************************************/
113491 /************** Continuing where we left off in tokenize.c *******************/
113492
113493
113494 /*
113495 ** If X is a character that can be used in an identifier then
113496 ** IdChar(X) will be true.  Otherwise it is false.
113497 **
113498 ** For ASCII, any character with the high-order bit set is
113499 ** allowed in an identifier.  For 7-bit characters,
113500 ** sqlite3IsIdChar[X] must be 1.
113501 **
113502 ** For EBCDIC, the rules are more complex but have the same
113503 ** end result.
113504 **
113505 ** Ticket #1066.  the SQL standard does not allow '$' in the
113506 ** middle of identfiers.  But many SQL implementations do.
113507 ** SQLite will allow '$' in identifiers for compatibility.
113508 ** But the feature is undocumented.
113509 */
113510 #ifdef SQLITE_ASCII
113511 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
113512 #endif
113513 #ifdef SQLITE_EBCDIC
113514 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
113515 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
113516     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
113517     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
113518     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
113519     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
113520     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
113521     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
113522     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
113523     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
113524     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
113525     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
113526     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
113527     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
113528 };
113529 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
113530 #endif
113531
113532
113533 /*
113534 ** Return the length of the token that begins at z[0].
113535 ** Store the token type in *tokenType before returning.
113536 */
113537 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
113538   int i, c;
113539   switch( *z ){
113540     case ' ': case '\t': case '\n': case '\f': case '\r': {
113541       testcase( z[0]==' ' );
113542       testcase( z[0]=='\t' );
113543       testcase( z[0]=='\n' );
113544       testcase( z[0]=='\f' );
113545       testcase( z[0]=='\r' );
113546       for(i=1; sqlite3Isspace(z[i]); i++){}
113547       *tokenType = TK_SPACE;
113548       return i;
113549     }
113550     case '-': {
113551       if( z[1]=='-' ){
113552         /* IMP: R-50417-27976 -- syntax diagram for comments */
113553         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
113554         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
113555         return i;
113556       }
113557       *tokenType = TK_MINUS;
113558       return 1;
113559     }
113560     case '(': {
113561       *tokenType = TK_LP;
113562       return 1;
113563     }
113564     case ')': {
113565       *tokenType = TK_RP;
113566       return 1;
113567     }
113568     case ';': {
113569       *tokenType = TK_SEMI;
113570       return 1;
113571     }
113572     case '+': {
113573       *tokenType = TK_PLUS;
113574       return 1;
113575     }
113576     case '*': {
113577       *tokenType = TK_STAR;
113578       return 1;
113579     }
113580     case '/': {
113581       if( z[1]!='*' || z[2]==0 ){
113582         *tokenType = TK_SLASH;
113583         return 1;
113584       }
113585       /* IMP: R-50417-27976 -- syntax diagram for comments */
113586       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
113587       if( c ) i++;
113588       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
113589       return i;
113590     }
113591     case '%': {
113592       *tokenType = TK_REM;
113593       return 1;
113594     }
113595     case '=': {
113596       *tokenType = TK_EQ;
113597       return 1 + (z[1]=='=');
113598     }
113599     case '<': {
113600       if( (c=z[1])=='=' ){
113601         *tokenType = TK_LE;
113602         return 2;
113603       }else if( c=='>' ){
113604         *tokenType = TK_NE;
113605         return 2;
113606       }else if( c=='<' ){
113607         *tokenType = TK_LSHIFT;
113608         return 2;
113609       }else{
113610         *tokenType = TK_LT;
113611         return 1;
113612       }
113613     }
113614     case '>': {
113615       if( (c=z[1])=='=' ){
113616         *tokenType = TK_GE;
113617         return 2;
113618       }else if( c=='>' ){
113619         *tokenType = TK_RSHIFT;
113620         return 2;
113621       }else{
113622         *tokenType = TK_GT;
113623         return 1;
113624       }
113625     }
113626     case '!': {
113627       if( z[1]!='=' ){
113628         *tokenType = TK_ILLEGAL;
113629         return 2;
113630       }else{
113631         *tokenType = TK_NE;
113632         return 2;
113633       }
113634     }
113635     case '|': {
113636       if( z[1]!='|' ){
113637         *tokenType = TK_BITOR;
113638         return 1;
113639       }else{
113640         *tokenType = TK_CONCAT;
113641         return 2;
113642       }
113643     }
113644     case ',': {
113645       *tokenType = TK_COMMA;
113646       return 1;
113647     }
113648     case '&': {
113649       *tokenType = TK_BITAND;
113650       return 1;
113651     }
113652     case '~': {
113653       *tokenType = TK_BITNOT;
113654       return 1;
113655     }
113656     case '`':
113657     case '\'':
113658     case '"': {
113659       int delim = z[0];
113660       testcase( delim=='`' );
113661       testcase( delim=='\'' );
113662       testcase( delim=='"' );
113663       for(i=1; (c=z[i])!=0; i++){
113664         if( c==delim ){
113665           if( z[i+1]==delim ){
113666             i++;
113667           }else{
113668             break;
113669           }
113670         }
113671       }
113672       if( c=='\'' ){
113673         *tokenType = TK_STRING;
113674         return i+1;
113675       }else if( c!=0 ){
113676         *tokenType = TK_ID;
113677         return i+1;
113678       }else{
113679         *tokenType = TK_ILLEGAL;
113680         return i;
113681       }
113682     }
113683     case '.': {
113684 #ifndef SQLITE_OMIT_FLOATING_POINT
113685       if( !sqlite3Isdigit(z[1]) )
113686 #endif
113687       {
113688         *tokenType = TK_DOT;
113689         return 1;
113690       }
113691       /* If the next character is a digit, this is a floating point
113692       ** number that begins with ".".  Fall thru into the next case */
113693     }
113694     case '0': case '1': case '2': case '3': case '4':
113695     case '5': case '6': case '7': case '8': case '9': {
113696       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
113697       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
113698       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
113699       testcase( z[0]=='9' );
113700       *tokenType = TK_INTEGER;
113701       for(i=0; sqlite3Isdigit(z[i]); i++){}
113702 #ifndef SQLITE_OMIT_FLOATING_POINT
113703       if( z[i]=='.' ){
113704         i++;
113705         while( sqlite3Isdigit(z[i]) ){ i++; }
113706         *tokenType = TK_FLOAT;
113707       }
113708       if( (z[i]=='e' || z[i]=='E') &&
113709            ( sqlite3Isdigit(z[i+1])
113710             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
113711            )
113712       ){
113713         i += 2;
113714         while( sqlite3Isdigit(z[i]) ){ i++; }
113715         *tokenType = TK_FLOAT;
113716       }
113717 #endif
113718       while( IdChar(z[i]) ){
113719         *tokenType = TK_ILLEGAL;
113720         i++;
113721       }
113722       return i;
113723     }
113724     case '[': {
113725       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
113726       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
113727       return i;
113728     }
113729     case '?': {
113730       *tokenType = TK_VARIABLE;
113731       for(i=1; sqlite3Isdigit(z[i]); i++){}
113732       return i;
113733     }
113734     case '#': {
113735       for(i=1; sqlite3Isdigit(z[i]); i++){}
113736       if( i>1 ){
113737         /* Parameters of the form #NNN (where NNN is a number) are used
113738         ** internally by sqlite3NestedParse.  */
113739         *tokenType = TK_REGISTER;
113740         return i;
113741       }
113742       /* Fall through into the next case if the '#' is not followed by
113743       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
113744     }
113745 #ifndef SQLITE_OMIT_TCL_VARIABLE
113746     case '$':
113747 #endif
113748     case '@':  /* For compatibility with MS SQL Server */
113749     case ':': {
113750       int n = 0;
113751       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
113752       *tokenType = TK_VARIABLE;
113753       for(i=1; (c=z[i])!=0; i++){
113754         if( IdChar(c) ){
113755           n++;
113756 #ifndef SQLITE_OMIT_TCL_VARIABLE
113757         }else if( c=='(' && n>0 ){
113758           do{
113759             i++;
113760           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
113761           if( c==')' ){
113762             i++;
113763           }else{
113764             *tokenType = TK_ILLEGAL;
113765           }
113766           break;
113767         }else if( c==':' && z[i+1]==':' ){
113768           i++;
113769 #endif
113770         }else{
113771           break;
113772         }
113773       }
113774       if( n==0 ) *tokenType = TK_ILLEGAL;
113775       return i;
113776     }
113777 #ifndef SQLITE_OMIT_BLOB_LITERAL
113778     case 'x': case 'X': {
113779       testcase( z[0]=='x' ); testcase( z[0]=='X' );
113780       if( z[1]=='\'' ){
113781         *tokenType = TK_BLOB;
113782         for(i=2; sqlite3Isxdigit(z[i]); i++){}
113783         if( z[i]!='\'' || i%2 ){
113784           *tokenType = TK_ILLEGAL;
113785           while( z[i] && z[i]!='\'' ){ i++; }
113786         }
113787         if( z[i] ) i++;
113788         return i;
113789       }
113790       /* Otherwise fall through to the next case */
113791     }
113792 #endif
113793     default: {
113794       if( !IdChar(*z) ){
113795         break;
113796       }
113797       for(i=1; IdChar(z[i]); i++){}
113798       *tokenType = keywordCode((char*)z, i);
113799       return i;
113800     }
113801   }
113802   *tokenType = TK_ILLEGAL;
113803   return 1;
113804 }
113805
113806 /*
113807 ** Run the parser on the given SQL string.  The parser structure is
113808 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
113809 ** then an and attempt is made to write an error message into
113810 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
113811 ** error message.
113812 */
113813 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
113814   int nErr = 0;                   /* Number of errors encountered */
113815   int i;                          /* Loop counter */
113816   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
113817   int tokenType;                  /* type of the next token */
113818   int lastTokenParsed = -1;       /* type of the previous token */
113819   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
113820   sqlite3 *db = pParse->db;       /* The database connection */
113821   int mxSqlLen;                   /* Max length of an SQL string */
113822
113823
113824   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
113825   if( db->activeVdbeCnt==0 ){
113826     db->u1.isInterrupted = 0;
113827   }
113828   pParse->rc = SQLITE_OK;
113829   pParse->zTail = zSql;
113830   i = 0;
113831   assert( pzErrMsg!=0 );
113832   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
113833   if( pEngine==0 ){
113834     db->mallocFailed = 1;
113835     return SQLITE_NOMEM;
113836   }
113837   assert( pParse->pNewTable==0 );
113838   assert( pParse->pNewTrigger==0 );
113839   assert( pParse->nVar==0 );
113840   assert( pParse->nzVar==0 );
113841   assert( pParse->azVar==0 );
113842   enableLookaside = db->lookaside.bEnabled;
113843   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
113844   while( !db->mallocFailed && zSql[i]!=0 ){
113845     assert( i>=0 );
113846     pParse->sLastToken.z = &zSql[i];
113847     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
113848     i += pParse->sLastToken.n;
113849     if( i>mxSqlLen ){
113850       pParse->rc = SQLITE_TOOBIG;
113851       break;
113852     }
113853     switch( tokenType ){
113854       case TK_SPACE: {
113855         if( db->u1.isInterrupted ){
113856           sqlite3ErrorMsg(pParse, "interrupt");
113857           pParse->rc = SQLITE_INTERRUPT;
113858           goto abort_parse;
113859         }
113860         break;
113861       }
113862       case TK_ILLEGAL: {
113863         sqlite3DbFree(db, *pzErrMsg);
113864         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
113865                         &pParse->sLastToken);
113866         nErr++;
113867         goto abort_parse;
113868       }
113869       case TK_SEMI: {
113870         pParse->zTail = &zSql[i];
113871         /* Fall thru into the default case */
113872       }
113873       default: {
113874         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
113875         lastTokenParsed = tokenType;
113876         if( pParse->rc!=SQLITE_OK ){
113877           goto abort_parse;
113878         }
113879         break;
113880       }
113881     }
113882   }
113883 abort_parse:
113884   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
113885     if( lastTokenParsed!=TK_SEMI ){
113886       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
113887       pParse->zTail = &zSql[i];
113888     }
113889     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
113890   }
113891 #ifdef YYTRACKMAXSTACKDEPTH
113892   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
113893       sqlite3ParserStackPeak(pEngine)
113894   );
113895 #endif /* YYDEBUG */
113896   sqlite3ParserFree(pEngine, sqlite3_free);
113897   db->lookaside.bEnabled = enableLookaside;
113898   if( db->mallocFailed ){
113899     pParse->rc = SQLITE_NOMEM;
113900   }
113901   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
113902     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
113903   }
113904   assert( pzErrMsg!=0 );
113905   if( pParse->zErrMsg ){
113906     *pzErrMsg = pParse->zErrMsg;
113907     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
113908     pParse->zErrMsg = 0;
113909     nErr++;
113910   }
113911   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
113912     sqlite3VdbeDelete(pParse->pVdbe);
113913     pParse->pVdbe = 0;
113914   }
113915 #ifndef SQLITE_OMIT_SHARED_CACHE
113916   if( pParse->nested==0 ){
113917     sqlite3DbFree(db, pParse->aTableLock);
113918     pParse->aTableLock = 0;
113919     pParse->nTableLock = 0;
113920   }
113921 #endif
113922 #ifndef SQLITE_OMIT_VIRTUALTABLE
113923   sqlite3_free(pParse->apVtabLock);
113924 #endif
113925
113926   if( !IN_DECLARE_VTAB ){
113927     /* If the pParse->declareVtab flag is set, do not delete any table
113928     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
113929     ** will take responsibility for freeing the Table structure.
113930     */
113931     sqlite3DeleteTable(db, pParse->pNewTable);
113932   }
113933
113934   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
113935   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
113936   sqlite3DbFree(db, pParse->azVar);
113937   sqlite3DbFree(db, pParse->aAlias);
113938   while( pParse->pAinc ){
113939     AutoincInfo *p = pParse->pAinc;
113940     pParse->pAinc = p->pNext;
113941     sqlite3DbFree(db, p);
113942   }
113943   while( pParse->pZombieTab ){
113944     Table *p = pParse->pZombieTab;
113945     pParse->pZombieTab = p->pNextZombie;
113946     sqlite3DeleteTable(db, p);
113947   }
113948   if( nErr>0 && pParse->rc==SQLITE_OK ){
113949     pParse->rc = SQLITE_ERROR;
113950   }
113951   return nErr;
113952 }
113953
113954 /************** End of tokenize.c ********************************************/
113955 /************** Begin file complete.c ****************************************/
113956 /*
113957 ** 2001 September 15
113958 **
113959 ** The author disclaims copyright to this source code.  In place of
113960 ** a legal notice, here is a blessing:
113961 **
113962 **    May you do good and not evil.
113963 **    May you find forgiveness for yourself and forgive others.
113964 **    May you share freely, never taking more than you give.
113965 **
113966 *************************************************************************
113967 ** An tokenizer for SQL
113968 **
113969 ** This file contains C code that implements the sqlite3_complete() API.
113970 ** This code used to be part of the tokenizer.c source file.  But by
113971 ** separating it out, the code will be automatically omitted from
113972 ** static links that do not use it.
113973 */
113974 #ifndef SQLITE_OMIT_COMPLETE
113975
113976 /*
113977 ** This is defined in tokenize.c.  We just have to import the definition.
113978 */
113979 #ifndef SQLITE_AMALGAMATION
113980 #ifdef SQLITE_ASCII
113981 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
113982 #endif
113983 #ifdef SQLITE_EBCDIC
113984 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
113985 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
113986 #endif
113987 #endif /* SQLITE_AMALGAMATION */
113988
113989
113990 /*
113991 ** Token types used by the sqlite3_complete() routine.  See the header
113992 ** comments on that procedure for additional information.
113993 */
113994 #define tkSEMI    0
113995 #define tkWS      1
113996 #define tkOTHER   2
113997 #ifndef SQLITE_OMIT_TRIGGER
113998 #define tkEXPLAIN 3
113999 #define tkCREATE  4
114000 #define tkTEMP    5
114001 #define tkTRIGGER 6
114002 #define tkEND     7
114003 #endif
114004
114005 /*
114006 ** Return TRUE if the given SQL string ends in a semicolon.
114007 **
114008 ** Special handling is require for CREATE TRIGGER statements.
114009 ** Whenever the CREATE TRIGGER keywords are seen, the statement
114010 ** must end with ";END;".
114011 **
114012 ** This implementation uses a state machine with 8 states:
114013 **
114014 **   (0) INVALID   We have not yet seen a non-whitespace character.
114015 **
114016 **   (1) START     At the beginning or end of an SQL statement.  This routine
114017 **                 returns 1 if it ends in the START state and 0 if it ends
114018 **                 in any other state.
114019 **
114020 **   (2) NORMAL    We are in the middle of statement which ends with a single
114021 **                 semicolon.
114022 **
114023 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
114024 **                 a statement.
114025 **
114026 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
114027 **                 statement, possibly preceeded by EXPLAIN and/or followed by
114028 **                 TEMP or TEMPORARY
114029 **
114030 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
114031 **                 ended by a semicolon, the keyword END, and another semicolon.
114032 **
114033 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
114034 **                 the end of a trigger definition.
114035 **
114036 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
114037 **                 of a trigger difinition.
114038 **
114039 ** Transitions between states above are determined by tokens extracted
114040 ** from the input.  The following tokens are significant:
114041 **
114042 **   (0) tkSEMI      A semicolon.
114043 **   (1) tkWS        Whitespace.
114044 **   (2) tkOTHER     Any other SQL token.
114045 **   (3) tkEXPLAIN   The "explain" keyword.
114046 **   (4) tkCREATE    The "create" keyword.
114047 **   (5) tkTEMP      The "temp" or "temporary" keyword.
114048 **   (6) tkTRIGGER   The "trigger" keyword.
114049 **   (7) tkEND       The "end" keyword.
114050 **
114051 ** Whitespace never causes a state transition and is always ignored.
114052 ** This means that a SQL string of all whitespace is invalid.
114053 **
114054 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
114055 ** to recognize the end of a trigger can be omitted.  All we have to do
114056 ** is look for a semicolon that is not part of an string or comment.
114057 */
114058 SQLITE_API int sqlite3_complete(const char *zSql){
114059   u8 state = 0;   /* Current state, using numbers defined in header comment */
114060   u8 token;       /* Value of the next token */
114061
114062 #ifndef SQLITE_OMIT_TRIGGER
114063   /* A complex statement machine used to detect the end of a CREATE TRIGGER
114064   ** statement.  This is the normal case.
114065   */
114066   static const u8 trans[8][8] = {
114067                      /* Token:                                                */
114068      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
114069      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
114070      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
114071      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
114072      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
114073      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
114074      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
114075      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
114076      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
114077   };
114078 #else
114079   /* If triggers are not supported by this compile then the statement machine
114080   ** used to detect the end of a statement is much simplier
114081   */
114082   static const u8 trans[3][3] = {
114083                      /* Token:           */
114084      /* State:       **  SEMI  WS  OTHER */
114085      /* 0 INVALID: */ {    1,  0,     2, },
114086      /* 1   START: */ {    1,  1,     2, },
114087      /* 2  NORMAL: */ {    1,  2,     2, },
114088   };
114089 #endif /* SQLITE_OMIT_TRIGGER */
114090
114091   while( *zSql ){
114092     switch( *zSql ){
114093       case ';': {  /* A semicolon */
114094         token = tkSEMI;
114095         break;
114096       }
114097       case ' ':
114098       case '\r':
114099       case '\t':
114100       case '\n':
114101       case '\f': {  /* White space is ignored */
114102         token = tkWS;
114103         break;
114104       }
114105       case '/': {   /* C-style comments */
114106         if( zSql[1]!='*' ){
114107           token = tkOTHER;
114108           break;
114109         }
114110         zSql += 2;
114111         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
114112         if( zSql[0]==0 ) return 0;
114113         zSql++;
114114         token = tkWS;
114115         break;
114116       }
114117       case '-': {   /* SQL-style comments from "--" to end of line */
114118         if( zSql[1]!='-' ){
114119           token = tkOTHER;
114120           break;
114121         }
114122         while( *zSql && *zSql!='\n' ){ zSql++; }
114123         if( *zSql==0 ) return state==1;
114124         token = tkWS;
114125         break;
114126       }
114127       case '[': {   /* Microsoft-style identifiers in [...] */
114128         zSql++;
114129         while( *zSql && *zSql!=']' ){ zSql++; }
114130         if( *zSql==0 ) return 0;
114131         token = tkOTHER;
114132         break;
114133       }
114134       case '`':     /* Grave-accent quoted symbols used by MySQL */
114135       case '"':     /* single- and double-quoted strings */
114136       case '\'': {
114137         int c = *zSql;
114138         zSql++;
114139         while( *zSql && *zSql!=c ){ zSql++; }
114140         if( *zSql==0 ) return 0;
114141         token = tkOTHER;
114142         break;
114143       }
114144       default: {
114145 #ifdef SQLITE_EBCDIC
114146         unsigned char c;
114147 #endif
114148         if( IdChar((u8)*zSql) ){
114149           /* Keywords and unquoted identifiers */
114150           int nId;
114151           for(nId=1; IdChar(zSql[nId]); nId++){}
114152 #ifdef SQLITE_OMIT_TRIGGER
114153           token = tkOTHER;
114154 #else
114155           switch( *zSql ){
114156             case 'c': case 'C': {
114157               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
114158                 token = tkCREATE;
114159               }else{
114160                 token = tkOTHER;
114161               }
114162               break;
114163             }
114164             case 't': case 'T': {
114165               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
114166                 token = tkTRIGGER;
114167               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
114168                 token = tkTEMP;
114169               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
114170                 token = tkTEMP;
114171               }else{
114172                 token = tkOTHER;
114173               }
114174               break;
114175             }
114176             case 'e':  case 'E': {
114177               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
114178                 token = tkEND;
114179               }else
114180 #ifndef SQLITE_OMIT_EXPLAIN
114181               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
114182                 token = tkEXPLAIN;
114183               }else
114184 #endif
114185               {
114186                 token = tkOTHER;
114187               }
114188               break;
114189             }
114190             default: {
114191               token = tkOTHER;
114192               break;
114193             }
114194           }
114195 #endif /* SQLITE_OMIT_TRIGGER */
114196           zSql += nId-1;
114197         }else{
114198           /* Operators and special symbols */
114199           token = tkOTHER;
114200         }
114201         break;
114202       }
114203     }
114204     state = trans[state][token];
114205     zSql++;
114206   }
114207   return state==1;
114208 }
114209
114210 #ifndef SQLITE_OMIT_UTF16
114211 /*
114212 ** This routine is the same as the sqlite3_complete() routine described
114213 ** above, except that the parameter is required to be UTF-16 encoded, not
114214 ** UTF-8.
114215 */
114216 SQLITE_API int sqlite3_complete16(const void *zSql){
114217   sqlite3_value *pVal;
114218   char const *zSql8;
114219   int rc = SQLITE_NOMEM;
114220
114221 #ifndef SQLITE_OMIT_AUTOINIT
114222   rc = sqlite3_initialize();
114223   if( rc ) return rc;
114224 #endif
114225   pVal = sqlite3ValueNew(0);
114226   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
114227   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
114228   if( zSql8 ){
114229     rc = sqlite3_complete(zSql8);
114230   }else{
114231     rc = SQLITE_NOMEM;
114232   }
114233   sqlite3ValueFree(pVal);
114234   return sqlite3ApiExit(0, rc);
114235 }
114236 #endif /* SQLITE_OMIT_UTF16 */
114237 #endif /* SQLITE_OMIT_COMPLETE */
114238
114239 /************** End of complete.c ********************************************/
114240 /************** Begin file main.c ********************************************/
114241 /*
114242 ** 2001 September 15
114243 **
114244 ** The author disclaims copyright to this source code.  In place of
114245 ** a legal notice, here is a blessing:
114246 **
114247 **    May you do good and not evil.
114248 **    May you find forgiveness for yourself and forgive others.
114249 **    May you share freely, never taking more than you give.
114250 **
114251 *************************************************************************
114252 ** Main file for the SQLite library.  The routines in this file
114253 ** implement the programmer interface to the library.  Routines in
114254 ** other files are for internal use by SQLite and should not be
114255 ** accessed by users of the library.
114256 */
114257
114258 #ifdef SQLITE_ENABLE_FTS3
114259 /************** Include fts3.h in the middle of main.c ***********************/
114260 /************** Begin file fts3.h ********************************************/
114261 /*
114262 ** 2006 Oct 10
114263 **
114264 ** The author disclaims copyright to this source code.  In place of
114265 ** a legal notice, here is a blessing:
114266 **
114267 **    May you do good and not evil.
114268 **    May you find forgiveness for yourself and forgive others.
114269 **    May you share freely, never taking more than you give.
114270 **
114271 ******************************************************************************
114272 **
114273 ** This header file is used by programs that want to link against the
114274 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
114275 */
114276
114277 #if 0
114278 extern "C" {
114279 #endif  /* __cplusplus */
114280
114281 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
114282
114283 #if 0
114284 }  /* extern "C" */
114285 #endif  /* __cplusplus */
114286
114287 /************** End of fts3.h ************************************************/
114288 /************** Continuing where we left off in main.c ***********************/
114289 #endif
114290 #ifdef SQLITE_ENABLE_RTREE
114291 /************** Include rtree.h in the middle of main.c **********************/
114292 /************** Begin file rtree.h *******************************************/
114293 /*
114294 ** 2008 May 26
114295 **
114296 ** The author disclaims copyright to this source code.  In place of
114297 ** a legal notice, here is a blessing:
114298 **
114299 **    May you do good and not evil.
114300 **    May you find forgiveness for yourself and forgive others.
114301 **    May you share freely, never taking more than you give.
114302 **
114303 ******************************************************************************
114304 **
114305 ** This header file is used by programs that want to link against the
114306 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
114307 */
114308
114309 #if 0
114310 extern "C" {
114311 #endif  /* __cplusplus */
114312
114313 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
114314
114315 #if 0
114316 }  /* extern "C" */
114317 #endif  /* __cplusplus */
114318
114319 /************** End of rtree.h ***********************************************/
114320 /************** Continuing where we left off in main.c ***********************/
114321 #endif
114322 #ifdef SQLITE_ENABLE_ICU
114323 /************** Include sqliteicu.h in the middle of main.c ******************/
114324 /************** Begin file sqliteicu.h ***************************************/
114325 /*
114326 ** 2008 May 26
114327 **
114328 ** The author disclaims copyright to this source code.  In place of
114329 ** a legal notice, here is a blessing:
114330 **
114331 **    May you do good and not evil.
114332 **    May you find forgiveness for yourself and forgive others.
114333 **    May you share freely, never taking more than you give.
114334 **
114335 ******************************************************************************
114336 **
114337 ** This header file is used by programs that want to link against the
114338 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
114339 */
114340
114341 #if 0
114342 extern "C" {
114343 #endif  /* __cplusplus */
114344
114345 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
114346
114347 #if 0
114348 }  /* extern "C" */
114349 #endif  /* __cplusplus */
114350
114351
114352 /************** End of sqliteicu.h *******************************************/
114353 /************** Continuing where we left off in main.c ***********************/
114354 #endif
114355
114356 #ifndef SQLITE_AMALGAMATION
114357 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
114358 ** contains the text of SQLITE_VERSION macro.
114359 */
114360 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
114361 #endif
114362
114363 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
114364 ** a pointer to the to the sqlite3_version[] string constant.
114365 */
114366 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
114367
114368 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
114369 ** pointer to a string constant whose value is the same as the
114370 ** SQLITE_SOURCE_ID C preprocessor macro.
114371 */
114372 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
114373
114374 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
114375 ** returns an integer equal to SQLITE_VERSION_NUMBER.
114376 */
114377 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
114378
114379 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
114380 ** zero if and only if SQLite was compiled with mutexing code omitted due to
114381 ** the SQLITE_THREADSAFE compile-time option being set to 0.
114382 */
114383 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
114384
114385 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
114386 /*
114387 ** If the following function pointer is not NULL and if
114388 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
114389 ** I/O active are written using this function.  These messages
114390 ** are intended for debugging activity only.
114391 */
114392 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
114393 #endif
114394
114395 /*
114396 ** If the following global variable points to a string which is the
114397 ** name of a directory, then that directory will be used to store
114398 ** temporary files.
114399 **
114400 ** See also the "PRAGMA temp_store_directory" SQL command.
114401 */
114402 SQLITE_API char *sqlite3_temp_directory = 0;
114403
114404 /*
114405 ** If the following global variable points to a string which is the
114406 ** name of a directory, then that directory will be used to store
114407 ** all database files specified with a relative pathname.
114408 **
114409 ** See also the "PRAGMA data_store_directory" SQL command.
114410 */
114411 SQLITE_API char *sqlite3_data_directory = 0;
114412
114413 /*
114414 ** Initialize SQLite.
114415 **
114416 ** This routine must be called to initialize the memory allocation,
114417 ** VFS, and mutex subsystems prior to doing any serious work with
114418 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
114419 ** this routine will be called automatically by key routines such as
114420 ** sqlite3_open().
114421 **
114422 ** This routine is a no-op except on its very first call for the process,
114423 ** or for the first call after a call to sqlite3_shutdown.
114424 **
114425 ** The first thread to call this routine runs the initialization to
114426 ** completion.  If subsequent threads call this routine before the first
114427 ** thread has finished the initialization process, then the subsequent
114428 ** threads must block until the first thread finishes with the initialization.
114429 **
114430 ** The first thread might call this routine recursively.  Recursive
114431 ** calls to this routine should not block, of course.  Otherwise the
114432 ** initialization process would never complete.
114433 **
114434 ** Let X be the first thread to enter this routine.  Let Y be some other
114435 ** thread.  Then while the initial invocation of this routine by X is
114436 ** incomplete, it is required that:
114437 **
114438 **    *  Calls to this routine from Y must block until the outer-most
114439 **       call by X completes.
114440 **
114441 **    *  Recursive calls to this routine from thread X return immediately
114442 **       without blocking.
114443 */
114444 SQLITE_API int sqlite3_initialize(void){
114445   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
114446   int rc;                                      /* Result code */
114447
114448 #ifdef SQLITE_OMIT_WSD
114449   rc = sqlite3_wsd_init(4096, 24);
114450   if( rc!=SQLITE_OK ){
114451     return rc;
114452   }
114453 #endif
114454
114455   /* If SQLite is already completely initialized, then this call
114456   ** to sqlite3_initialize() should be a no-op.  But the initialization
114457   ** must be complete.  So isInit must not be set until the very end
114458   ** of this routine.
114459   */
114460   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
114461
114462 #ifdef SQLITE_ENABLE_SQLLOG
114463   {
114464     extern void sqlite3_init_sqllog(void);
114465     sqlite3_init_sqllog();
114466   }
114467 #endif
114468
114469   /* Make sure the mutex subsystem is initialized.  If unable to
114470   ** initialize the mutex subsystem, return early with the error.
114471   ** If the system is so sick that we are unable to allocate a mutex,
114472   ** there is not much SQLite is going to be able to do.
114473   **
114474   ** The mutex subsystem must take care of serializing its own
114475   ** initialization.
114476   */
114477   rc = sqlite3MutexInit();
114478   if( rc ) return rc;
114479
114480   /* Initialize the malloc() system and the recursive pInitMutex mutex.
114481   ** This operation is protected by the STATIC_MASTER mutex.  Note that
114482   ** MutexAlloc() is called for a static mutex prior to initializing the
114483   ** malloc subsystem - this implies that the allocation of a static
114484   ** mutex must not require support from the malloc subsystem.
114485   */
114486   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
114487   sqlite3_mutex_enter(pMaster);
114488   sqlite3GlobalConfig.isMutexInit = 1;
114489   if( !sqlite3GlobalConfig.isMallocInit ){
114490     rc = sqlite3MallocInit();
114491   }
114492   if( rc==SQLITE_OK ){
114493     sqlite3GlobalConfig.isMallocInit = 1;
114494     if( !sqlite3GlobalConfig.pInitMutex ){
114495       sqlite3GlobalConfig.pInitMutex =
114496            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
114497       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
114498         rc = SQLITE_NOMEM;
114499       }
114500     }
114501   }
114502   if( rc==SQLITE_OK ){
114503     sqlite3GlobalConfig.nRefInitMutex++;
114504   }
114505   sqlite3_mutex_leave(pMaster);
114506
114507   /* If rc is not SQLITE_OK at this point, then either the malloc
114508   ** subsystem could not be initialized or the system failed to allocate
114509   ** the pInitMutex mutex. Return an error in either case.  */
114510   if( rc!=SQLITE_OK ){
114511     return rc;
114512   }
114513
114514   /* Do the rest of the initialization under the recursive mutex so
114515   ** that we will be able to handle recursive calls into
114516   ** sqlite3_initialize().  The recursive calls normally come through
114517   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
114518   ** recursive calls might also be possible.
114519   **
114520   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
114521   ** to the xInit method, so the xInit method need not be threadsafe.
114522   **
114523   ** The following mutex is what serializes access to the appdef pcache xInit
114524   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
114525   ** call to sqlite3PcacheInitialize().
114526   */
114527   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
114528   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
114529     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
114530     sqlite3GlobalConfig.inProgress = 1;
114531     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
114532     sqlite3RegisterGlobalFunctions();
114533     if( sqlite3GlobalConfig.isPCacheInit==0 ){
114534       rc = sqlite3PcacheInitialize();
114535     }
114536     if( rc==SQLITE_OK ){
114537       sqlite3GlobalConfig.isPCacheInit = 1;
114538       rc = sqlite3OsInit();
114539     }
114540     if( rc==SQLITE_OK ){
114541       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
114542           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
114543       sqlite3GlobalConfig.isInit = 1;
114544     }
114545     sqlite3GlobalConfig.inProgress = 0;
114546   }
114547   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
114548
114549   /* Go back under the static mutex and clean up the recursive
114550   ** mutex to prevent a resource leak.
114551   */
114552   sqlite3_mutex_enter(pMaster);
114553   sqlite3GlobalConfig.nRefInitMutex--;
114554   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
114555     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
114556     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
114557     sqlite3GlobalConfig.pInitMutex = 0;
114558   }
114559   sqlite3_mutex_leave(pMaster);
114560
114561   /* The following is just a sanity check to make sure SQLite has
114562   ** been compiled correctly.  It is important to run this code, but
114563   ** we don't want to run it too often and soak up CPU cycles for no
114564   ** reason.  So we run it once during initialization.
114565   */
114566 #ifndef NDEBUG
114567 #ifndef SQLITE_OMIT_FLOATING_POINT
114568   /* This section of code's only "output" is via assert() statements. */
114569   if ( rc==SQLITE_OK ){
114570     u64 x = (((u64)1)<<63)-1;
114571     double y;
114572     assert(sizeof(x)==8);
114573     assert(sizeof(x)==sizeof(y));
114574     memcpy(&y, &x, 8);
114575     assert( sqlite3IsNaN(y) );
114576   }
114577 #endif
114578 #endif
114579
114580   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
114581   ** compile-time option.
114582   */
114583 #ifdef SQLITE_EXTRA_INIT
114584   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
114585     int SQLITE_EXTRA_INIT(const char*);
114586     rc = SQLITE_EXTRA_INIT(0);
114587   }
114588 #endif
114589
114590   return rc;
114591 }
114592
114593 /*
114594 ** Undo the effects of sqlite3_initialize().  Must not be called while
114595 ** there are outstanding database connections or memory allocations or
114596 ** while any part of SQLite is otherwise in use in any thread.  This
114597 ** routine is not threadsafe.  But it is safe to invoke this routine
114598 ** on when SQLite is already shut down.  If SQLite is already shut down
114599 ** when this routine is invoked, then this routine is a harmless no-op.
114600 */
114601 SQLITE_API int sqlite3_shutdown(void){
114602   if( sqlite3GlobalConfig.isInit ){
114603 #ifdef SQLITE_EXTRA_SHUTDOWN
114604     void SQLITE_EXTRA_SHUTDOWN(void);
114605     SQLITE_EXTRA_SHUTDOWN();
114606 #endif
114607     sqlite3_os_end();
114608     sqlite3_reset_auto_extension();
114609     sqlite3GlobalConfig.isInit = 0;
114610   }
114611   if( sqlite3GlobalConfig.isPCacheInit ){
114612     sqlite3PcacheShutdown();
114613     sqlite3GlobalConfig.isPCacheInit = 0;
114614   }
114615   if( sqlite3GlobalConfig.isMallocInit ){
114616     sqlite3MallocEnd();
114617     sqlite3GlobalConfig.isMallocInit = 0;
114618
114619 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
114620     /* The heap subsystem has now been shutdown and these values are supposed
114621     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
114622     ** which would rely on that heap subsystem; therefore, make sure these
114623     ** values cannot refer to heap memory that was just invalidated when the
114624     ** heap subsystem was shutdown.  This is only done if the current call to
114625     ** this function resulted in the heap subsystem actually being shutdown.
114626     */
114627     sqlite3_data_directory = 0;
114628     sqlite3_temp_directory = 0;
114629 #endif
114630   }
114631   if( sqlite3GlobalConfig.isMutexInit ){
114632     sqlite3MutexEnd();
114633     sqlite3GlobalConfig.isMutexInit = 0;
114634   }
114635
114636   return SQLITE_OK;
114637 }
114638
114639 /*
114640 ** This API allows applications to modify the global configuration of
114641 ** the SQLite library at run-time.
114642 **
114643 ** This routine should only be called when there are no outstanding
114644 ** database connections or memory allocations.  This routine is not
114645 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
114646 ** behavior.
114647 */
114648 SQLITE_API int sqlite3_config(int op, ...){
114649   va_list ap;
114650   int rc = SQLITE_OK;
114651
114652   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
114653   ** the SQLite library is in use. */
114654   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
114655
114656   va_start(ap, op);
114657   switch( op ){
114658
114659     /* Mutex configuration options are only available in a threadsafe
114660     ** compile.
114661     */
114662 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
114663     case SQLITE_CONFIG_SINGLETHREAD: {
114664       /* Disable all mutexing */
114665       sqlite3GlobalConfig.bCoreMutex = 0;
114666       sqlite3GlobalConfig.bFullMutex = 0;
114667       break;
114668     }
114669     case SQLITE_CONFIG_MULTITHREAD: {
114670       /* Disable mutexing of database connections */
114671       /* Enable mutexing of core data structures */
114672       sqlite3GlobalConfig.bCoreMutex = 1;
114673       sqlite3GlobalConfig.bFullMutex = 0;
114674       break;
114675     }
114676     case SQLITE_CONFIG_SERIALIZED: {
114677       /* Enable all mutexing */
114678       sqlite3GlobalConfig.bCoreMutex = 1;
114679       sqlite3GlobalConfig.bFullMutex = 1;
114680       break;
114681     }
114682     case SQLITE_CONFIG_MUTEX: {
114683       /* Specify an alternative mutex implementation */
114684       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
114685       break;
114686     }
114687     case SQLITE_CONFIG_GETMUTEX: {
114688       /* Retrieve the current mutex implementation */
114689       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
114690       break;
114691     }
114692 #endif
114693
114694
114695     case SQLITE_CONFIG_MALLOC: {
114696       /* Specify an alternative malloc implementation */
114697       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
114698       break;
114699     }
114700     case SQLITE_CONFIG_GETMALLOC: {
114701       /* Retrieve the current malloc() implementation */
114702       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
114703       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
114704       break;
114705     }
114706     case SQLITE_CONFIG_MEMSTATUS: {
114707       /* Enable or disable the malloc status collection */
114708       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
114709       break;
114710     }
114711     case SQLITE_CONFIG_SCRATCH: {
114712       /* Designate a buffer for scratch memory space */
114713       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
114714       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
114715       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
114716       break;
114717     }
114718     case SQLITE_CONFIG_PAGECACHE: {
114719       /* Designate a buffer for page cache memory space */
114720       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
114721       sqlite3GlobalConfig.szPage = va_arg(ap, int);
114722       sqlite3GlobalConfig.nPage = va_arg(ap, int);
114723       break;
114724     }
114725
114726     case SQLITE_CONFIG_PCACHE: {
114727       /* no-op */
114728       break;
114729     }
114730     case SQLITE_CONFIG_GETPCACHE: {
114731       /* now an error */
114732       rc = SQLITE_ERROR;
114733       break;
114734     }
114735
114736     case SQLITE_CONFIG_PCACHE2: {
114737       /* Specify an alternative page cache implementation */
114738       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
114739       break;
114740     }
114741     case SQLITE_CONFIG_GETPCACHE2: {
114742       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
114743         sqlite3PCacheSetDefault();
114744       }
114745       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
114746       break;
114747     }
114748
114749 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
114750     case SQLITE_CONFIG_HEAP: {
114751       /* Designate a buffer for heap memory space */
114752       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
114753       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
114754       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
114755
114756       if( sqlite3GlobalConfig.mnReq<1 ){
114757         sqlite3GlobalConfig.mnReq = 1;
114758       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
114759         /* cap min request size at 2^12 */
114760         sqlite3GlobalConfig.mnReq = (1<<12);
114761       }
114762
114763       if( sqlite3GlobalConfig.pHeap==0 ){
114764         /* If the heap pointer is NULL, then restore the malloc implementation
114765         ** back to NULL pointers too.  This will cause the malloc to go
114766         ** back to its default implementation when sqlite3_initialize() is
114767         ** run.
114768         */
114769         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
114770       }else{
114771         /* The heap pointer is not NULL, then install one of the
114772         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
114773         ** ENABLE_MEMSYS5 is defined, return an error.
114774         */
114775 #ifdef SQLITE_ENABLE_MEMSYS3
114776         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
114777 #endif
114778 #ifdef SQLITE_ENABLE_MEMSYS5
114779         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
114780 #endif
114781       }
114782       break;
114783     }
114784 #endif
114785
114786     case SQLITE_CONFIG_LOOKASIDE: {
114787       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
114788       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
114789       break;
114790     }
114791
114792     /* Record a pointer to the logger funcction and its first argument.
114793     ** The default is NULL.  Logging is disabled if the function pointer is
114794     ** NULL.
114795     */
114796     case SQLITE_CONFIG_LOG: {
114797       /* MSVC is picky about pulling func ptrs from va lists.
114798       ** http://support.microsoft.com/kb/47961
114799       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
114800       */
114801       typedef void(*LOGFUNC_t)(void*,int,const char*);
114802       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
114803       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
114804       break;
114805     }
114806
114807     case SQLITE_CONFIG_URI: {
114808       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
114809       break;
114810     }
114811
114812     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
114813       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
114814       break;
114815     }
114816
114817 #ifdef SQLITE_ENABLE_SQLLOG
114818     case SQLITE_CONFIG_SQLLOG: {
114819       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
114820       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
114821       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
114822       break;
114823     }
114824 #endif
114825
114826     default: {
114827       rc = SQLITE_ERROR;
114828       break;
114829     }
114830   }
114831   va_end(ap);
114832   return rc;
114833 }
114834
114835 /*
114836 ** Set up the lookaside buffers for a database connection.
114837 ** Return SQLITE_OK on success.
114838 ** If lookaside is already active, return SQLITE_BUSY.
114839 **
114840 ** The sz parameter is the number of bytes in each lookaside slot.
114841 ** The cnt parameter is the number of slots.  If pStart is NULL the
114842 ** space for the lookaside memory is obtained from sqlite3_malloc().
114843 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
114844 ** the lookaside memory.
114845 */
114846 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
114847   void *pStart;
114848   if( db->lookaside.nOut ){
114849     return SQLITE_BUSY;
114850   }
114851   /* Free any existing lookaside buffer for this handle before
114852   ** allocating a new one so we don't have to have space for
114853   ** both at the same time.
114854   */
114855   if( db->lookaside.bMalloced ){
114856     sqlite3_free(db->lookaside.pStart);
114857   }
114858   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
114859   ** than a pointer to be useful.
114860   */
114861   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
114862   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
114863   if( cnt<0 ) cnt = 0;
114864   if( sz==0 || cnt==0 ){
114865     sz = 0;
114866     pStart = 0;
114867   }else if( pBuf==0 ){
114868     sqlite3BeginBenignMalloc();
114869     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
114870     sqlite3EndBenignMalloc();
114871     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
114872   }else{
114873     pStart = pBuf;
114874   }
114875   db->lookaside.pStart = pStart;
114876   db->lookaside.pFree = 0;
114877   db->lookaside.sz = (u16)sz;
114878   if( pStart ){
114879     int i;
114880     LookasideSlot *p;
114881     assert( sz > (int)sizeof(LookasideSlot*) );
114882     p = (LookasideSlot*)pStart;
114883     for(i=cnt-1; i>=0; i--){
114884       p->pNext = db->lookaside.pFree;
114885       db->lookaside.pFree = p;
114886       p = (LookasideSlot*)&((u8*)p)[sz];
114887     }
114888     db->lookaside.pEnd = p;
114889     db->lookaside.bEnabled = 1;
114890     db->lookaside.bMalloced = pBuf==0 ?1:0;
114891   }else{
114892     db->lookaside.pEnd = 0;
114893     db->lookaside.bEnabled = 0;
114894     db->lookaside.bMalloced = 0;
114895   }
114896   return SQLITE_OK;
114897 }
114898
114899 /*
114900 ** Return the mutex associated with a database connection.
114901 */
114902 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
114903   return db->mutex;
114904 }
114905
114906 /*
114907 ** Free up as much memory as we can from the given database
114908 ** connection.
114909 */
114910 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
114911   int i;
114912   sqlite3_mutex_enter(db->mutex);
114913   sqlite3BtreeEnterAll(db);
114914   for(i=0; i<db->nDb; i++){
114915     Btree *pBt = db->aDb[i].pBt;
114916     if( pBt ){
114917       Pager *pPager = sqlite3BtreePager(pBt);
114918       sqlite3PagerShrink(pPager);
114919     }
114920   }
114921   sqlite3BtreeLeaveAll(db);
114922   sqlite3_mutex_leave(db->mutex);
114923   return SQLITE_OK;
114924 }
114925
114926 /*
114927 ** Configuration settings for an individual database connection
114928 */
114929 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
114930   va_list ap;
114931   int rc;
114932   va_start(ap, op);
114933   switch( op ){
114934     case SQLITE_DBCONFIG_LOOKASIDE: {
114935       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
114936       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
114937       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
114938       rc = setupLookaside(db, pBuf, sz, cnt);
114939       break;
114940     }
114941     default: {
114942       static const struct {
114943         int op;      /* The opcode */
114944         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
114945       } aFlagOp[] = {
114946         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
114947         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
114948       };
114949       unsigned int i;
114950       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
114951       for(i=0; i<ArraySize(aFlagOp); i++){
114952         if( aFlagOp[i].op==op ){
114953           int onoff = va_arg(ap, int);
114954           int *pRes = va_arg(ap, int*);
114955           int oldFlags = db->flags;
114956           if( onoff>0 ){
114957             db->flags |= aFlagOp[i].mask;
114958           }else if( onoff==0 ){
114959             db->flags &= ~aFlagOp[i].mask;
114960           }
114961           if( oldFlags!=db->flags ){
114962             sqlite3ExpirePreparedStatements(db);
114963           }
114964           if( pRes ){
114965             *pRes = (db->flags & aFlagOp[i].mask)!=0;
114966           }
114967           rc = SQLITE_OK;
114968           break;
114969         }
114970       }
114971       break;
114972     }
114973   }
114974   va_end(ap);
114975   return rc;
114976 }
114977
114978
114979 /*
114980 ** Return true if the buffer z[0..n-1] contains all spaces.
114981 */
114982 static int allSpaces(const char *z, int n){
114983   while( n>0 && z[n-1]==' ' ){ n--; }
114984   return n==0;
114985 }
114986
114987 /*
114988 ** This is the default collating function named "BINARY" which is always
114989 ** available.
114990 **
114991 ** If the padFlag argument is not NULL then space padding at the end
114992 ** of strings is ignored.  This implements the RTRIM collation.
114993 */
114994 static int binCollFunc(
114995   void *padFlag,
114996   int nKey1, const void *pKey1,
114997   int nKey2, const void *pKey2
114998 ){
114999   int rc, n;
115000   n = nKey1<nKey2 ? nKey1 : nKey2;
115001   rc = memcmp(pKey1, pKey2, n);
115002   if( rc==0 ){
115003     if( padFlag
115004      && allSpaces(((char*)pKey1)+n, nKey1-n)
115005      && allSpaces(((char*)pKey2)+n, nKey2-n)
115006     ){
115007       /* Leave rc unchanged at 0 */
115008     }else{
115009       rc = nKey1 - nKey2;
115010     }
115011   }
115012   return rc;
115013 }
115014
115015 /*
115016 ** Another built-in collating sequence: NOCASE.
115017 **
115018 ** This collating sequence is intended to be used for "case independant
115019 ** comparison". SQLite's knowledge of upper and lower case equivalents
115020 ** extends only to the 26 characters used in the English language.
115021 **
115022 ** At the moment there is only a UTF-8 implementation.
115023 */
115024 static int nocaseCollatingFunc(
115025   void *NotUsed,
115026   int nKey1, const void *pKey1,
115027   int nKey2, const void *pKey2
115028 ){
115029   int r = sqlite3StrNICmp(
115030       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
115031   UNUSED_PARAMETER(NotUsed);
115032   if( 0==r ){
115033     r = nKey1-nKey2;
115034   }
115035   return r;
115036 }
115037
115038 /*
115039 ** Return the ROWID of the most recent insert
115040 */
115041 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
115042   return db->lastRowid;
115043 }
115044
115045 /*
115046 ** Return the number of changes in the most recent call to sqlite3_exec().
115047 */
115048 SQLITE_API int sqlite3_changes(sqlite3 *db){
115049   return db->nChange;
115050 }
115051
115052 /*
115053 ** Return the number of changes since the database handle was opened.
115054 */
115055 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
115056   return db->nTotalChange;
115057 }
115058
115059 /*
115060 ** Close all open savepoints. This function only manipulates fields of the
115061 ** database handle object, it does not close any savepoints that may be open
115062 ** at the b-tree/pager level.
115063 */
115064 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
115065   while( db->pSavepoint ){
115066     Savepoint *pTmp = db->pSavepoint;
115067     db->pSavepoint = pTmp->pNext;
115068     sqlite3DbFree(db, pTmp);
115069   }
115070   db->nSavepoint = 0;
115071   db->nStatement = 0;
115072   db->isTransactionSavepoint = 0;
115073 }
115074
115075 /*
115076 ** Invoke the destructor function associated with FuncDef p, if any. Except,
115077 ** if this is not the last copy of the function, do not invoke it. Multiple
115078 ** copies of a single function are created when create_function() is called
115079 ** with SQLITE_ANY as the encoding.
115080 */
115081 static void functionDestroy(sqlite3 *db, FuncDef *p){
115082   FuncDestructor *pDestructor = p->pDestructor;
115083   if( pDestructor ){
115084     pDestructor->nRef--;
115085     if( pDestructor->nRef==0 ){
115086       pDestructor->xDestroy(pDestructor->pUserData);
115087       sqlite3DbFree(db, pDestructor);
115088     }
115089   }
115090 }
115091
115092 /*
115093 ** Disconnect all sqlite3_vtab objects that belong to database connection
115094 ** db. This is called when db is being closed.
115095 */
115096 static void disconnectAllVtab(sqlite3 *db){
115097 #ifndef SQLITE_OMIT_VIRTUALTABLE
115098   int i;
115099   sqlite3BtreeEnterAll(db);
115100   for(i=0; i<db->nDb; i++){
115101     Schema *pSchema = db->aDb[i].pSchema;
115102     if( db->aDb[i].pSchema ){
115103       HashElem *p;
115104       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
115105         Table *pTab = (Table *)sqliteHashData(p);
115106         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
115107       }
115108     }
115109   }
115110   sqlite3BtreeLeaveAll(db);
115111 #else
115112   UNUSED_PARAMETER(db);
115113 #endif
115114 }
115115
115116 /*
115117 ** Return TRUE if database connection db has unfinalized prepared
115118 ** statements or unfinished sqlite3_backup objects.
115119 */
115120 static int connectionIsBusy(sqlite3 *db){
115121   int j;
115122   assert( sqlite3_mutex_held(db->mutex) );
115123   if( db->pVdbe ) return 1;
115124   for(j=0; j<db->nDb; j++){
115125     Btree *pBt = db->aDb[j].pBt;
115126     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
115127   }
115128   return 0;
115129 }
115130
115131 /*
115132 ** Close an existing SQLite database
115133 */
115134 static int sqlite3Close(sqlite3 *db, int forceZombie){
115135   if( !db ){
115136     return SQLITE_OK;
115137   }
115138   if( !sqlite3SafetyCheckSickOrOk(db) ){
115139     return SQLITE_MISUSE_BKPT;
115140   }
115141   sqlite3_mutex_enter(db->mutex);
115142
115143   /* Force xDisconnect calls on all virtual tables */
115144   disconnectAllVtab(db);
115145
115146   /* If a transaction is open, the disconnectAllVtab() call above
115147   ** will not have called the xDisconnect() method on any virtual
115148   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
115149   ** call will do so. We need to do this before the check for active
115150   ** SQL statements below, as the v-table implementation may be storing
115151   ** some prepared statements internally.
115152   */
115153   sqlite3VtabRollback(db);
115154
115155   /* Legacy behavior (sqlite3_close() behavior) is to return
115156   ** SQLITE_BUSY if the connection can not be closed immediately.
115157   */
115158   if( !forceZombie && connectionIsBusy(db) ){
115159     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
115160        "statements or unfinished backups");
115161     sqlite3_mutex_leave(db->mutex);
115162     return SQLITE_BUSY;
115163   }
115164
115165 #ifdef SQLITE_ENABLE_SQLLOG
115166   if( sqlite3GlobalConfig.xSqllog ){
115167     /* Closing the handle. Fourth parameter is passed the value 2. */
115168     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115169   }
115170 #endif
115171
115172   /* Convert the connection into a zombie and then close it.
115173   */
115174   db->magic = SQLITE_MAGIC_ZOMBIE;
115175   sqlite3LeaveMutexAndCloseZombie(db);
115176   return SQLITE_OK;
115177 }
115178
115179 /*
115180 ** Two variations on the public interface for closing a database
115181 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
115182 ** leaves the connection option if there are unfinalized prepared
115183 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
115184 ** version forces the connection to become a zombie if there are
115185 ** unclosed resources, and arranges for deallocation when the last
115186 ** prepare statement or sqlite3_backup closes.
115187 */
115188 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
115189 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
115190
115191
115192 /*
115193 ** Close the mutex on database connection db.
115194 **
115195 ** Furthermore, if database connection db is a zombie (meaning that there
115196 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
115197 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
115198 ** finished, then free all resources.
115199 */
115200 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
115201   HashElem *i;                    /* Hash table iterator */
115202   int j;
115203
115204   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
115205   ** or if the connection has not yet been closed by sqlite3_close_v2(),
115206   ** then just leave the mutex and return.
115207   */
115208   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
115209     sqlite3_mutex_leave(db->mutex);
115210     return;
115211   }
115212
115213   /* If we reach this point, it means that the database connection has
115214   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
115215   ** pased to sqlite3_close (meaning that it is a zombie).  Therefore,
115216   ** go ahead and free all resources.
115217   */
115218
115219   /* Free any outstanding Savepoint structures. */
115220   sqlite3CloseSavepoints(db);
115221
115222   /* Close all database connections */
115223   for(j=0; j<db->nDb; j++){
115224     struct Db *pDb = &db->aDb[j];
115225     if( pDb->pBt ){
115226       sqlite3BtreeClose(pDb->pBt);
115227       pDb->pBt = 0;
115228       if( j!=1 ){
115229         pDb->pSchema = 0;
115230       }
115231     }
115232   }
115233   /* Clear the TEMP schema separately and last */
115234   if( db->aDb[1].pSchema ){
115235     sqlite3SchemaClear(db->aDb[1].pSchema);
115236   }
115237   sqlite3VtabUnlockList(db);
115238
115239   /* Free up the array of auxiliary databases */
115240   sqlite3CollapseDatabaseArray(db);
115241   assert( db->nDb<=2 );
115242   assert( db->aDb==db->aDbStatic );
115243
115244   /* Tell the code in notify.c that the connection no longer holds any
115245   ** locks and does not require any further unlock-notify callbacks.
115246   */
115247   sqlite3ConnectionClosed(db);
115248
115249   for(j=0; j<ArraySize(db->aFunc.a); j++){
115250     FuncDef *pNext, *pHash, *p;
115251     for(p=db->aFunc.a[j]; p; p=pHash){
115252       pHash = p->pHash;
115253       while( p ){
115254         functionDestroy(db, p);
115255         pNext = p->pNext;
115256         sqlite3DbFree(db, p);
115257         p = pNext;
115258       }
115259     }
115260   }
115261   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
115262     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
115263     /* Invoke any destructors registered for collation sequence user data. */
115264     for(j=0; j<3; j++){
115265       if( pColl[j].xDel ){
115266         pColl[j].xDel(pColl[j].pUser);
115267       }
115268     }
115269     sqlite3DbFree(db, pColl);
115270   }
115271   sqlite3HashClear(&db->aCollSeq);
115272 #ifndef SQLITE_OMIT_VIRTUALTABLE
115273   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
115274     Module *pMod = (Module *)sqliteHashData(i);
115275     if( pMod->xDestroy ){
115276       pMod->xDestroy(pMod->pAux);
115277     }
115278     sqlite3DbFree(db, pMod);
115279   }
115280   sqlite3HashClear(&db->aModule);
115281 #endif
115282
115283   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
115284   if( db->pErr ){
115285     sqlite3ValueFree(db->pErr);
115286   }
115287   sqlite3CloseExtensions(db);
115288
115289   db->magic = SQLITE_MAGIC_ERROR;
115290
115291   /* The temp-database schema is allocated differently from the other schema
115292   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
115293   ** So it needs to be freed here. Todo: Why not roll the temp schema into
115294   ** the same sqliteMalloc() as the one that allocates the database
115295   ** structure?
115296   */
115297   sqlite3DbFree(db, db->aDb[1].pSchema);
115298   sqlite3_mutex_leave(db->mutex);
115299   db->magic = SQLITE_MAGIC_CLOSED;
115300   sqlite3_mutex_free(db->mutex);
115301   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
115302   if( db->lookaside.bMalloced ){
115303     sqlite3_free(db->lookaside.pStart);
115304   }
115305   sqlite3_free(db);
115306 }
115307
115308 /*
115309 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
115310 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
115311 ** breaker") and made to return tripCode if there are any further
115312 ** attempts to use that cursor.
115313 */
115314 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115315   int i;
115316   int inTrans = 0;
115317   assert( sqlite3_mutex_held(db->mutex) );
115318   sqlite3BeginBenignMalloc();
115319   for(i=0; i<db->nDb; i++){
115320     Btree *p = db->aDb[i].pBt;
115321     if( p ){
115322       if( sqlite3BtreeIsInTrans(p) ){
115323         inTrans = 1;
115324       }
115325       sqlite3BtreeRollback(p, tripCode);
115326       db->aDb[i].inTrans = 0;
115327     }
115328   }
115329   sqlite3VtabRollback(db);
115330   sqlite3EndBenignMalloc();
115331
115332   if( db->flags&SQLITE_InternChanges ){
115333     sqlite3ExpirePreparedStatements(db);
115334     sqlite3ResetAllSchemasOfConnection(db);
115335   }
115336
115337   /* Any deferred constraint violations have now been resolved. */
115338   db->nDeferredCons = 0;
115339
115340   /* If one has been configured, invoke the rollback-hook callback */
115341   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
115342     db->xRollbackCallback(db->pRollbackArg);
115343   }
115344 }
115345
115346 /*
115347 ** Return a static string that describes the kind of error specified in the
115348 ** argument.
115349 */
115350 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
115351   static const char* const aMsg[] = {
115352     /* SQLITE_OK          */ "not an error",
115353     /* SQLITE_ERROR       */ "SQL logic error or missing database",
115354     /* SQLITE_INTERNAL    */ 0,
115355     /* SQLITE_PERM        */ "access permission denied",
115356     /* SQLITE_ABORT       */ "callback requested query abort",
115357     /* SQLITE_BUSY        */ "database is locked",
115358     /* SQLITE_LOCKED      */ "database table is locked",
115359     /* SQLITE_NOMEM       */ "out of memory",
115360     /* SQLITE_READONLY    */ "attempt to write a readonly database",
115361     /* SQLITE_INTERRUPT   */ "interrupted",
115362     /* SQLITE_IOERR       */ "disk I/O error",
115363     /* SQLITE_CORRUPT     */ "database disk image is malformed",
115364     /* SQLITE_NOTFOUND    */ "unknown operation",
115365     /* SQLITE_FULL        */ "database or disk is full",
115366     /* SQLITE_CANTOPEN    */ "unable to open database file",
115367     /* SQLITE_PROTOCOL    */ "locking protocol",
115368     /* SQLITE_EMPTY       */ "table contains no data",
115369     /* SQLITE_SCHEMA      */ "database schema has changed",
115370     /* SQLITE_TOOBIG      */ "string or blob too big",
115371     /* SQLITE_CONSTRAINT  */ "constraint failed",
115372     /* SQLITE_MISMATCH    */ "datatype mismatch",
115373     /* SQLITE_MISUSE      */ "library routine called out of sequence",
115374     /* SQLITE_NOLFS       */ "large file support is disabled",
115375     /* SQLITE_AUTH        */ "authorization denied",
115376     /* SQLITE_FORMAT      */ "auxiliary database format error",
115377     /* SQLITE_RANGE       */ "bind or column index out of range",
115378     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
115379   };
115380   const char *zErr = "unknown error";
115381   switch( rc ){
115382     case SQLITE_ABORT_ROLLBACK: {
115383       zErr = "abort due to ROLLBACK";
115384       break;
115385     }
115386     default: {
115387       rc &= 0xff;
115388       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
115389         zErr = aMsg[rc];
115390       }
115391       break;
115392     }
115393   }
115394   return zErr;
115395 }
115396
115397 /*
115398 ** This routine implements a busy callback that sleeps and tries
115399 ** again until a timeout value is reached.  The timeout value is
115400 ** an integer number of milliseconds passed in as the first
115401 ** argument.
115402 */
115403 static int sqliteDefaultBusyCallback(
115404  void *ptr,               /* Database connection */
115405  int count                /* Number of times table has been busy */
115406 ){
115407 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
115408   static const u8 delays[] =
115409      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
115410   static const u8 totals[] =
115411      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
115412 # define NDELAY ArraySize(delays)
115413   sqlite3 *db = (sqlite3 *)ptr;
115414   int timeout = db->busyTimeout;
115415   int delay, prior;
115416
115417   assert( count>=0 );
115418   if( count < NDELAY ){
115419     delay = delays[count];
115420     prior = totals[count];
115421   }else{
115422     delay = delays[NDELAY-1];
115423     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
115424   }
115425   if( prior + delay > timeout ){
115426     delay = timeout - prior;
115427     if( delay<=0 ) return 0;
115428   }
115429   sqlite3OsSleep(db->pVfs, delay*1000);
115430   return 1;
115431 #else
115432   sqlite3 *db = (sqlite3 *)ptr;
115433   int timeout = ((sqlite3 *)ptr)->busyTimeout;
115434   if( (count+1)*1000 > timeout ){
115435     return 0;
115436   }
115437   sqlite3OsSleep(db->pVfs, 1000000);
115438   return 1;
115439 #endif
115440 }
115441
115442 /*
115443 ** Invoke the given busy handler.
115444 **
115445 ** This routine is called when an operation failed with a lock.
115446 ** If this routine returns non-zero, the lock is retried.  If it
115447 ** returns 0, the operation aborts with an SQLITE_BUSY error.
115448 */
115449 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
115450   int rc;
115451   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
115452   rc = p->xFunc(p->pArg, p->nBusy);
115453   if( rc==0 ){
115454     p->nBusy = -1;
115455   }else{
115456     p->nBusy++;
115457   }
115458   return rc;
115459 }
115460
115461 /*
115462 ** This routine sets the busy callback for an Sqlite database to the
115463 ** given callback function with the given argument.
115464 */
115465 SQLITE_API int sqlite3_busy_handler(
115466   sqlite3 *db,
115467   int (*xBusy)(void*,int),
115468   void *pArg
115469 ){
115470   sqlite3_mutex_enter(db->mutex);
115471   db->busyHandler.xFunc = xBusy;
115472   db->busyHandler.pArg = pArg;
115473   db->busyHandler.nBusy = 0;
115474   db->busyTimeout = 0;
115475   sqlite3_mutex_leave(db->mutex);
115476   return SQLITE_OK;
115477 }
115478
115479 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
115480 /*
115481 ** This routine sets the progress callback for an Sqlite database to the
115482 ** given callback function with the given argument. The progress callback will
115483 ** be invoked every nOps opcodes.
115484 */
115485 SQLITE_API void sqlite3_progress_handler(
115486   sqlite3 *db,
115487   int nOps,
115488   int (*xProgress)(void*),
115489   void *pArg
115490 ){
115491   sqlite3_mutex_enter(db->mutex);
115492   if( nOps>0 ){
115493     db->xProgress = xProgress;
115494     db->nProgressOps = nOps;
115495     db->pProgressArg = pArg;
115496   }else{
115497     db->xProgress = 0;
115498     db->nProgressOps = 0;
115499     db->pProgressArg = 0;
115500   }
115501   sqlite3_mutex_leave(db->mutex);
115502 }
115503 #endif
115504
115505
115506 /*
115507 ** This routine installs a default busy handler that waits for the
115508 ** specified number of milliseconds before returning 0.
115509 */
115510 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
115511   if( ms>0 ){
115512     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
115513     db->busyTimeout = ms;
115514   }else{
115515     sqlite3_busy_handler(db, 0, 0);
115516   }
115517   return SQLITE_OK;
115518 }
115519
115520 /*
115521 ** Cause any pending operation to stop at its earliest opportunity.
115522 */
115523 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
115524   db->u1.isInterrupted = 1;
115525 }
115526
115527
115528 /*
115529 ** This function is exactly the same as sqlite3_create_function(), except
115530 ** that it is designed to be called by internal code. The difference is
115531 ** that if a malloc() fails in sqlite3_create_function(), an error code
115532 ** is returned and the mallocFailed flag cleared.
115533 */
115534 SQLITE_PRIVATE int sqlite3CreateFunc(
115535   sqlite3 *db,
115536   const char *zFunctionName,
115537   int nArg,
115538   int enc,
115539   void *pUserData,
115540   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
115541   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
115542   void (*xFinal)(sqlite3_context*),
115543   FuncDestructor *pDestructor
115544 ){
115545   FuncDef *p;
115546   int nName;
115547
115548   assert( sqlite3_mutex_held(db->mutex) );
115549   if( zFunctionName==0 ||
115550       (xFunc && (xFinal || xStep)) ||
115551       (!xFunc && (xFinal && !xStep)) ||
115552       (!xFunc && (!xFinal && xStep)) ||
115553       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
115554       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
115555     return SQLITE_MISUSE_BKPT;
115556   }
115557
115558 #ifndef SQLITE_OMIT_UTF16
115559   /* If SQLITE_UTF16 is specified as the encoding type, transform this
115560   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
115561   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
115562   **
115563   ** If SQLITE_ANY is specified, add three versions of the function
115564   ** to the hash table.
115565   */
115566   if( enc==SQLITE_UTF16 ){
115567     enc = SQLITE_UTF16NATIVE;
115568   }else if( enc==SQLITE_ANY ){
115569     int rc;
115570     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
115571          pUserData, xFunc, xStep, xFinal, pDestructor);
115572     if( rc==SQLITE_OK ){
115573       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
115574           pUserData, xFunc, xStep, xFinal, pDestructor);
115575     }
115576     if( rc!=SQLITE_OK ){
115577       return rc;
115578     }
115579     enc = SQLITE_UTF16BE;
115580   }
115581 #else
115582   enc = SQLITE_UTF8;
115583 #endif
115584
115585   /* Check if an existing function is being overridden or deleted. If so,
115586   ** and there are active VMs, then return SQLITE_BUSY. If a function
115587   ** is being overridden/deleted but there are no active VMs, allow the
115588   ** operation to continue but invalidate all precompiled statements.
115589   */
115590   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
115591   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
115592     if( db->activeVdbeCnt ){
115593       sqlite3Error(db, SQLITE_BUSY,
115594         "unable to delete/modify user-function due to active statements");
115595       assert( !db->mallocFailed );
115596       return SQLITE_BUSY;
115597     }else{
115598       sqlite3ExpirePreparedStatements(db);
115599     }
115600   }
115601
115602   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
115603   assert(p || db->mallocFailed);
115604   if( !p ){
115605     return SQLITE_NOMEM;
115606   }
115607
115608   /* If an older version of the function with a configured destructor is
115609   ** being replaced invoke the destructor function here. */
115610   functionDestroy(db, p);
115611
115612   if( pDestructor ){
115613     pDestructor->nRef++;
115614   }
115615   p->pDestructor = pDestructor;
115616   p->flags = 0;
115617   p->xFunc = xFunc;
115618   p->xStep = xStep;
115619   p->xFinalize = xFinal;
115620   p->pUserData = pUserData;
115621   p->nArg = (u16)nArg;
115622   return SQLITE_OK;
115623 }
115624
115625 /*
115626 ** Create new user functions.
115627 */
115628 SQLITE_API int sqlite3_create_function(
115629   sqlite3 *db,
115630   const char *zFunc,
115631   int nArg,
115632   int enc,
115633   void *p,
115634   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
115635   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
115636   void (*xFinal)(sqlite3_context*)
115637 ){
115638   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
115639                                     xFinal, 0);
115640 }
115641
115642 SQLITE_API int sqlite3_create_function_v2(
115643   sqlite3 *db,
115644   const char *zFunc,
115645   int nArg,
115646   int enc,
115647   void *p,
115648   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
115649   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
115650   void (*xFinal)(sqlite3_context*),
115651   void (*xDestroy)(void *)
115652 ){
115653   int rc = SQLITE_ERROR;
115654   FuncDestructor *pArg = 0;
115655   sqlite3_mutex_enter(db->mutex);
115656   if( xDestroy ){
115657     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
115658     if( !pArg ){
115659       xDestroy(p);
115660       goto out;
115661     }
115662     pArg->xDestroy = xDestroy;
115663     pArg->pUserData = p;
115664   }
115665   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
115666   if( pArg && pArg->nRef==0 ){
115667     assert( rc!=SQLITE_OK );
115668     xDestroy(p);
115669     sqlite3DbFree(db, pArg);
115670   }
115671
115672  out:
115673   rc = sqlite3ApiExit(db, rc);
115674   sqlite3_mutex_leave(db->mutex);
115675   return rc;
115676 }
115677
115678 #ifndef SQLITE_OMIT_UTF16
115679 SQLITE_API int sqlite3_create_function16(
115680   sqlite3 *db,
115681   const void *zFunctionName,
115682   int nArg,
115683   int eTextRep,
115684   void *p,
115685   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
115686   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
115687   void (*xFinal)(sqlite3_context*)
115688 ){
115689   int rc;
115690   char *zFunc8;
115691   sqlite3_mutex_enter(db->mutex);
115692   assert( !db->mallocFailed );
115693   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
115694   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
115695   sqlite3DbFree(db, zFunc8);
115696   rc = sqlite3ApiExit(db, rc);
115697   sqlite3_mutex_leave(db->mutex);
115698   return rc;
115699 }
115700 #endif
115701
115702
115703 /*
115704 ** Declare that a function has been overloaded by a virtual table.
115705 **
115706 ** If the function already exists as a regular global function, then
115707 ** this routine is a no-op.  If the function does not exist, then create
115708 ** a new one that always throws a run-time error.
115709 **
115710 ** When virtual tables intend to provide an overloaded function, they
115711 ** should call this routine to make sure the global function exists.
115712 ** A global function must exist in order for name resolution to work
115713 ** properly.
115714 */
115715 SQLITE_API int sqlite3_overload_function(
115716   sqlite3 *db,
115717   const char *zName,
115718   int nArg
115719 ){
115720   int nName = sqlite3Strlen30(zName);
115721   int rc = SQLITE_OK;
115722   sqlite3_mutex_enter(db->mutex);
115723   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
115724     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
115725                            0, sqlite3InvalidFunction, 0, 0, 0);
115726   }
115727   rc = sqlite3ApiExit(db, rc);
115728   sqlite3_mutex_leave(db->mutex);
115729   return rc;
115730 }
115731
115732 #ifndef SQLITE_OMIT_TRACE
115733 /*
115734 ** Register a trace function.  The pArg from the previously registered trace
115735 ** is returned.
115736 **
115737 ** A NULL trace function means that no tracing is executes.  A non-NULL
115738 ** trace is a pointer to a function that is invoked at the start of each
115739 ** SQL statement.
115740 */
115741 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
115742   void *pOld;
115743   sqlite3_mutex_enter(db->mutex);
115744   pOld = db->pTraceArg;
115745   db->xTrace = xTrace;
115746   db->pTraceArg = pArg;
115747   sqlite3_mutex_leave(db->mutex);
115748   return pOld;
115749 }
115750 /*
115751 ** Register a profile function.  The pArg from the previously registered
115752 ** profile function is returned.
115753 **
115754 ** A NULL profile function means that no profiling is executes.  A non-NULL
115755 ** profile is a pointer to a function that is invoked at the conclusion of
115756 ** each SQL statement that is run.
115757 */
115758 SQLITE_API void *sqlite3_profile(
115759   sqlite3 *db,
115760   void (*xProfile)(void*,const char*,sqlite_uint64),
115761   void *pArg
115762 ){
115763   void *pOld;
115764   sqlite3_mutex_enter(db->mutex);
115765   pOld = db->pProfileArg;
115766   db->xProfile = xProfile;
115767   db->pProfileArg = pArg;
115768   sqlite3_mutex_leave(db->mutex);
115769   return pOld;
115770 }
115771 #endif /* SQLITE_OMIT_TRACE */
115772
115773 /*
115774 ** Register a function to be invoked when a transaction commits.
115775 ** If the invoked function returns non-zero, then the commit becomes a
115776 ** rollback.
115777 */
115778 SQLITE_API void *sqlite3_commit_hook(
115779   sqlite3 *db,              /* Attach the hook to this database */
115780   int (*xCallback)(void*),  /* Function to invoke on each commit */
115781   void *pArg                /* Argument to the function */
115782 ){
115783   void *pOld;
115784   sqlite3_mutex_enter(db->mutex);
115785   pOld = db->pCommitArg;
115786   db->xCommitCallback = xCallback;
115787   db->pCommitArg = pArg;
115788   sqlite3_mutex_leave(db->mutex);
115789   return pOld;
115790 }
115791
115792 /*
115793 ** Register a callback to be invoked each time a row is updated,
115794 ** inserted or deleted using this database connection.
115795 */
115796 SQLITE_API void *sqlite3_update_hook(
115797   sqlite3 *db,              /* Attach the hook to this database */
115798   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
115799   void *pArg                /* Argument to the function */
115800 ){
115801   void *pRet;
115802   sqlite3_mutex_enter(db->mutex);
115803   pRet = db->pUpdateArg;
115804   db->xUpdateCallback = xCallback;
115805   db->pUpdateArg = pArg;
115806   sqlite3_mutex_leave(db->mutex);
115807   return pRet;
115808 }
115809
115810 /*
115811 ** Register a callback to be invoked each time a transaction is rolled
115812 ** back by this database connection.
115813 */
115814 SQLITE_API void *sqlite3_rollback_hook(
115815   sqlite3 *db,              /* Attach the hook to this database */
115816   void (*xCallback)(void*), /* Callback function */
115817   void *pArg                /* Argument to the function */
115818 ){
115819   void *pRet;
115820   sqlite3_mutex_enter(db->mutex);
115821   pRet = db->pRollbackArg;
115822   db->xRollbackCallback = xCallback;
115823   db->pRollbackArg = pArg;
115824   sqlite3_mutex_leave(db->mutex);
115825   return pRet;
115826 }
115827
115828 #ifndef SQLITE_OMIT_WAL
115829 /*
115830 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
115831 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
115832 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
115833 ** wal_autocheckpoint()).
115834 */
115835 SQLITE_PRIVATE int sqlite3WalDefaultHook(
115836   void *pClientData,     /* Argument */
115837   sqlite3 *db,           /* Connection */
115838   const char *zDb,       /* Database */
115839   int nFrame             /* Size of WAL */
115840 ){
115841   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
115842     sqlite3BeginBenignMalloc();
115843     sqlite3_wal_checkpoint(db, zDb);
115844     sqlite3EndBenignMalloc();
115845   }
115846   return SQLITE_OK;
115847 }
115848 #endif /* SQLITE_OMIT_WAL */
115849
115850 /*
115851 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
115852 ** a database after committing a transaction if there are nFrame or
115853 ** more frames in the log file. Passing zero or a negative value as the
115854 ** nFrame parameter disables automatic checkpoints entirely.
115855 **
115856 ** The callback registered by this function replaces any existing callback
115857 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
115858 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
115859 ** configured by this function.
115860 */
115861 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
115862 #ifdef SQLITE_OMIT_WAL
115863   UNUSED_PARAMETER(db);
115864   UNUSED_PARAMETER(nFrame);
115865 #else
115866   if( nFrame>0 ){
115867     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
115868   }else{
115869     sqlite3_wal_hook(db, 0, 0);
115870   }
115871 #endif
115872   return SQLITE_OK;
115873 }
115874
115875 /*
115876 ** Register a callback to be invoked each time a transaction is written
115877 ** into the write-ahead-log by this database connection.
115878 */
115879 SQLITE_API void *sqlite3_wal_hook(
115880   sqlite3 *db,                    /* Attach the hook to this db handle */
115881   int(*xCallback)(void *, sqlite3*, const char*, int),
115882   void *pArg                      /* First argument passed to xCallback() */
115883 ){
115884 #ifndef SQLITE_OMIT_WAL
115885   void *pRet;
115886   sqlite3_mutex_enter(db->mutex);
115887   pRet = db->pWalArg;
115888   db->xWalCallback = xCallback;
115889   db->pWalArg = pArg;
115890   sqlite3_mutex_leave(db->mutex);
115891   return pRet;
115892 #else
115893   return 0;
115894 #endif
115895 }
115896
115897 /*
115898 ** Checkpoint database zDb.
115899 */
115900 SQLITE_API int sqlite3_wal_checkpoint_v2(
115901   sqlite3 *db,                    /* Database handle */
115902   const char *zDb,                /* Name of attached database (or NULL) */
115903   int eMode,                      /* SQLITE_CHECKPOINT_* value */
115904   int *pnLog,                     /* OUT: Size of WAL log in frames */
115905   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
115906 ){
115907 #ifdef SQLITE_OMIT_WAL
115908   return SQLITE_OK;
115909 #else
115910   int rc;                         /* Return code */
115911   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
115912
115913   /* Initialize the output variables to -1 in case an error occurs. */
115914   if( pnLog ) *pnLog = -1;
115915   if( pnCkpt ) *pnCkpt = -1;
115916
115917   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
115918   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
115919   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
115920   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
115921     return SQLITE_MISUSE;
115922   }
115923
115924   sqlite3_mutex_enter(db->mutex);
115925   if( zDb && zDb[0] ){
115926     iDb = sqlite3FindDbName(db, zDb);
115927   }
115928   if( iDb<0 ){
115929     rc = SQLITE_ERROR;
115930     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
115931   }else{
115932     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
115933     sqlite3Error(db, rc, 0);
115934   }
115935   rc = sqlite3ApiExit(db, rc);
115936   sqlite3_mutex_leave(db->mutex);
115937   return rc;
115938 #endif
115939 }
115940
115941
115942 /*
115943 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
115944 ** to contains a zero-length string, all attached databases are
115945 ** checkpointed.
115946 */
115947 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
115948   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
115949 }
115950
115951 #ifndef SQLITE_OMIT_WAL
115952 /*
115953 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
115954 ** not currently open in WAL mode.
115955 **
115956 ** If a transaction is open on the database being checkpointed, this
115957 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
115958 ** an error occurs while running the checkpoint, an SQLite error code is
115959 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
115960 **
115961 ** The mutex on database handle db should be held by the caller. The mutex
115962 ** associated with the specific b-tree being checkpointed is taken by
115963 ** this function while the checkpoint is running.
115964 **
115965 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
115966 ** checkpointed. If an error is encountered it is returned immediately -
115967 ** no attempt is made to checkpoint any remaining databases.
115968 **
115969 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
115970 */
115971 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
115972   int rc = SQLITE_OK;             /* Return code */
115973   int i;                          /* Used to iterate through attached dbs */
115974   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
115975
115976   assert( sqlite3_mutex_held(db->mutex) );
115977   assert( !pnLog || *pnLog==-1 );
115978   assert( !pnCkpt || *pnCkpt==-1 );
115979
115980   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
115981     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
115982       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
115983       pnLog = 0;
115984       pnCkpt = 0;
115985       if( rc==SQLITE_BUSY ){
115986         bBusy = 1;
115987         rc = SQLITE_OK;
115988       }
115989     }
115990   }
115991
115992   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
115993 }
115994 #endif /* SQLITE_OMIT_WAL */
115995
115996 /*
115997 ** This function returns true if main-memory should be used instead of
115998 ** a temporary file for transient pager files and statement journals.
115999 ** The value returned depends on the value of db->temp_store (runtime
116000 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
116001 ** following table describes the relationship between these two values
116002 ** and this functions return value.
116003 **
116004 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
116005 **   -----------------     --------------     ------------------------------
116006 **   0                     any                file      (return 0)
116007 **   1                     1                  file      (return 0)
116008 **   1                     2                  memory    (return 1)
116009 **   1                     0                  file      (return 0)
116010 **   2                     1                  file      (return 0)
116011 **   2                     2                  memory    (return 1)
116012 **   2                     0                  memory    (return 1)
116013 **   3                     any                memory    (return 1)
116014 */
116015 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
116016 #if SQLITE_TEMP_STORE==1
116017   return ( db->temp_store==2 );
116018 #endif
116019 #if SQLITE_TEMP_STORE==2
116020   return ( db->temp_store!=1 );
116021 #endif
116022 #if SQLITE_TEMP_STORE==3
116023   return 1;
116024 #endif
116025 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
116026   return 0;
116027 #endif
116028 }
116029
116030 /*
116031 ** Return UTF-8 encoded English language explanation of the most recent
116032 ** error.
116033 */
116034 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
116035   const char *z;
116036   if( !db ){
116037     return sqlite3ErrStr(SQLITE_NOMEM);
116038   }
116039   if( !sqlite3SafetyCheckSickOrOk(db) ){
116040     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
116041   }
116042   sqlite3_mutex_enter(db->mutex);
116043   if( db->mallocFailed ){
116044     z = sqlite3ErrStr(SQLITE_NOMEM);
116045   }else{
116046     z = (char*)sqlite3_value_text(db->pErr);
116047     assert( !db->mallocFailed );
116048     if( z==0 ){
116049       z = sqlite3ErrStr(db->errCode);
116050     }
116051   }
116052   sqlite3_mutex_leave(db->mutex);
116053   return z;
116054 }
116055
116056 #ifndef SQLITE_OMIT_UTF16
116057 /*
116058 ** Return UTF-16 encoded English language explanation of the most recent
116059 ** error.
116060 */
116061 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
116062   static const u16 outOfMem[] = {
116063     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
116064   };
116065   static const u16 misuse[] = {
116066     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
116067     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
116068     'c', 'a', 'l', 'l', 'e', 'd', ' ',
116069     'o', 'u', 't', ' ',
116070     'o', 'f', ' ',
116071     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
116072   };
116073
116074   const void *z;
116075   if( !db ){
116076     return (void *)outOfMem;
116077   }
116078   if( !sqlite3SafetyCheckSickOrOk(db) ){
116079     return (void *)misuse;
116080   }
116081   sqlite3_mutex_enter(db->mutex);
116082   if( db->mallocFailed ){
116083     z = (void *)outOfMem;
116084   }else{
116085     z = sqlite3_value_text16(db->pErr);
116086     if( z==0 ){
116087       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
116088            SQLITE_UTF8, SQLITE_STATIC);
116089       z = sqlite3_value_text16(db->pErr);
116090     }
116091     /* A malloc() may have failed within the call to sqlite3_value_text16()
116092     ** above. If this is the case, then the db->mallocFailed flag needs to
116093     ** be cleared before returning. Do this directly, instead of via
116094     ** sqlite3ApiExit(), to avoid setting the database handle error message.
116095     */
116096     db->mallocFailed = 0;
116097   }
116098   sqlite3_mutex_leave(db->mutex);
116099   return z;
116100 }
116101 #endif /* SQLITE_OMIT_UTF16 */
116102
116103 /*
116104 ** Return the most recent error code generated by an SQLite routine. If NULL is
116105 ** passed to this function, we assume a malloc() failed during sqlite3_open().
116106 */
116107 SQLITE_API int sqlite3_errcode(sqlite3 *db){
116108   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
116109     return SQLITE_MISUSE_BKPT;
116110   }
116111   if( !db || db->mallocFailed ){
116112     return SQLITE_NOMEM;
116113   }
116114   return db->errCode & db->errMask;
116115 }
116116 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
116117   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
116118     return SQLITE_MISUSE_BKPT;
116119   }
116120   if( !db || db->mallocFailed ){
116121     return SQLITE_NOMEM;
116122   }
116123   return db->errCode;
116124 }
116125
116126 /*
116127 ** Return a string that describes the kind of error specified in the
116128 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
116129 ** function.
116130 */
116131 SQLITE_API const char *sqlite3_errstr(int rc){
116132   return sqlite3ErrStr(rc);
116133 }
116134
116135 /*
116136 ** Create a new collating function for database "db".  The name is zName
116137 ** and the encoding is enc.
116138 */
116139 static int createCollation(
116140   sqlite3* db,
116141   const char *zName,
116142   u8 enc,
116143   void* pCtx,
116144   int(*xCompare)(void*,int,const void*,int,const void*),
116145   void(*xDel)(void*)
116146 ){
116147   CollSeq *pColl;
116148   int enc2;
116149   int nName = sqlite3Strlen30(zName);
116150
116151   assert( sqlite3_mutex_held(db->mutex) );
116152
116153   /* If SQLITE_UTF16 is specified as the encoding type, transform this
116154   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
116155   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
116156   */
116157   enc2 = enc;
116158   testcase( enc2==SQLITE_UTF16 );
116159   testcase( enc2==SQLITE_UTF16_ALIGNED );
116160   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
116161     enc2 = SQLITE_UTF16NATIVE;
116162   }
116163   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
116164     return SQLITE_MISUSE_BKPT;
116165   }
116166
116167   /* Check if this call is removing or replacing an existing collation
116168   ** sequence. If so, and there are active VMs, return busy. If there
116169   ** are no active VMs, invalidate any pre-compiled statements.
116170   */
116171   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
116172   if( pColl && pColl->xCmp ){
116173     if( db->activeVdbeCnt ){
116174       sqlite3Error(db, SQLITE_BUSY,
116175         "unable to delete/modify collation sequence due to active statements");
116176       return SQLITE_BUSY;
116177     }
116178     sqlite3ExpirePreparedStatements(db);
116179
116180     /* If collation sequence pColl was created directly by a call to
116181     ** sqlite3_create_collation, and not generated by synthCollSeq(),
116182     ** then any copies made by synthCollSeq() need to be invalidated.
116183     ** Also, collation destructor - CollSeq.xDel() - function may need
116184     ** to be called.
116185     */
116186     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
116187       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
116188       int j;
116189       for(j=0; j<3; j++){
116190         CollSeq *p = &aColl[j];
116191         if( p->enc==pColl->enc ){
116192           if( p->xDel ){
116193             p->xDel(p->pUser);
116194           }
116195           p->xCmp = 0;
116196         }
116197       }
116198     }
116199   }
116200
116201   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
116202   if( pColl==0 ) return SQLITE_NOMEM;
116203   pColl->xCmp = xCompare;
116204   pColl->pUser = pCtx;
116205   pColl->xDel = xDel;
116206   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
116207   sqlite3Error(db, SQLITE_OK, 0);
116208   return SQLITE_OK;
116209 }
116210
116211
116212 /*
116213 ** This array defines hard upper bounds on limit values.  The
116214 ** initializer must be kept in sync with the SQLITE_LIMIT_*
116215 ** #defines in sqlite3.h.
116216 */
116217 static const int aHardLimit[] = {
116218   SQLITE_MAX_LENGTH,
116219   SQLITE_MAX_SQL_LENGTH,
116220   SQLITE_MAX_COLUMN,
116221   SQLITE_MAX_EXPR_DEPTH,
116222   SQLITE_MAX_COMPOUND_SELECT,
116223   SQLITE_MAX_VDBE_OP,
116224   SQLITE_MAX_FUNCTION_ARG,
116225   SQLITE_MAX_ATTACHED,
116226   SQLITE_MAX_LIKE_PATTERN_LENGTH,
116227   SQLITE_MAX_VARIABLE_NUMBER,
116228   SQLITE_MAX_TRIGGER_DEPTH,
116229 };
116230
116231 /*
116232 ** Make sure the hard limits are set to reasonable values
116233 */
116234 #if SQLITE_MAX_LENGTH<100
116235 # error SQLITE_MAX_LENGTH must be at least 100
116236 #endif
116237 #if SQLITE_MAX_SQL_LENGTH<100
116238 # error SQLITE_MAX_SQL_LENGTH must be at least 100
116239 #endif
116240 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
116241 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
116242 #endif
116243 #if SQLITE_MAX_COMPOUND_SELECT<2
116244 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
116245 #endif
116246 #if SQLITE_MAX_VDBE_OP<40
116247 # error SQLITE_MAX_VDBE_OP must be at least 40
116248 #endif
116249 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
116250 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
116251 #endif
116252 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
116253 # error SQLITE_MAX_ATTACHED must be between 0 and 62
116254 #endif
116255 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
116256 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
116257 #endif
116258 #if SQLITE_MAX_COLUMN>32767
116259 # error SQLITE_MAX_COLUMN must not exceed 32767
116260 #endif
116261 #if SQLITE_MAX_TRIGGER_DEPTH<1
116262 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
116263 #endif
116264
116265
116266 /*
116267 ** Change the value of a limit.  Report the old value.
116268 ** If an invalid limit index is supplied, report -1.
116269 ** Make no changes but still report the old value if the
116270 ** new limit is negative.
116271 **
116272 ** A new lower limit does not shrink existing constructs.
116273 ** It merely prevents new constructs that exceed the limit
116274 ** from forming.
116275 */
116276 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
116277   int oldLimit;
116278
116279
116280   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
116281   ** there is a hard upper bound set at compile-time by a C preprocessor
116282   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
116283   ** "_MAX_".)
116284   */
116285   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
116286   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
116287   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
116288   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
116289   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
116290   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
116291   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
116292   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
116293   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
116294                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
116295   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
116296   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
116297   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
116298
116299
116300   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
116301     return -1;
116302   }
116303   oldLimit = db->aLimit[limitId];
116304   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
116305     if( newLimit>aHardLimit[limitId] ){
116306       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
116307     }
116308     db->aLimit[limitId] = newLimit;
116309   }
116310   return oldLimit;                     /* IMP: R-53341-35419 */
116311 }
116312
116313 /*
116314 ** This function is used to parse both URIs and non-URI filenames passed by the
116315 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
116316 ** URIs specified as part of ATTACH statements.
116317 **
116318 ** The first argument to this function is the name of the VFS to use (or
116319 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
116320 ** query parameter. The second argument contains the URI (or non-URI filename)
116321 ** itself. When this function is called the *pFlags variable should contain
116322 ** the default flags to open the database handle with. The value stored in
116323 ** *pFlags may be updated before returning if the URI filename contains
116324 ** "cache=xxx" or "mode=xxx" query parameters.
116325 **
116326 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
116327 ** the VFS that should be used to open the database file. *pzFile is set to
116328 ** point to a buffer containing the name of the file to open. It is the
116329 ** responsibility of the caller to eventually call sqlite3_free() to release
116330 ** this buffer.
116331 **
116332 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
116333 ** may be set to point to a buffer containing an English language error
116334 ** message. It is the responsibility of the caller to eventually release
116335 ** this buffer by calling sqlite3_free().
116336 */
116337 SQLITE_PRIVATE int sqlite3ParseUri(
116338   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
116339   const char *zUri,               /* Nul-terminated URI to parse */
116340   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
116341   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
116342   char **pzFile,                  /* OUT: Filename component of URI */
116343   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
116344 ){
116345   int rc = SQLITE_OK;
116346   unsigned int flags = *pFlags;
116347   const char *zVfs = zDefaultVfs;
116348   char *zFile;
116349   char c;
116350   int nUri = sqlite3Strlen30(zUri);
116351
116352   assert( *pzErrMsg==0 );
116353
116354   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
116355    && nUri>=5 && memcmp(zUri, "file:", 5)==0
116356   ){
116357     char *zOpt;
116358     int eState;                   /* Parser state when parsing URI */
116359     int iIn;                      /* Input character index */
116360     int iOut = 0;                 /* Output character index */
116361     int nByte = nUri+2;           /* Bytes of space to allocate */
116362
116363     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
116364     ** method that there may be extra parameters following the file-name.  */
116365     flags |= SQLITE_OPEN_URI;
116366
116367     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
116368     zFile = sqlite3_malloc(nByte);
116369     if( !zFile ) return SQLITE_NOMEM;
116370
116371     /* Discard the scheme and authority segments of the URI. */
116372     if( zUri[5]=='/' && zUri[6]=='/' ){
116373       iIn = 7;
116374       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
116375
116376       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
116377         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
116378             iIn-7, &zUri[7]);
116379         rc = SQLITE_ERROR;
116380         goto parse_uri_out;
116381       }
116382     }else{
116383       iIn = 5;
116384     }
116385
116386     /* Copy the filename and any query parameters into the zFile buffer.
116387     ** Decode %HH escape codes along the way.
116388     **
116389     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
116390     ** on the parsing context. As follows:
116391     **
116392     **   0: Parsing file-name.
116393     **   1: Parsing name section of a name=value query parameter.
116394     **   2: Parsing value section of a name=value query parameter.
116395     */
116396     eState = 0;
116397     while( (c = zUri[iIn])!=0 && c!='#' ){
116398       iIn++;
116399       if( c=='%'
116400        && sqlite3Isxdigit(zUri[iIn])
116401        && sqlite3Isxdigit(zUri[iIn+1])
116402       ){
116403         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
116404         octet += sqlite3HexToInt(zUri[iIn++]);
116405
116406         assert( octet>=0 && octet<256 );
116407         if( octet==0 ){
116408           /* This branch is taken when "%00" appears within the URI. In this
116409           ** case we ignore all text in the remainder of the path, name or
116410           ** value currently being parsed. So ignore the current character
116411           ** and skip to the next "?", "=" or "&", as appropriate. */
116412           while( (c = zUri[iIn])!=0 && c!='#'
116413               && (eState!=0 || c!='?')
116414               && (eState!=1 || (c!='=' && c!='&'))
116415               && (eState!=2 || c!='&')
116416           ){
116417             iIn++;
116418           }
116419           continue;
116420         }
116421         c = octet;
116422       }else if( eState==1 && (c=='&' || c=='=') ){
116423         if( zFile[iOut-1]==0 ){
116424           /* An empty option name. Ignore this option altogether. */
116425           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
116426           continue;
116427         }
116428         if( c=='&' ){
116429           zFile[iOut++] = '\0';
116430         }else{
116431           eState = 2;
116432         }
116433         c = 0;
116434       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
116435         c = 0;
116436         eState = 1;
116437       }
116438       zFile[iOut++] = c;
116439     }
116440     if( eState==1 ) zFile[iOut++] = '\0';
116441     zFile[iOut++] = '\0';
116442     zFile[iOut++] = '\0';
116443
116444     /* Check if there were any options specified that should be interpreted
116445     ** here. Options that are interpreted here include "vfs" and those that
116446     ** correspond to flags that may be passed to the sqlite3_open_v2()
116447     ** method. */
116448     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
116449     while( zOpt[0] ){
116450       int nOpt = sqlite3Strlen30(zOpt);
116451       char *zVal = &zOpt[nOpt+1];
116452       int nVal = sqlite3Strlen30(zVal);
116453
116454       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
116455         zVfs = zVal;
116456       }else{
116457         struct OpenMode {
116458           const char *z;
116459           int mode;
116460         } *aMode = 0;
116461         char *zModeType = 0;
116462         int mask = 0;
116463         int limit = 0;
116464
116465         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
116466           static struct OpenMode aCacheMode[] = {
116467             { "shared",  SQLITE_OPEN_SHAREDCACHE },
116468             { "private", SQLITE_OPEN_PRIVATECACHE },
116469             { 0, 0 }
116470           };
116471
116472           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
116473           aMode = aCacheMode;
116474           limit = mask;
116475           zModeType = "cache";
116476         }
116477         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
116478           static struct OpenMode aOpenMode[] = {
116479             { "ro",  SQLITE_OPEN_READONLY },
116480             { "rw",  SQLITE_OPEN_READWRITE },
116481             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
116482             { "memory", SQLITE_OPEN_MEMORY },
116483             { 0, 0 }
116484           };
116485
116486           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
116487                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
116488           aMode = aOpenMode;
116489           limit = mask & flags;
116490           zModeType = "access";
116491         }
116492
116493         if( aMode ){
116494           int i;
116495           int mode = 0;
116496           for(i=0; aMode[i].z; i++){
116497             const char *z = aMode[i].z;
116498             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
116499               mode = aMode[i].mode;
116500               break;
116501             }
116502           }
116503           if( mode==0 ){
116504             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
116505             rc = SQLITE_ERROR;
116506             goto parse_uri_out;
116507           }
116508           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
116509             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
116510                                         zModeType, zVal);
116511             rc = SQLITE_PERM;
116512             goto parse_uri_out;
116513           }
116514           flags = (flags & ~mask) | mode;
116515         }
116516       }
116517
116518       zOpt = &zVal[nVal+1];
116519     }
116520
116521   }else{
116522     zFile = sqlite3_malloc(nUri+2);
116523     if( !zFile ) return SQLITE_NOMEM;
116524     memcpy(zFile, zUri, nUri);
116525     zFile[nUri] = '\0';
116526     zFile[nUri+1] = '\0';
116527     flags &= ~SQLITE_OPEN_URI;
116528   }
116529
116530   *ppVfs = sqlite3_vfs_find(zVfs);
116531   if( *ppVfs==0 ){
116532     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
116533     rc = SQLITE_ERROR;
116534   }
116535  parse_uri_out:
116536   if( rc!=SQLITE_OK ){
116537     sqlite3_free(zFile);
116538     zFile = 0;
116539   }
116540   *pFlags = flags;
116541   *pzFile = zFile;
116542   return rc;
116543 }
116544
116545
116546 /*
116547 ** This routine does the work of opening a database on behalf of
116548 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
116549 ** is UTF-8 encoded.
116550 */
116551 static int openDatabase(
116552   const char *zFilename, /* Database filename UTF-8 encoded */
116553   sqlite3 **ppDb,        /* OUT: Returned database handle */
116554   unsigned int flags,    /* Operational flags */
116555   const char *zVfs       /* Name of the VFS to use */
116556 ){
116557   sqlite3 *db;                    /* Store allocated handle here */
116558   int rc;                         /* Return code */
116559   int isThreadsafe;               /* True for threadsafe connections */
116560   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
116561   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
116562
116563   *ppDb = 0;
116564 #ifndef SQLITE_OMIT_AUTOINIT
116565   rc = sqlite3_initialize();
116566   if( rc ) return rc;
116567 #endif
116568
116569   /* Only allow sensible combinations of bits in the flags argument.
116570   ** Throw an error if any non-sense combination is used.  If we
116571   ** do not block illegal combinations here, it could trigger
116572   ** assert() statements in deeper layers.  Sensible combinations
116573   ** are:
116574   **
116575   **  1:  SQLITE_OPEN_READONLY
116576   **  2:  SQLITE_OPEN_READWRITE
116577   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
116578   */
116579   assert( SQLITE_OPEN_READONLY  == 0x01 );
116580   assert( SQLITE_OPEN_READWRITE == 0x02 );
116581   assert( SQLITE_OPEN_CREATE    == 0x04 );
116582   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
116583   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
116584   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
116585   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
116586
116587   if( sqlite3GlobalConfig.bCoreMutex==0 ){
116588     isThreadsafe = 0;
116589   }else if( flags & SQLITE_OPEN_NOMUTEX ){
116590     isThreadsafe = 0;
116591   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
116592     isThreadsafe = 1;
116593   }else{
116594     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
116595   }
116596   if( flags & SQLITE_OPEN_PRIVATECACHE ){
116597     flags &= ~SQLITE_OPEN_SHAREDCACHE;
116598   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
116599     flags |= SQLITE_OPEN_SHAREDCACHE;
116600   }
116601
116602   /* Remove harmful bits from the flags parameter
116603   **
116604   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
116605   ** dealt with in the previous code block.  Besides these, the only
116606   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
116607   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
116608   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
116609   ** off all other flags.
116610   */
116611   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
116612                SQLITE_OPEN_EXCLUSIVE |
116613                SQLITE_OPEN_MAIN_DB |
116614                SQLITE_OPEN_TEMP_DB |
116615                SQLITE_OPEN_TRANSIENT_DB |
116616                SQLITE_OPEN_MAIN_JOURNAL |
116617                SQLITE_OPEN_TEMP_JOURNAL |
116618                SQLITE_OPEN_SUBJOURNAL |
116619                SQLITE_OPEN_MASTER_JOURNAL |
116620                SQLITE_OPEN_NOMUTEX |
116621                SQLITE_OPEN_FULLMUTEX |
116622                SQLITE_OPEN_WAL
116623              );
116624
116625   /* Allocate the sqlite data structure */
116626   db = sqlite3MallocZero( sizeof(sqlite3) );
116627   if( db==0 ) goto opendb_out;
116628   if( isThreadsafe ){
116629     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
116630     if( db->mutex==0 ){
116631       sqlite3_free(db);
116632       db = 0;
116633       goto opendb_out;
116634     }
116635   }
116636   sqlite3_mutex_enter(db->mutex);
116637   db->errMask = 0xff;
116638   db->nDb = 2;
116639   db->magic = SQLITE_MAGIC_BUSY;
116640   db->aDb = db->aDbStatic;
116641
116642   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
116643   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
116644   db->autoCommit = 1;
116645   db->nextAutovac = -1;
116646   db->nextPagesize = 0;
116647   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
116648 #if SQLITE_DEFAULT_FILE_FORMAT<4
116649                  | SQLITE_LegacyFileFmt
116650 #endif
116651 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
116652                  | SQLITE_LoadExtension
116653 #endif
116654 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
116655                  | SQLITE_RecTriggers
116656 #endif
116657 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
116658                  | SQLITE_ForeignKeys
116659 #endif
116660       ;
116661   sqlite3HashInit(&db->aCollSeq);
116662 #ifndef SQLITE_OMIT_VIRTUALTABLE
116663   sqlite3HashInit(&db->aModule);
116664 #endif
116665
116666   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
116667   ** and UTF-16, so add a version for each to avoid any unnecessary
116668   ** conversions. The only error that can occur here is a malloc() failure.
116669   */
116670   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
116671   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
116672   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
116673   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
116674   if( db->mallocFailed ){
116675     goto opendb_out;
116676   }
116677   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
116678   assert( db->pDfltColl!=0 );
116679
116680   /* Also add a UTF-8 case-insensitive collation sequence. */
116681   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
116682
116683   /* Parse the filename/URI argument. */
116684   db->openFlags = flags;
116685   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
116686   if( rc!=SQLITE_OK ){
116687     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
116688     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
116689     sqlite3_free(zErrMsg);
116690     goto opendb_out;
116691   }
116692
116693   /* Open the backend database driver */
116694   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
116695                         flags | SQLITE_OPEN_MAIN_DB);
116696   if( rc!=SQLITE_OK ){
116697     if( rc==SQLITE_IOERR_NOMEM ){
116698       rc = SQLITE_NOMEM;
116699     }
116700     sqlite3Error(db, rc, 0);
116701     goto opendb_out;
116702   }
116703   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
116704   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
116705
116706
116707   /* The default safety_level for the main database is 'full'; for the temp
116708   ** database it is 'NONE'. This matches the pager layer defaults.
116709   */
116710   db->aDb[0].zName = "main";
116711   db->aDb[0].safety_level = 3;
116712   db->aDb[1].zName = "temp";
116713   db->aDb[1].safety_level = 1;
116714
116715   db->magic = SQLITE_MAGIC_OPEN;
116716   if( db->mallocFailed ){
116717     goto opendb_out;
116718   }
116719
116720   /* Register all built-in functions, but do not attempt to read the
116721   ** database schema yet. This is delayed until the first time the database
116722   ** is accessed.
116723   */
116724   sqlite3Error(db, SQLITE_OK, 0);
116725   sqlite3RegisterBuiltinFunctions(db);
116726
116727   /* Load automatic extensions - extensions that have been registered
116728   ** using the sqlite3_automatic_extension() API.
116729   */
116730   rc = sqlite3_errcode(db);
116731   if( rc==SQLITE_OK ){
116732     sqlite3AutoLoadExtensions(db);
116733     rc = sqlite3_errcode(db);
116734     if( rc!=SQLITE_OK ){
116735       goto opendb_out;
116736     }
116737   }
116738
116739 #ifdef SQLITE_ENABLE_FTS1
116740   if( !db->mallocFailed ){
116741     extern int sqlite3Fts1Init(sqlite3*);
116742     rc = sqlite3Fts1Init(db);
116743   }
116744 #endif
116745
116746 #ifdef SQLITE_ENABLE_FTS2
116747   if( !db->mallocFailed && rc==SQLITE_OK ){
116748     extern int sqlite3Fts2Init(sqlite3*);
116749     rc = sqlite3Fts2Init(db);
116750   }
116751 #endif
116752
116753 #ifdef SQLITE_ENABLE_FTS3
116754   if( !db->mallocFailed && rc==SQLITE_OK ){
116755     rc = sqlite3Fts3Init(db);
116756   }
116757 #endif
116758
116759 #ifdef SQLITE_ENABLE_ICU
116760   if( !db->mallocFailed && rc==SQLITE_OK ){
116761     rc = sqlite3IcuInit(db);
116762   }
116763 #endif
116764
116765 #ifdef SQLITE_ENABLE_RTREE
116766   if( !db->mallocFailed && rc==SQLITE_OK){
116767     rc = sqlite3RtreeInit(db);
116768   }
116769 #endif
116770
116771   sqlite3Error(db, rc, 0);
116772
116773   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
116774   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
116775   ** mode.  Doing nothing at all also makes NORMAL the default.
116776   */
116777 #ifdef SQLITE_DEFAULT_LOCKING_MODE
116778   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
116779   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
116780                           SQLITE_DEFAULT_LOCKING_MODE);
116781 #endif
116782
116783   /* Enable the lookaside-malloc subsystem */
116784   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
116785                         sqlite3GlobalConfig.nLookaside);
116786
116787   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
116788
116789 opendb_out:
116790   sqlite3_free(zOpen);
116791   if( db ){
116792     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
116793     sqlite3_mutex_leave(db->mutex);
116794   }
116795   rc = sqlite3_errcode(db);
116796   assert( db!=0 || rc==SQLITE_NOMEM );
116797   if( rc==SQLITE_NOMEM ){
116798     sqlite3_close(db);
116799     db = 0;
116800   }else if( rc!=SQLITE_OK ){
116801     db->magic = SQLITE_MAGIC_SICK;
116802   }
116803   *ppDb = db;
116804 #ifdef SQLITE_ENABLE_SQLLOG
116805   if( sqlite3GlobalConfig.xSqllog ){
116806     /* Opening a db handle. Fourth parameter is passed 0. */
116807     void *pArg = sqlite3GlobalConfig.pSqllogArg;
116808     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
116809   }
116810 #endif
116811   return sqlite3ApiExit(0, rc);
116812 }
116813
116814 /*
116815 ** Open a new database handle.
116816 */
116817 SQLITE_API int sqlite3_open(
116818   const char *zFilename,
116819   sqlite3 **ppDb
116820 ){
116821   return openDatabase(zFilename, ppDb,
116822                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
116823 }
116824 SQLITE_API int sqlite3_open_v2(
116825   const char *filename,   /* Database filename (UTF-8) */
116826   sqlite3 **ppDb,         /* OUT: SQLite db handle */
116827   int flags,              /* Flags */
116828   const char *zVfs        /* Name of VFS module to use */
116829 ){
116830   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
116831 }
116832
116833 #ifndef SQLITE_OMIT_UTF16
116834 /*
116835 ** Open a new database handle.
116836 */
116837 SQLITE_API int sqlite3_open16(
116838   const void *zFilename,
116839   sqlite3 **ppDb
116840 ){
116841   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
116842   sqlite3_value *pVal;
116843   int rc;
116844
116845   assert( zFilename );
116846   assert( ppDb );
116847   *ppDb = 0;
116848 #ifndef SQLITE_OMIT_AUTOINIT
116849   rc = sqlite3_initialize();
116850   if( rc ) return rc;
116851 #endif
116852   pVal = sqlite3ValueNew(0);
116853   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
116854   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
116855   if( zFilename8 ){
116856     rc = openDatabase(zFilename8, ppDb,
116857                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
116858     assert( *ppDb || rc==SQLITE_NOMEM );
116859     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
116860       ENC(*ppDb) = SQLITE_UTF16NATIVE;
116861     }
116862   }else{
116863     rc = SQLITE_NOMEM;
116864   }
116865   sqlite3ValueFree(pVal);
116866
116867   return sqlite3ApiExit(0, rc);
116868 }
116869 #endif /* SQLITE_OMIT_UTF16 */
116870
116871 /*
116872 ** Register a new collation sequence with the database handle db.
116873 */
116874 SQLITE_API int sqlite3_create_collation(
116875   sqlite3* db,
116876   const char *zName,
116877   int enc,
116878   void* pCtx,
116879   int(*xCompare)(void*,int,const void*,int,const void*)
116880 ){
116881   int rc;
116882   sqlite3_mutex_enter(db->mutex);
116883   assert( !db->mallocFailed );
116884   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
116885   rc = sqlite3ApiExit(db, rc);
116886   sqlite3_mutex_leave(db->mutex);
116887   return rc;
116888 }
116889
116890 /*
116891 ** Register a new collation sequence with the database handle db.
116892 */
116893 SQLITE_API int sqlite3_create_collation_v2(
116894   sqlite3* db,
116895   const char *zName,
116896   int enc,
116897   void* pCtx,
116898   int(*xCompare)(void*,int,const void*,int,const void*),
116899   void(*xDel)(void*)
116900 ){
116901   int rc;
116902   sqlite3_mutex_enter(db->mutex);
116903   assert( !db->mallocFailed );
116904   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
116905   rc = sqlite3ApiExit(db, rc);
116906   sqlite3_mutex_leave(db->mutex);
116907   return rc;
116908 }
116909
116910 #ifndef SQLITE_OMIT_UTF16
116911 /*
116912 ** Register a new collation sequence with the database handle db.
116913 */
116914 SQLITE_API int sqlite3_create_collation16(
116915   sqlite3* db,
116916   const void *zName,
116917   int enc,
116918   void* pCtx,
116919   int(*xCompare)(void*,int,const void*,int,const void*)
116920 ){
116921   int rc = SQLITE_OK;
116922   char *zName8;
116923   sqlite3_mutex_enter(db->mutex);
116924   assert( !db->mallocFailed );
116925   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
116926   if( zName8 ){
116927     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
116928     sqlite3DbFree(db, zName8);
116929   }
116930   rc = sqlite3ApiExit(db, rc);
116931   sqlite3_mutex_leave(db->mutex);
116932   return rc;
116933 }
116934 #endif /* SQLITE_OMIT_UTF16 */
116935
116936 /*
116937 ** Register a collation sequence factory callback with the database handle
116938 ** db. Replace any previously installed collation sequence factory.
116939 */
116940 SQLITE_API int sqlite3_collation_needed(
116941   sqlite3 *db,
116942   void *pCollNeededArg,
116943   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
116944 ){
116945   sqlite3_mutex_enter(db->mutex);
116946   db->xCollNeeded = xCollNeeded;
116947   db->xCollNeeded16 = 0;
116948   db->pCollNeededArg = pCollNeededArg;
116949   sqlite3_mutex_leave(db->mutex);
116950   return SQLITE_OK;
116951 }
116952
116953 #ifndef SQLITE_OMIT_UTF16
116954 /*
116955 ** Register a collation sequence factory callback with the database handle
116956 ** db. Replace any previously installed collation sequence factory.
116957 */
116958 SQLITE_API int sqlite3_collation_needed16(
116959   sqlite3 *db,
116960   void *pCollNeededArg,
116961   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
116962 ){
116963   sqlite3_mutex_enter(db->mutex);
116964   db->xCollNeeded = 0;
116965   db->xCollNeeded16 = xCollNeeded16;
116966   db->pCollNeededArg = pCollNeededArg;
116967   sqlite3_mutex_leave(db->mutex);
116968   return SQLITE_OK;
116969 }
116970 #endif /* SQLITE_OMIT_UTF16 */
116971
116972 #ifndef SQLITE_OMIT_DEPRECATED
116973 /*
116974 ** This function is now an anachronism. It used to be used to recover from a
116975 ** malloc() failure, but SQLite now does this automatically.
116976 */
116977 SQLITE_API int sqlite3_global_recover(void){
116978   return SQLITE_OK;
116979 }
116980 #endif
116981
116982 /*
116983 ** Test to see whether or not the database connection is in autocommit
116984 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
116985 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
116986 ** by the next COMMIT or ROLLBACK.
116987 **
116988 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
116989 */
116990 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
116991   return db->autoCommit;
116992 }
116993
116994 /*
116995 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
116996 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
116997 ** constants.  They server two purposes:
116998 **
116999 **   1.  Serve as a convenient place to set a breakpoint in a debugger
117000 **       to detect when version error conditions occurs.
117001 **
117002 **   2.  Invoke sqlite3_log() to provide the source code location where
117003 **       a low-level error is first detected.
117004 */
117005 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
117006   testcase( sqlite3GlobalConfig.xLog!=0 );
117007   sqlite3_log(SQLITE_CORRUPT,
117008               "database corruption at line %d of [%.10s]",
117009               lineno, 20+sqlite3_sourceid());
117010   return SQLITE_CORRUPT;
117011 }
117012 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
117013   testcase( sqlite3GlobalConfig.xLog!=0 );
117014   sqlite3_log(SQLITE_MISUSE,
117015               "misuse at line %d of [%.10s]",
117016               lineno, 20+sqlite3_sourceid());
117017   return SQLITE_MISUSE;
117018 }
117019 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
117020   testcase( sqlite3GlobalConfig.xLog!=0 );
117021   sqlite3_log(SQLITE_CANTOPEN,
117022               "cannot open file at line %d of [%.10s]",
117023               lineno, 20+sqlite3_sourceid());
117024   return SQLITE_CANTOPEN;
117025 }
117026
117027
117028 #ifndef SQLITE_OMIT_DEPRECATED
117029 /*
117030 ** This is a convenience routine that makes sure that all thread-specific
117031 ** data for this thread has been deallocated.
117032 **
117033 ** SQLite no longer uses thread-specific data so this routine is now a
117034 ** no-op.  It is retained for historical compatibility.
117035 */
117036 SQLITE_API void sqlite3_thread_cleanup(void){
117037 }
117038 #endif
117039
117040 /*
117041 ** Return meta information about a specific column of a database table.
117042 ** See comment in sqlite3.h (sqlite.h.in) for details.
117043 */
117044 #ifdef SQLITE_ENABLE_COLUMN_METADATA
117045 SQLITE_API int sqlite3_table_column_metadata(
117046   sqlite3 *db,                /* Connection handle */
117047   const char *zDbName,        /* Database name or NULL */
117048   const char *zTableName,     /* Table name */
117049   const char *zColumnName,    /* Column name */
117050   char const **pzDataType,    /* OUTPUT: Declared data type */
117051   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
117052   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
117053   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
117054   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
117055 ){
117056   int rc;
117057   char *zErrMsg = 0;
117058   Table *pTab = 0;
117059   Column *pCol = 0;
117060   int iCol;
117061
117062   char const *zDataType = 0;
117063   char const *zCollSeq = 0;
117064   int notnull = 0;
117065   int primarykey = 0;
117066   int autoinc = 0;
117067
117068   /* Ensure the database schema has been loaded */
117069   sqlite3_mutex_enter(db->mutex);
117070   sqlite3BtreeEnterAll(db);
117071   rc = sqlite3Init(db, &zErrMsg);
117072   if( SQLITE_OK!=rc ){
117073     goto error_out;
117074   }
117075
117076   /* Locate the table in question */
117077   pTab = sqlite3FindTable(db, zTableName, zDbName);
117078   if( !pTab || pTab->pSelect ){
117079     pTab = 0;
117080     goto error_out;
117081   }
117082
117083   /* Find the column for which info is requested */
117084   if( sqlite3IsRowid(zColumnName) ){
117085     iCol = pTab->iPKey;
117086     if( iCol>=0 ){
117087       pCol = &pTab->aCol[iCol];
117088     }
117089   }else{
117090     for(iCol=0; iCol<pTab->nCol; iCol++){
117091       pCol = &pTab->aCol[iCol];
117092       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
117093         break;
117094       }
117095     }
117096     if( iCol==pTab->nCol ){
117097       pTab = 0;
117098       goto error_out;
117099     }
117100   }
117101
117102   /* The following block stores the meta information that will be returned
117103   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
117104   ** and autoinc. At this point there are two possibilities:
117105   **
117106   **     1. The specified column name was rowid", "oid" or "_rowid_"
117107   **        and there is no explicitly declared IPK column.
117108   **
117109   **     2. The table is not a view and the column name identified an
117110   **        explicitly declared column. Copy meta information from *pCol.
117111   */
117112   if( pCol ){
117113     zDataType = pCol->zType;
117114     zCollSeq = pCol->zColl;
117115     notnull = pCol->notNull!=0;
117116     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
117117     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
117118   }else{
117119     zDataType = "INTEGER";
117120     primarykey = 1;
117121   }
117122   if( !zCollSeq ){
117123     zCollSeq = "BINARY";
117124   }
117125
117126 error_out:
117127   sqlite3BtreeLeaveAll(db);
117128
117129   /* Whether the function call succeeded or failed, set the output parameters
117130   ** to whatever their local counterparts contain. If an error did occur,
117131   ** this has the effect of zeroing all output parameters.
117132   */
117133   if( pzDataType ) *pzDataType = zDataType;
117134   if( pzCollSeq ) *pzCollSeq = zCollSeq;
117135   if( pNotNull ) *pNotNull = notnull;
117136   if( pPrimaryKey ) *pPrimaryKey = primarykey;
117137   if( pAutoinc ) *pAutoinc = autoinc;
117138
117139   if( SQLITE_OK==rc && !pTab ){
117140     sqlite3DbFree(db, zErrMsg);
117141     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
117142         zColumnName);
117143     rc = SQLITE_ERROR;
117144   }
117145   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
117146   sqlite3DbFree(db, zErrMsg);
117147   rc = sqlite3ApiExit(db, rc);
117148   sqlite3_mutex_leave(db->mutex);
117149   return rc;
117150 }
117151 #endif
117152
117153 /*
117154 ** Sleep for a little while.  Return the amount of time slept.
117155 */
117156 SQLITE_API int sqlite3_sleep(int ms){
117157   sqlite3_vfs *pVfs;
117158   int rc;
117159   pVfs = sqlite3_vfs_find(0);
117160   if( pVfs==0 ) return 0;
117161
117162   /* This function works in milliseconds, but the underlying OsSleep()
117163   ** API uses microseconds. Hence the 1000's.
117164   */
117165   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
117166   return rc;
117167 }
117168
117169 /*
117170 ** Enable or disable the extended result codes.
117171 */
117172 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
117173   sqlite3_mutex_enter(db->mutex);
117174   db->errMask = onoff ? 0xffffffff : 0xff;
117175   sqlite3_mutex_leave(db->mutex);
117176   return SQLITE_OK;
117177 }
117178
117179 /*
117180 ** Invoke the xFileControl method on a particular database.
117181 */
117182 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
117183   int rc = SQLITE_ERROR;
117184   Btree *pBtree;
117185
117186   sqlite3_mutex_enter(db->mutex);
117187   pBtree = sqlite3DbNameToBtree(db, zDbName);
117188   if( pBtree ){
117189     Pager *pPager;
117190     sqlite3_file *fd;
117191     sqlite3BtreeEnter(pBtree);
117192     pPager = sqlite3BtreePager(pBtree);
117193     assert( pPager!=0 );
117194     fd = sqlite3PagerFile(pPager);
117195     assert( fd!=0 );
117196     if( op==SQLITE_FCNTL_FILE_POINTER ){
117197       *(sqlite3_file**)pArg = fd;
117198       rc = SQLITE_OK;
117199     }else if( fd->pMethods ){
117200       rc = sqlite3OsFileControl(fd, op, pArg);
117201     }else{
117202       rc = SQLITE_NOTFOUND;
117203     }
117204     sqlite3BtreeLeave(pBtree);
117205   }
117206   sqlite3_mutex_leave(db->mutex);
117207   return rc;
117208 }
117209
117210 /*
117211 ** Interface to the testing logic.
117212 */
117213 SQLITE_API int sqlite3_test_control(int op, ...){
117214   int rc = 0;
117215 #ifndef SQLITE_OMIT_BUILTIN_TEST
117216   va_list ap;
117217   va_start(ap, op);
117218   switch( op ){
117219
117220     /*
117221     ** Save the current state of the PRNG.
117222     */
117223     case SQLITE_TESTCTRL_PRNG_SAVE: {
117224       sqlite3PrngSaveState();
117225       break;
117226     }
117227
117228     /*
117229     ** Restore the state of the PRNG to the last state saved using
117230     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
117231     ** this verb acts like PRNG_RESET.
117232     */
117233     case SQLITE_TESTCTRL_PRNG_RESTORE: {
117234       sqlite3PrngRestoreState();
117235       break;
117236     }
117237
117238     /*
117239     ** Reset the PRNG back to its uninitialized state.  The next call
117240     ** to sqlite3_randomness() will reseed the PRNG using a single call
117241     ** to the xRandomness method of the default VFS.
117242     */
117243     case SQLITE_TESTCTRL_PRNG_RESET: {
117244       sqlite3PrngResetState();
117245       break;
117246     }
117247
117248     /*
117249     **  sqlite3_test_control(BITVEC_TEST, size, program)
117250     **
117251     ** Run a test against a Bitvec object of size.  The program argument
117252     ** is an array of integers that defines the test.  Return -1 on a
117253     ** memory allocation error, 0 on success, or non-zero for an error.
117254     ** See the sqlite3BitvecBuiltinTest() for additional information.
117255     */
117256     case SQLITE_TESTCTRL_BITVEC_TEST: {
117257       int sz = va_arg(ap, int);
117258       int *aProg = va_arg(ap, int*);
117259       rc = sqlite3BitvecBuiltinTest(sz, aProg);
117260       break;
117261     }
117262
117263     /*
117264     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
117265     **
117266     ** Register hooks to call to indicate which malloc() failures
117267     ** are benign.
117268     */
117269     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
117270       typedef void (*void_function)(void);
117271       void_function xBenignBegin;
117272       void_function xBenignEnd;
117273       xBenignBegin = va_arg(ap, void_function);
117274       xBenignEnd = va_arg(ap, void_function);
117275       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
117276       break;
117277     }
117278
117279     /*
117280     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
117281     **
117282     ** Set the PENDING byte to the value in the argument, if X>0.
117283     ** Make no changes if X==0.  Return the value of the pending byte
117284     ** as it existing before this routine was called.
117285     **
117286     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
117287     ** an incompatible database file format.  Changing the PENDING byte
117288     ** while any database connection is open results in undefined and
117289     ** dileterious behavior.
117290     */
117291     case SQLITE_TESTCTRL_PENDING_BYTE: {
117292       rc = PENDING_BYTE;
117293 #ifndef SQLITE_OMIT_WSD
117294       {
117295         unsigned int newVal = va_arg(ap, unsigned int);
117296         if( newVal ) sqlite3PendingByte = newVal;
117297       }
117298 #endif
117299       break;
117300     }
117301
117302     /*
117303     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
117304     **
117305     ** This action provides a run-time test to see whether or not
117306     ** assert() was enabled at compile-time.  If X is true and assert()
117307     ** is enabled, then the return value is true.  If X is true and
117308     ** assert() is disabled, then the return value is zero.  If X is
117309     ** false and assert() is enabled, then the assertion fires and the
117310     ** process aborts.  If X is false and assert() is disabled, then the
117311     ** return value is zero.
117312     */
117313     case SQLITE_TESTCTRL_ASSERT: {
117314       volatile int x = 0;
117315       assert( (x = va_arg(ap,int))!=0 );
117316       rc = x;
117317       break;
117318     }
117319
117320
117321     /*
117322     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
117323     **
117324     ** This action provides a run-time test to see how the ALWAYS and
117325     ** NEVER macros were defined at compile-time.
117326     **
117327     ** The return value is ALWAYS(X).
117328     **
117329     ** The recommended test is X==2.  If the return value is 2, that means
117330     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
117331     ** default setting.  If the return value is 1, then ALWAYS() is either
117332     ** hard-coded to true or else it asserts if its argument is false.
117333     ** The first behavior (hard-coded to true) is the case if
117334     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
117335     ** behavior (assert if the argument to ALWAYS() is false) is the case if
117336     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
117337     **
117338     ** The run-time test procedure might look something like this:
117339     **
117340     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
117341     **      // ALWAYS() and NEVER() are no-op pass-through macros
117342     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
117343     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
117344     **    }else{
117345     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
117346     **    }
117347     */
117348     case SQLITE_TESTCTRL_ALWAYS: {
117349       int x = va_arg(ap,int);
117350       rc = ALWAYS(x);
117351       break;
117352     }
117353
117354     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
117355     **
117356     ** Set the nReserve size to N for the main database on the database
117357     ** connection db.
117358     */
117359     case SQLITE_TESTCTRL_RESERVE: {
117360       sqlite3 *db = va_arg(ap, sqlite3*);
117361       int x = va_arg(ap,int);
117362       sqlite3_mutex_enter(db->mutex);
117363       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
117364       sqlite3_mutex_leave(db->mutex);
117365       break;
117366     }
117367
117368     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
117369     **
117370     ** Enable or disable various optimizations for testing purposes.  The
117371     ** argument N is a bitmask of optimizations to be disabled.  For normal
117372     ** operation N should be 0.  The idea is that a test program (like the
117373     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
117374     ** with various optimizations disabled to verify that the same answer
117375     ** is obtained in every case.
117376     */
117377     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
117378       sqlite3 *db = va_arg(ap, sqlite3*);
117379       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
117380       break;
117381     }
117382
117383 #ifdef SQLITE_N_KEYWORD
117384     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
117385     **
117386     ** If zWord is a keyword recognized by the parser, then return the
117387     ** number of keywords.  Or if zWord is not a keyword, return 0.
117388     **
117389     ** This test feature is only available in the amalgamation since
117390     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
117391     ** is built using separate source files.
117392     */
117393     case SQLITE_TESTCTRL_ISKEYWORD: {
117394       const char *zWord = va_arg(ap, const char*);
117395       int n = sqlite3Strlen30(zWord);
117396       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
117397       break;
117398     }
117399 #endif
117400
117401     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
117402     **
117403     ** Pass pFree into sqlite3ScratchFree().
117404     ** If sz>0 then allocate a scratch buffer into pNew.
117405     */
117406     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
117407       void *pFree, **ppNew;
117408       int sz;
117409       sz = va_arg(ap, int);
117410       ppNew = va_arg(ap, void**);
117411       pFree = va_arg(ap, void*);
117412       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
117413       sqlite3ScratchFree(pFree);
117414       break;
117415     }
117416
117417     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
117418     **
117419     ** If parameter onoff is non-zero, configure the wrappers so that all
117420     ** subsequent calls to localtime() and variants fail. If onoff is zero,
117421     ** undo this setting.
117422     */
117423     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
117424       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
117425       break;
117426     }
117427
117428 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
117429     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
117430     **                        sqlite3_stmt*,const char**);
117431     **
117432     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
117433     ** a string that describes the optimized parse tree.  This test-control
117434     ** returns a pointer to that string.
117435     */
117436     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
117437       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
117438       const char **pzRet = va_arg(ap, const char**);
117439       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
117440       break;
117441     }
117442 #endif
117443
117444   }
117445   va_end(ap);
117446 #endif /* SQLITE_OMIT_BUILTIN_TEST */
117447   return rc;
117448 }
117449
117450 /*
117451 ** This is a utility routine, useful to VFS implementations, that checks
117452 ** to see if a database file was a URI that contained a specific query
117453 ** parameter, and if so obtains the value of the query parameter.
117454 **
117455 ** The zFilename argument is the filename pointer passed into the xOpen()
117456 ** method of a VFS implementation.  The zParam argument is the name of the
117457 ** query parameter we seek.  This routine returns the value of the zParam
117458 ** parameter if it exists.  If the parameter does not exist, this routine
117459 ** returns a NULL pointer.
117460 */
117461 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
117462   if( zFilename==0 ) return 0;
117463   zFilename += sqlite3Strlen30(zFilename) + 1;
117464   while( zFilename[0] ){
117465     int x = strcmp(zFilename, zParam);
117466     zFilename += sqlite3Strlen30(zFilename) + 1;
117467     if( x==0 ) return zFilename;
117468     zFilename += sqlite3Strlen30(zFilename) + 1;
117469   }
117470   return 0;
117471 }
117472
117473 /*
117474 ** Return a boolean value for a query parameter.
117475 */
117476 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
117477   const char *z = sqlite3_uri_parameter(zFilename, zParam);
117478   bDflt = bDflt!=0;
117479   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
117480 }
117481
117482 /*
117483 ** Return a 64-bit integer value for a query parameter.
117484 */
117485 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
117486   const char *zFilename,    /* Filename as passed to xOpen */
117487   const char *zParam,       /* URI parameter sought */
117488   sqlite3_int64 bDflt       /* return if parameter is missing */
117489 ){
117490   const char *z = sqlite3_uri_parameter(zFilename, zParam);
117491   sqlite3_int64 v;
117492   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
117493     bDflt = v;
117494   }
117495   return bDflt;
117496 }
117497
117498 /*
117499 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
117500 */
117501 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
117502   int i;
117503   for(i=0; i<db->nDb; i++){
117504     if( db->aDb[i].pBt
117505      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
117506     ){
117507       return db->aDb[i].pBt;
117508     }
117509   }
117510   return 0;
117511 }
117512
117513 /*
117514 ** Return the filename of the database associated with a database
117515 ** connection.
117516 */
117517 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
117518   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
117519   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
117520 }
117521
117522 /*
117523 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
117524 ** no such database exists.
117525 */
117526 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
117527   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
117528   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
117529 }
117530
117531 /************** End of main.c ************************************************/
117532 /************** Begin file notify.c ******************************************/
117533 /*
117534 ** 2009 March 3
117535 **
117536 ** The author disclaims copyright to this source code.  In place of
117537 ** a legal notice, here is a blessing:
117538 **
117539 **    May you do good and not evil.
117540 **    May you find forgiveness for yourself and forgive others.
117541 **    May you share freely, never taking more than you give.
117542 **
117543 *************************************************************************
117544 **
117545 ** This file contains the implementation of the sqlite3_unlock_notify()
117546 ** API method and its associated functionality.
117547 */
117548
117549 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
117550 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
117551
117552 /*
117553 ** Public interfaces:
117554 **
117555 **   sqlite3ConnectionBlocked()
117556 **   sqlite3ConnectionUnlocked()
117557 **   sqlite3ConnectionClosed()
117558 **   sqlite3_unlock_notify()
117559 */
117560
117561 #define assertMutexHeld() \
117562   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
117563
117564 /*
117565 ** Head of a linked list of all sqlite3 objects created by this process
117566 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
117567 ** is not NULL. This variable may only accessed while the STATIC_MASTER
117568 ** mutex is held.
117569 */
117570 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
117571
117572 #ifndef NDEBUG
117573 /*
117574 ** This function is a complex assert() that verifies the following
117575 ** properties of the blocked connections list:
117576 **
117577 **   1) Each entry in the list has a non-NULL value for either
117578 **      pUnlockConnection or pBlockingConnection, or both.
117579 **
117580 **   2) All entries in the list that share a common value for
117581 **      xUnlockNotify are grouped together.
117582 **
117583 **   3) If the argument db is not NULL, then none of the entries in the
117584 **      blocked connections list have pUnlockConnection or pBlockingConnection
117585 **      set to db. This is used when closing connection db.
117586 */
117587 static void checkListProperties(sqlite3 *db){
117588   sqlite3 *p;
117589   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
117590     int seen = 0;
117591     sqlite3 *p2;
117592
117593     /* Verify property (1) */
117594     assert( p->pUnlockConnection || p->pBlockingConnection );
117595
117596     /* Verify property (2) */
117597     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
117598       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
117599       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
117600       assert( db==0 || p->pUnlockConnection!=db );
117601       assert( db==0 || p->pBlockingConnection!=db );
117602     }
117603   }
117604 }
117605 #else
117606 # define checkListProperties(x)
117607 #endif
117608
117609 /*
117610 ** Remove connection db from the blocked connections list. If connection
117611 ** db is not currently a part of the list, this function is a no-op.
117612 */
117613 static void removeFromBlockedList(sqlite3 *db){
117614   sqlite3 **pp;
117615   assertMutexHeld();
117616   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
117617     if( *pp==db ){
117618       *pp = (*pp)->pNextBlocked;
117619       break;
117620     }
117621   }
117622 }
117623
117624 /*
117625 ** Add connection db to the blocked connections list. It is assumed
117626 ** that it is not already a part of the list.
117627 */
117628 static void addToBlockedList(sqlite3 *db){
117629   sqlite3 **pp;
117630   assertMutexHeld();
117631   for(
117632     pp=&sqlite3BlockedList;
117633     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
117634     pp=&(*pp)->pNextBlocked
117635   );
117636   db->pNextBlocked = *pp;
117637   *pp = db;
117638 }
117639
117640 /*
117641 ** Obtain the STATIC_MASTER mutex.
117642 */
117643 static void enterMutex(void){
117644   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
117645   checkListProperties(0);
117646 }
117647
117648 /*
117649 ** Release the STATIC_MASTER mutex.
117650 */
117651 static void leaveMutex(void){
117652   assertMutexHeld();
117653   checkListProperties(0);
117654   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
117655 }
117656
117657 /*
117658 ** Register an unlock-notify callback.
117659 **
117660 ** This is called after connection "db" has attempted some operation
117661 ** but has received an SQLITE_LOCKED error because another connection
117662 ** (call it pOther) in the same process was busy using the same shared
117663 ** cache.  pOther is found by looking at db->pBlockingConnection.
117664 **
117665 ** If there is no blocking connection, the callback is invoked immediately,
117666 ** before this routine returns.
117667 **
117668 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
117669 ** a deadlock.
117670 **
117671 ** Otherwise, make arrangements to invoke xNotify when pOther drops
117672 ** its locks.
117673 **
117674 ** Each call to this routine overrides any prior callbacks registered
117675 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
117676 ** cancelled.
117677 */
117678 SQLITE_API int sqlite3_unlock_notify(
117679   sqlite3 *db,
117680   void (*xNotify)(void **, int),
117681   void *pArg
117682 ){
117683   int rc = SQLITE_OK;
117684
117685   sqlite3_mutex_enter(db->mutex);
117686   enterMutex();
117687
117688   if( xNotify==0 ){
117689     removeFromBlockedList(db);
117690     db->pBlockingConnection = 0;
117691     db->pUnlockConnection = 0;
117692     db->xUnlockNotify = 0;
117693     db->pUnlockArg = 0;
117694   }else if( 0==db->pBlockingConnection ){
117695     /* The blocking transaction has been concluded. Or there never was a
117696     ** blocking transaction. In either case, invoke the notify callback
117697     ** immediately.
117698     */
117699     xNotify(&pArg, 1);
117700   }else{
117701     sqlite3 *p;
117702
117703     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
117704     if( p ){
117705       rc = SQLITE_LOCKED;              /* Deadlock detected. */
117706     }else{
117707       db->pUnlockConnection = db->pBlockingConnection;
117708       db->xUnlockNotify = xNotify;
117709       db->pUnlockArg = pArg;
117710       removeFromBlockedList(db);
117711       addToBlockedList(db);
117712     }
117713   }
117714
117715   leaveMutex();
117716   assert( !db->mallocFailed );
117717   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
117718   sqlite3_mutex_leave(db->mutex);
117719   return rc;
117720 }
117721
117722 /*
117723 ** This function is called while stepping or preparing a statement
117724 ** associated with connection db. The operation will return SQLITE_LOCKED
117725 ** to the user because it requires a lock that will not be available
117726 ** until connection pBlocker concludes its current transaction.
117727 */
117728 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
117729   enterMutex();
117730   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
117731     addToBlockedList(db);
117732   }
117733   db->pBlockingConnection = pBlocker;
117734   leaveMutex();
117735 }
117736
117737 /*
117738 ** This function is called when
117739 ** the transaction opened by database db has just finished. Locks held
117740 ** by database connection db have been released.
117741 **
117742 ** This function loops through each entry in the blocked connections
117743 ** list and does the following:
117744 **
117745 **   1) If the sqlite3.pBlockingConnection member of a list entry is
117746 **      set to db, then set pBlockingConnection=0.
117747 **
117748 **   2) If the sqlite3.pUnlockConnection member of a list entry is
117749 **      set to db, then invoke the configured unlock-notify callback and
117750 **      set pUnlockConnection=0.
117751 **
117752 **   3) If the two steps above mean that pBlockingConnection==0 and
117753 **      pUnlockConnection==0, remove the entry from the blocked connections
117754 **      list.
117755 */
117756 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
117757   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
117758   int nArg = 0;                            /* Number of entries in aArg[] */
117759   sqlite3 **pp;                            /* Iterator variable */
117760   void **aArg;               /* Arguments to the unlock callback */
117761   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
117762   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
117763
117764   aArg = aStatic;
117765   enterMutex();         /* Enter STATIC_MASTER mutex */
117766
117767   /* This loop runs once for each entry in the blocked-connections list. */
117768   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
117769     sqlite3 *p = *pp;
117770
117771     /* Step 1. */
117772     if( p->pBlockingConnection==db ){
117773       p->pBlockingConnection = 0;
117774     }
117775
117776     /* Step 2. */
117777     if( p->pUnlockConnection==db ){
117778       assert( p->xUnlockNotify );
117779       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
117780         xUnlockNotify(aArg, nArg);
117781         nArg = 0;
117782       }
117783
117784       sqlite3BeginBenignMalloc();
117785       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
117786       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
117787       if( (!aDyn && nArg==(int)ArraySize(aStatic))
117788        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
117789       ){
117790         /* The aArg[] array needs to grow. */
117791         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
117792         if( pNew ){
117793           memcpy(pNew, aArg, nArg*sizeof(void *));
117794           sqlite3_free(aDyn);
117795           aDyn = aArg = pNew;
117796         }else{
117797           /* This occurs when the array of context pointers that need to
117798           ** be passed to the unlock-notify callback is larger than the
117799           ** aStatic[] array allocated on the stack and the attempt to
117800           ** allocate a larger array from the heap has failed.
117801           **
117802           ** This is a difficult situation to handle. Returning an error
117803           ** code to the caller is insufficient, as even if an error code
117804           ** is returned the transaction on connection db will still be
117805           ** closed and the unlock-notify callbacks on blocked connections
117806           ** will go unissued. This might cause the application to wait
117807           ** indefinitely for an unlock-notify callback that will never
117808           ** arrive.
117809           **
117810           ** Instead, invoke the unlock-notify callback with the context
117811           ** array already accumulated. We can then clear the array and
117812           ** begin accumulating any further context pointers without
117813           ** requiring any dynamic allocation. This is sub-optimal because
117814           ** it means that instead of one callback with a large array of
117815           ** context pointers the application will receive two or more
117816           ** callbacks with smaller arrays of context pointers, which will
117817           ** reduce the applications ability to prioritize multiple
117818           ** connections. But it is the best that can be done under the
117819           ** circumstances.
117820           */
117821           xUnlockNotify(aArg, nArg);
117822           nArg = 0;
117823         }
117824       }
117825       sqlite3EndBenignMalloc();
117826
117827       aArg[nArg++] = p->pUnlockArg;
117828       xUnlockNotify = p->xUnlockNotify;
117829       p->pUnlockConnection = 0;
117830       p->xUnlockNotify = 0;
117831       p->pUnlockArg = 0;
117832     }
117833
117834     /* Step 3. */
117835     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
117836       /* Remove connection p from the blocked connections list. */
117837       *pp = p->pNextBlocked;
117838       p->pNextBlocked = 0;
117839     }else{
117840       pp = &p->pNextBlocked;
117841     }
117842   }
117843
117844   if( nArg!=0 ){
117845     xUnlockNotify(aArg, nArg);
117846   }
117847   sqlite3_free(aDyn);
117848   leaveMutex();         /* Leave STATIC_MASTER mutex */
117849 }
117850
117851 /*
117852 ** This is called when the database connection passed as an argument is
117853 ** being closed. The connection is removed from the blocked list.
117854 */
117855 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
117856   sqlite3ConnectionUnlocked(db);
117857   enterMutex();
117858   removeFromBlockedList(db);
117859   checkListProperties(db);
117860   leaveMutex();
117861 }
117862 #endif
117863
117864 /************** End of notify.c **********************************************/
117865 /************** Begin file fts3.c ********************************************/
117866 /*
117867 ** 2006 Oct 10
117868 **
117869 ** The author disclaims copyright to this source code.  In place of
117870 ** a legal notice, here is a blessing:
117871 **
117872 **    May you do good and not evil.
117873 **    May you find forgiveness for yourself and forgive others.
117874 **    May you share freely, never taking more than you give.
117875 **
117876 ******************************************************************************
117877 **
117878 ** This is an SQLite module implementing full-text search.
117879 */
117880
117881 /*
117882 ** The code in this file is only compiled if:
117883 **
117884 **     * The FTS3 module is being built as an extension
117885 **       (in which case SQLITE_CORE is not defined), or
117886 **
117887 **     * The FTS3 module is being built into the core of
117888 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
117889 */
117890
117891 /* The full-text index is stored in a series of b+tree (-like)
117892 ** structures called segments which map terms to doclists.  The
117893 ** structures are like b+trees in layout, but are constructed from the
117894 ** bottom up in optimal fashion and are not updatable.  Since trees
117895 ** are built from the bottom up, things will be described from the
117896 ** bottom up.
117897 **
117898 **
117899 **** Varints ****
117900 ** The basic unit of encoding is a variable-length integer called a
117901 ** varint.  We encode variable-length integers in little-endian order
117902 ** using seven bits * per byte as follows:
117903 **
117904 ** KEY:
117905 **         A = 0xxxxxxx    7 bits of data and one flag bit
117906 **         B = 1xxxxxxx    7 bits of data and one flag bit
117907 **
117908 **  7 bits - A
117909 ** 14 bits - BA
117910 ** 21 bits - BBA
117911 ** and so on.
117912 **
117913 ** This is similar in concept to how sqlite encodes "varints" but
117914 ** the encoding is not the same.  SQLite varints are big-endian
117915 ** are are limited to 9 bytes in length whereas FTS3 varints are
117916 ** little-endian and can be up to 10 bytes in length (in theory).
117917 **
117918 ** Example encodings:
117919 **
117920 **     1:    0x01
117921 **   127:    0x7f
117922 **   128:    0x81 0x00
117923 **
117924 **
117925 **** Document lists ****
117926 ** A doclist (document list) holds a docid-sorted list of hits for a
117927 ** given term.  Doclists hold docids and associated token positions.
117928 ** A docid is the unique integer identifier for a single document.
117929 ** A position is the index of a word within the document.  The first
117930 ** word of the document has a position of 0.
117931 **
117932 ** FTS3 used to optionally store character offsets using a compile-time
117933 ** option.  But that functionality is no longer supported.
117934 **
117935 ** A doclist is stored like this:
117936 **
117937 ** array {
117938 **   varint docid;          (delta from previous doclist)
117939 **   array {                (position list for column 0)
117940 **     varint position;     (2 more than the delta from previous position)
117941 **   }
117942 **   array {
117943 **     varint POS_COLUMN;   (marks start of position list for new column)
117944 **     varint column;       (index of new column)
117945 **     array {
117946 **       varint position;   (2 more than the delta from previous position)
117947 **     }
117948 **   }
117949 **   varint POS_END;        (marks end of positions for this document.
117950 ** }
117951 **
117952 ** Here, array { X } means zero or more occurrences of X, adjacent in
117953 ** memory.  A "position" is an index of a token in the token stream
117954 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
117955 ** in the same logical place as the position element, and act as sentinals
117956 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
117957 ** The positions numbers are not stored literally but rather as two more
117958 ** than the difference from the prior position, or the just the position plus
117959 ** 2 for the first position.  Example:
117960 **
117961 **   label:       A B C D E  F  G H   I  J K
117962 **   value:     123 5 9 1 1 14 35 0 234 72 0
117963 **
117964 ** The 123 value is the first docid.  For column zero in this document
117965 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
117966 ** at D signals the start of a new column; the 1 at E indicates that the
117967 ** new column is column number 1.  There are two positions at 12 and 45
117968 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
117969 ** 234 at I is the delta to next docid (357).  It has one position 70
117970 ** (72-2) and then terminates with the 0 at K.
117971 **
117972 ** A "position-list" is the list of positions for multiple columns for
117973 ** a single docid.  A "column-list" is the set of positions for a single
117974 ** column.  Hence, a position-list consists of one or more column-lists,
117975 ** a document record consists of a docid followed by a position-list and
117976 ** a doclist consists of one or more document records.
117977 **
117978 ** A bare doclist omits the position information, becoming an
117979 ** array of varint-encoded docids.
117980 **
117981 **** Segment leaf nodes ****
117982 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
117983 ** nodes are written using LeafWriter, and read using LeafReader (to
117984 ** iterate through a single leaf node's data) and LeavesReader (to
117985 ** iterate through a segment's entire leaf layer).  Leaf nodes have
117986 ** the format:
117987 **
117988 ** varint iHeight;             (height from leaf level, always 0)
117989 ** varint nTerm;               (length of first term)
117990 ** char pTerm[nTerm];          (content of first term)
117991 ** varint nDoclist;            (length of term's associated doclist)
117992 ** char pDoclist[nDoclist];    (content of doclist)
117993 ** array {
117994 **                             (further terms are delta-encoded)
117995 **   varint nPrefix;           (length of prefix shared with previous term)
117996 **   varint nSuffix;           (length of unshared suffix)
117997 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
117998 **   varint nDoclist;          (length of term's associated doclist)
117999 **   char pDoclist[nDoclist];  (content of doclist)
118000 ** }
118001 **
118002 ** Here, array { X } means zero or more occurrences of X, adjacent in
118003 ** memory.
118004 **
118005 ** Leaf nodes are broken into blocks which are stored contiguously in
118006 ** the %_segments table in sorted order.  This means that when the end
118007 ** of a node is reached, the next term is in the node with the next
118008 ** greater node id.
118009 **
118010 ** New data is spilled to a new leaf node when the current node
118011 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
118012 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
118013 ** node (a leaf node with a single term and doclist).  The goal of
118014 ** these settings is to pack together groups of small doclists while
118015 ** making it efficient to directly access large doclists.  The
118016 ** assumption is that large doclists represent terms which are more
118017 ** likely to be query targets.
118018 **
118019 ** TODO(shess) It may be useful for blocking decisions to be more
118020 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
118021 ** node rather than splitting into 2k and .5k nodes.  My intuition is
118022 ** that this might extend through 2x or 4x the pagesize.
118023 **
118024 **
118025 **** Segment interior nodes ****
118026 ** Segment interior nodes store blockids for subtree nodes and terms
118027 ** to describe what data is stored by the each subtree.  Interior
118028 ** nodes are written using InteriorWriter, and read using
118029 ** InteriorReader.  InteriorWriters are created as needed when
118030 ** SegmentWriter creates new leaf nodes, or when an interior node
118031 ** itself grows too big and must be split.  The format of interior
118032 ** nodes:
118033 **
118034 ** varint iHeight;           (height from leaf level, always >0)
118035 ** varint iBlockid;          (block id of node's leftmost subtree)
118036 ** optional {
118037 **   varint nTerm;           (length of first term)
118038 **   char pTerm[nTerm];      (content of first term)
118039 **   array {
118040 **                                (further terms are delta-encoded)
118041 **     varint nPrefix;            (length of shared prefix with previous term)
118042 **     varint nSuffix;            (length of unshared suffix)
118043 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
118044 **   }
118045 ** }
118046 **
118047 ** Here, optional { X } means an optional element, while array { X }
118048 ** means zero or more occurrences of X, adjacent in memory.
118049 **
118050 ** An interior node encodes n terms separating n+1 subtrees.  The
118051 ** subtree blocks are contiguous, so only the first subtree's blockid
118052 ** is encoded.  The subtree at iBlockid will contain all terms less
118053 ** than the first term encoded (or all terms if no term is encoded).
118054 ** Otherwise, for terms greater than or equal to pTerm[i] but less
118055 ** than pTerm[i+1], the subtree for that term will be rooted at
118056 ** iBlockid+i.  Interior nodes only store enough term data to
118057 ** distinguish adjacent children (if the rightmost term of the left
118058 ** child is "something", and the leftmost term of the right child is
118059 ** "wicked", only "w" is stored).
118060 **
118061 ** New data is spilled to a new interior node at the same height when
118062 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
118063 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
118064 ** interior nodes and making the tree too skinny.  The interior nodes
118065 ** at a given height are naturally tracked by interior nodes at
118066 ** height+1, and so on.
118067 **
118068 **
118069 **** Segment directory ****
118070 ** The segment directory in table %_segdir stores meta-information for
118071 ** merging and deleting segments, and also the root node of the
118072 ** segment's tree.
118073 **
118074 ** The root node is the top node of the segment's tree after encoding
118075 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
118076 ** This could be either a leaf node or an interior node.  If the top
118077 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
118078 ** and a new root interior node is generated (which should always fit
118079 ** within ROOT_MAX because it only needs space for 2 varints, the
118080 ** height and the blockid of the previous root).
118081 **
118082 ** The meta-information in the segment directory is:
118083 **   level               - segment level (see below)
118084 **   idx                 - index within level
118085 **                       - (level,idx uniquely identify a segment)
118086 **   start_block         - first leaf node
118087 **   leaves_end_block    - last leaf node
118088 **   end_block           - last block (including interior nodes)
118089 **   root                - contents of root node
118090 **
118091 ** If the root node is a leaf node, then start_block,
118092 ** leaves_end_block, and end_block are all 0.
118093 **
118094 **
118095 **** Segment merging ****
118096 ** To amortize update costs, segments are grouped into levels and
118097 ** merged in batches.  Each increase in level represents exponentially
118098 ** more documents.
118099 **
118100 ** New documents (actually, document updates) are tokenized and
118101 ** written individually (using LeafWriter) to a level 0 segment, with
118102 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
118103 ** level 0 segments are merged into a single level 1 segment.  Level 1
118104 ** is populated like level 0, and eventually MERGE_COUNT level 1
118105 ** segments are merged to a single level 2 segment (representing
118106 ** MERGE_COUNT^2 updates), and so on.
118107 **
118108 ** A segment merge traverses all segments at a given level in
118109 ** parallel, performing a straightforward sorted merge.  Since segment
118110 ** leaf nodes are written in to the %_segments table in order, this
118111 ** merge traverses the underlying sqlite disk structures efficiently.
118112 ** After the merge, all segment blocks from the merged level are
118113 ** deleted.
118114 **
118115 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
118116 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
118117 ** very similar performance numbers to 16 on insertion, though they're
118118 ** a tiny bit slower (perhaps due to more overhead in merge-time
118119 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
118120 ** 16, 2 about 66% slower than 16.
118121 **
118122 ** At query time, high MERGE_COUNT increases the number of segments
118123 ** which need to be scanned and merged.  For instance, with 100k docs
118124 ** inserted:
118125 **
118126 **    MERGE_COUNT   segments
118127 **       16           25
118128 **        8           12
118129 **        4           10
118130 **        2            6
118131 **
118132 ** This appears to have only a moderate impact on queries for very
118133 ** frequent terms (which are somewhat dominated by segment merge
118134 ** costs), and infrequent and non-existent terms still seem to be fast
118135 ** even with many segments.
118136 **
118137 ** TODO(shess) That said, it would be nice to have a better query-side
118138 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
118139 ** optimizations to things like doclist merging will swing the sweet
118140 ** spot around.
118141 **
118142 **
118143 **
118144 **** Handling of deletions and updates ****
118145 ** Since we're using a segmented structure, with no docid-oriented
118146 ** index into the term index, we clearly cannot simply update the term
118147 ** index when a document is deleted or updated.  For deletions, we
118148 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
118149 ** we simply write the new doclist.  Segment merges overwrite older
118150 ** data for a particular docid with newer data, so deletes or updates
118151 ** will eventually overtake the earlier data and knock it out.  The
118152 ** query logic likewise merges doclists so that newer data knocks out
118153 ** older data.
118154 */
118155
118156 /************** Include fts3Int.h in the middle of fts3.c ********************/
118157 /************** Begin file fts3Int.h *****************************************/
118158 /*
118159 ** 2009 Nov 12
118160 **
118161 ** The author disclaims copyright to this source code.  In place of
118162 ** a legal notice, here is a blessing:
118163 **
118164 **    May you do good and not evil.
118165 **    May you find forgiveness for yourself and forgive others.
118166 **    May you share freely, never taking more than you give.
118167 **
118168 ******************************************************************************
118169 **
118170 */
118171 #ifndef _FTSINT_H
118172 #define _FTSINT_H
118173
118174 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
118175 # define NDEBUG 1
118176 #endif
118177
118178 /*
118179 ** FTS4 is really an extension for FTS3.  It is enabled using the
118180 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
118181 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
118182 */
118183 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
118184 # define SQLITE_ENABLE_FTS3
118185 #endif
118186
118187 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118188
118189 /* If not building as part of the core, include sqlite3ext.h. */
118190 #ifndef SQLITE_CORE
118191 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
118192 #endif
118193
118194 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
118195 /************** Begin file fts3_tokenizer.h **********************************/
118196 /*
118197 ** 2006 July 10
118198 **
118199 ** The author disclaims copyright to this source code.
118200 **
118201 *************************************************************************
118202 ** Defines the interface to tokenizers used by fulltext-search.  There
118203 ** are three basic components:
118204 **
118205 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
118206 ** interface functions.  This is essentially the class structure for
118207 ** tokenizers.
118208 **
118209 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
118210 ** including customization information defined at creation time.
118211 **
118212 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
118213 ** tokens from a particular input.
118214 */
118215 #ifndef _FTS3_TOKENIZER_H_
118216 #define _FTS3_TOKENIZER_H_
118217
118218 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
118219 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
118220 ** we will need a way to register the API consistently.
118221 */
118222
118223 /*
118224 ** Structures used by the tokenizer interface. When a new tokenizer
118225 ** implementation is registered, the caller provides a pointer to
118226 ** an sqlite3_tokenizer_module containing pointers to the callback
118227 ** functions that make up an implementation.
118228 **
118229 ** When an fts3 table is created, it passes any arguments passed to
118230 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
118231 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
118232 ** implementation. The xCreate() function in turn returns an
118233 ** sqlite3_tokenizer structure representing the specific tokenizer to
118234 ** be used for the fts3 table (customized by the tokenizer clause arguments).
118235 **
118236 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
118237 ** method is called. It returns an sqlite3_tokenizer_cursor object
118238 ** that may be used to tokenize a specific input buffer based on
118239 ** the tokenization rules supplied by a specific sqlite3_tokenizer
118240 ** object.
118241 */
118242 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
118243 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
118244 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
118245
118246 struct sqlite3_tokenizer_module {
118247
118248   /*
118249   ** Structure version. Should always be set to 0 or 1.
118250   */
118251   int iVersion;
118252
118253   /*
118254   ** Create a new tokenizer. The values in the argv[] array are the
118255   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
118256   ** TABLE statement that created the fts3 table. For example, if
118257   ** the following SQL is executed:
118258   **
118259   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
118260   **
118261   ** then argc is set to 2, and the argv[] array contains pointers
118262   ** to the strings "arg1" and "arg2".
118263   **
118264   ** This method should return either SQLITE_OK (0), or an SQLite error
118265   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
118266   ** to point at the newly created tokenizer structure. The generic
118267   ** sqlite3_tokenizer.pModule variable should not be initialised by
118268   ** this callback. The caller will do so.
118269   */
118270   int (*xCreate)(
118271     int argc,                           /* Size of argv array */
118272     const char *const*argv,             /* Tokenizer argument strings */
118273     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
118274   );
118275
118276   /*
118277   ** Destroy an existing tokenizer. The fts3 module calls this method
118278   ** exactly once for each successful call to xCreate().
118279   */
118280   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
118281
118282   /*
118283   ** Create a tokenizer cursor to tokenize an input buffer. The caller
118284   ** is responsible for ensuring that the input buffer remains valid
118285   ** until the cursor is closed (using the xClose() method).
118286   */
118287   int (*xOpen)(
118288     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
118289     const char *pInput, int nBytes,      /* Input buffer */
118290     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
118291   );
118292
118293   /*
118294   ** Destroy an existing tokenizer cursor. The fts3 module calls this
118295   ** method exactly once for each successful call to xOpen().
118296   */
118297   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
118298
118299   /*
118300   ** Retrieve the next token from the tokenizer cursor pCursor. This
118301   ** method should either return SQLITE_OK and set the values of the
118302   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
118303   ** the end of the buffer has been reached, or an SQLite error code.
118304   **
118305   ** *ppToken should be set to point at a buffer containing the
118306   ** normalized version of the token (i.e. after any case-folding and/or
118307   ** stemming has been performed). *pnBytes should be set to the length
118308   ** of this buffer in bytes. The input text that generated the token is
118309   ** identified by the byte offsets returned in *piStartOffset and
118310   ** *piEndOffset. *piStartOffset should be set to the index of the first
118311   ** byte of the token in the input buffer. *piEndOffset should be set
118312   ** to the index of the first byte just past the end of the token in
118313   ** the input buffer.
118314   **
118315   ** The buffer *ppToken is set to point at is managed by the tokenizer
118316   ** implementation. It is only required to be valid until the next call
118317   ** to xNext() or xClose().
118318   */
118319   /* TODO(shess) current implementation requires pInput to be
118320   ** nul-terminated.  This should either be fixed, or pInput/nBytes
118321   ** should be converted to zInput.
118322   */
118323   int (*xNext)(
118324     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
118325     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
118326     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
118327     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
118328     int *piPosition      /* OUT: Number of tokens returned before this one */
118329   );
118330
118331   /***********************************************************************
118332   ** Methods below this point are only available if iVersion>=1.
118333   */
118334
118335   /*
118336   ** Configure the language id of a tokenizer cursor.
118337   */
118338   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
118339 };
118340
118341 struct sqlite3_tokenizer {
118342   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
118343   /* Tokenizer implementations will typically add additional fields */
118344 };
118345
118346 struct sqlite3_tokenizer_cursor {
118347   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
118348   /* Tokenizer implementations will typically add additional fields */
118349 };
118350
118351 int fts3_global_term_cnt(int iTerm, int iCol);
118352 int fts3_term_cnt(int iTerm, int iCol);
118353
118354
118355 #endif /* _FTS3_TOKENIZER_H_ */
118356
118357 /************** End of fts3_tokenizer.h **************************************/
118358 /************** Continuing where we left off in fts3Int.h ********************/
118359 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
118360 /************** Begin file fts3_hash.h ***************************************/
118361 /*
118362 ** 2001 September 22
118363 **
118364 ** The author disclaims copyright to this source code.  In place of
118365 ** a legal notice, here is a blessing:
118366 **
118367 **    May you do good and not evil.
118368 **    May you find forgiveness for yourself and forgive others.
118369 **    May you share freely, never taking more than you give.
118370 **
118371 *************************************************************************
118372 ** This is the header file for the generic hash-table implemenation
118373 ** used in SQLite.  We've modified it slightly to serve as a standalone
118374 ** hash table implementation for the full-text indexing module.
118375 **
118376 */
118377 #ifndef _FTS3_HASH_H_
118378 #define _FTS3_HASH_H_
118379
118380 /* Forward declarations of structures. */
118381 typedef struct Fts3Hash Fts3Hash;
118382 typedef struct Fts3HashElem Fts3HashElem;
118383
118384 /* A complete hash table is an instance of the following structure.
118385 ** The internals of this structure are intended to be opaque -- client
118386 ** code should not attempt to access or modify the fields of this structure
118387 ** directly.  Change this structure only by using the routines below.
118388 ** However, many of the "procedures" and "functions" for modifying and
118389 ** accessing this structure are really macros, so we can't really make
118390 ** this structure opaque.
118391 */
118392 struct Fts3Hash {
118393   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
118394   char copyKey;           /* True if copy of key made on insert */
118395   int count;              /* Number of entries in this table */
118396   Fts3HashElem *first;    /* The first element of the array */
118397   int htsize;             /* Number of buckets in the hash table */
118398   struct _fts3ht {        /* the hash table */
118399     int count;               /* Number of entries with this hash */
118400     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
118401   } *ht;
118402 };
118403
118404 /* Each element in the hash table is an instance of the following
118405 ** structure.  All elements are stored on a single doubly-linked list.
118406 **
118407 ** Again, this structure is intended to be opaque, but it can't really
118408 ** be opaque because it is used by macros.
118409 */
118410 struct Fts3HashElem {
118411   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
118412   void *data;                /* Data associated with this element */
118413   void *pKey; int nKey;      /* Key associated with this element */
118414 };
118415
118416 /*
118417 ** There are 2 different modes of operation for a hash table:
118418 **
118419 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
118420 **                           (including the null-terminator, if any).  Case
118421 **                           is respected in comparisons.
118422 **
118423 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
118424 **                           memcmp() is used to compare keys.
118425 **
118426 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
118427 */
118428 #define FTS3_HASH_STRING    1
118429 #define FTS3_HASH_BINARY    2
118430
118431 /*
118432 ** Access routines.  To delete, insert a NULL pointer.
118433 */
118434 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
118435 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
118436 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
118437 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
118438 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
118439
118440 /*
118441 ** Shorthand for the functions above
118442 */
118443 #define fts3HashInit     sqlite3Fts3HashInit
118444 #define fts3HashInsert   sqlite3Fts3HashInsert
118445 #define fts3HashFind     sqlite3Fts3HashFind
118446 #define fts3HashClear    sqlite3Fts3HashClear
118447 #define fts3HashFindElem sqlite3Fts3HashFindElem
118448
118449 /*
118450 ** Macros for looping over all elements of a hash table.  The idiom is
118451 ** like this:
118452 **
118453 **   Fts3Hash h;
118454 **   Fts3HashElem *p;
118455 **   ...
118456 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
118457 **     SomeStructure *pData = fts3HashData(p);
118458 **     // do something with pData
118459 **   }
118460 */
118461 #define fts3HashFirst(H)  ((H)->first)
118462 #define fts3HashNext(E)   ((E)->next)
118463 #define fts3HashData(E)   ((E)->data)
118464 #define fts3HashKey(E)    ((E)->pKey)
118465 #define fts3HashKeysize(E) ((E)->nKey)
118466
118467 /*
118468 ** Number of entries in a hash table
118469 */
118470 #define fts3HashCount(H)  ((H)->count)
118471
118472 #endif /* _FTS3_HASH_H_ */
118473
118474 /************** End of fts3_hash.h *******************************************/
118475 /************** Continuing where we left off in fts3Int.h ********************/
118476
118477 /*
118478 ** This constant controls how often segments are merged. Once there are
118479 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
118480 ** segment of level N+1.
118481 */
118482 #define FTS3_MERGE_COUNT 16
118483
118484 /*
118485 ** This is the maximum amount of data (in bytes) to store in the
118486 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
118487 ** populated as documents are inserted/updated/deleted in a transaction
118488 ** and used to create a new segment when the transaction is committed.
118489 ** However if this limit is reached midway through a transaction, a new
118490 ** segment is created and the hash table cleared immediately.
118491 */
118492 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
118493
118494 /*
118495 ** Macro to return the number of elements in an array. SQLite has a
118496 ** similar macro called ArraySize(). Use a different name to avoid
118497 ** a collision when building an amalgamation with built-in FTS3.
118498 */
118499 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
118500
118501
118502 #ifndef MIN
118503 # define MIN(x,y) ((x)<(y)?(x):(y))
118504 #endif
118505 #ifndef MAX
118506 # define MAX(x,y) ((x)>(y)?(x):(y))
118507 #endif
118508
118509 /*
118510 ** Maximum length of a varint encoded integer. The varint format is different
118511 ** from that used by SQLite, so the maximum length is 10, not 9.
118512 */
118513 #define FTS3_VARINT_MAX 10
118514
118515 /*
118516 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
118517 ** in the document set and zero or more prefix indexes. All indexes are stored
118518 ** as one or more b+-trees in the %_segments and %_segdir tables.
118519 **
118520 ** It is possible to determine which index a b+-tree belongs to based on the
118521 ** value stored in the "%_segdir.level" column. Given this value L, the index
118522 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
118523 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
118524 ** between 1024 and 2047 to index 1, and so on.
118525 **
118526 ** It is considered impossible for an index to use more than 1024 levels. In
118527 ** theory though this may happen, but only after at least
118528 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
118529 */
118530 #define FTS3_SEGDIR_MAXLEVEL      1024
118531 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
118532
118533 /*
118534 ** The testcase() macro is only used by the amalgamation.  If undefined,
118535 ** make it a no-op.
118536 */
118537 #ifndef testcase
118538 # define testcase(X)
118539 #endif
118540
118541 /*
118542 ** Terminator values for position-lists and column-lists.
118543 */
118544 #define POS_COLUMN  (1)     /* Column-list terminator */
118545 #define POS_END     (0)     /* Position-list terminator */
118546
118547 /*
118548 ** This section provides definitions to allow the
118549 ** FTS3 extension to be compiled outside of the
118550 ** amalgamation.
118551 */
118552 #ifndef SQLITE_AMALGAMATION
118553 /*
118554 ** Macros indicating that conditional expressions are always true or
118555 ** false.
118556 */
118557 #ifdef SQLITE_COVERAGE_TEST
118558 # define ALWAYS(x) (1)
118559 # define NEVER(X)  (0)
118560 #else
118561 # define ALWAYS(x) (x)
118562 # define NEVER(x)  (x)
118563 #endif
118564
118565 /*
118566 ** Internal types used by SQLite.
118567 */
118568 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
118569 typedef short int i16;            /* 2-byte (or larger) signed integer */
118570 typedef unsigned int u32;         /* 4-byte unsigned integer */
118571 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
118572 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
118573
118574 /*
118575 ** Macro used to suppress compiler warnings for unused parameters.
118576 */
118577 #define UNUSED_PARAMETER(x) (void)(x)
118578
118579 /*
118580 ** Activate assert() only if SQLITE_TEST is enabled.
118581 */
118582 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
118583 # define NDEBUG 1
118584 #endif
118585
118586 /*
118587 ** The TESTONLY macro is used to enclose variable declarations or
118588 ** other bits of code that are needed to support the arguments
118589 ** within testcase() and assert() macros.
118590 */
118591 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
118592 # define TESTONLY(X)  X
118593 #else
118594 # define TESTONLY(X)
118595 #endif
118596
118597 #endif /* SQLITE_AMALGAMATION */
118598
118599 #ifdef SQLITE_DEBUG
118600 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
118601 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
118602 #else
118603 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
118604 #endif
118605
118606 typedef struct Fts3Table Fts3Table;
118607 typedef struct Fts3Cursor Fts3Cursor;
118608 typedef struct Fts3Expr Fts3Expr;
118609 typedef struct Fts3Phrase Fts3Phrase;
118610 typedef struct Fts3PhraseToken Fts3PhraseToken;
118611
118612 typedef struct Fts3Doclist Fts3Doclist;
118613 typedef struct Fts3SegFilter Fts3SegFilter;
118614 typedef struct Fts3DeferredToken Fts3DeferredToken;
118615 typedef struct Fts3SegReader Fts3SegReader;
118616 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
118617
118618 /*
118619 ** A connection to a fulltext index is an instance of the following
118620 ** structure. The xCreate and xConnect methods create an instance
118621 ** of this structure and xDestroy and xDisconnect free that instance.
118622 ** All other methods receive a pointer to the structure as one of their
118623 ** arguments.
118624 */
118625 struct Fts3Table {
118626   sqlite3_vtab base;              /* Base class used by SQLite core */
118627   sqlite3 *db;                    /* The database connection */
118628   const char *zDb;                /* logical database name */
118629   const char *zName;              /* virtual table name */
118630   int nColumn;                    /* number of named columns in virtual table */
118631   char **azColumn;                /* column names.  malloced */
118632   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
118633   char *zContentTbl;              /* content=xxx option, or NULL */
118634   char *zLanguageid;              /* languageid=xxx option, or NULL */
118635   u8 bAutoincrmerge;              /* True if automerge=1 */
118636   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
118637
118638   /* Precompiled statements used by the implementation. Each of these
118639   ** statements is run and reset within a single virtual table API call.
118640   */
118641   sqlite3_stmt *aStmt[37];
118642
118643   char *zReadExprlist;
118644   char *zWriteExprlist;
118645
118646   int nNodeSize;                  /* Soft limit for node size */
118647   u8 bFts4;                       /* True for FTS4, false for FTS3 */
118648   u8 bHasStat;                    /* True if %_stat table exists */
118649   u8 bHasDocsize;                 /* True if %_docsize table exists */
118650   u8 bDescIdx;                    /* True if doclists are in reverse order */
118651   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
118652   int nPgsz;                      /* Page size for host database */
118653   char *zSegmentsTbl;             /* Name of %_segments table */
118654   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
118655
118656   /*
118657   ** The following array of hash tables is used to buffer pending index
118658   ** updates during transactions. All pending updates buffered at any one
118659   ** time must share a common language-id (see the FTS4 langid= feature).
118660   ** The current language id is stored in variable iPrevLangid.
118661   **
118662   ** A single FTS4 table may have multiple full-text indexes. For each index
118663   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
118664   ** terms that appear in the document set. Each subsequent index in aIndex[]
118665   ** is an index of prefixes of a specific length.
118666   **
118667   ** Variable nPendingData contains an estimate the memory consumed by the
118668   ** pending data structures, including hash table overhead, but not including
118669   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
118670   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
118671   ** recently inserted record.
118672   */
118673   int nIndex;                     /* Size of aIndex[] */
118674   struct Fts3Index {
118675     int nPrefix;                  /* Prefix length (0 for main terms index) */
118676     Fts3Hash hPending;            /* Pending terms table for this index */
118677   } *aIndex;
118678   int nMaxPendingData;            /* Max pending data before flush to disk */
118679   int nPendingData;               /* Current bytes of pending data */
118680   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
118681   int iPrevLangid;                /* Langid of recently inserted document */
118682
118683 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
118684   /* State variables used for validating that the transaction control
118685   ** methods of the virtual table are called at appropriate times.  These
118686   ** values do not contribute to FTS functionality; they are used for
118687   ** verifying the operation of the SQLite core.
118688   */
118689   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
118690   int mxSavepoint;       /* Largest valid xSavepoint integer */
118691 #endif
118692 };
118693
118694 /*
118695 ** When the core wants to read from the virtual table, it creates a
118696 ** virtual table cursor (an instance of the following structure) using
118697 ** the xOpen method. Cursors are destroyed using the xClose method.
118698 */
118699 struct Fts3Cursor {
118700   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
118701   i16 eSearch;                    /* Search strategy (see below) */
118702   u8 isEof;                       /* True if at End Of Results */
118703   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
118704   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
118705   Fts3Expr *pExpr;                /* Parsed MATCH query string */
118706   int iLangid;                    /* Language being queried for */
118707   int nPhrase;                    /* Number of matchable phrases in query */
118708   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
118709   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
118710   char *pNextId;                  /* Pointer into the body of aDoclist */
118711   char *aDoclist;                 /* List of docids for full-text queries */
118712   int nDoclist;                   /* Size of buffer at aDoclist */
118713   u8 bDesc;                       /* True to sort in descending order */
118714   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
118715   int nRowAvg;                    /* Average size of database rows, in pages */
118716   sqlite3_int64 nDoc;             /* Documents in table */
118717
118718   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
118719   u32 *aMatchinfo;                /* Information about most recent match */
118720   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
118721   char *zMatchinfo;               /* Matchinfo specification */
118722 };
118723
118724 #define FTS3_EVAL_FILTER    0
118725 #define FTS3_EVAL_NEXT      1
118726 #define FTS3_EVAL_MATCHINFO 2
118727
118728 /*
118729 ** The Fts3Cursor.eSearch member is always set to one of the following.
118730 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
118731 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
118732 ** of the column to be searched.  For example, in
118733 **
118734 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
118735 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
118736 **
118737 ** Because the LHS of the MATCH operator is 2nd column "b",
118738 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
118739 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
118740 ** indicating that all columns should be searched,
118741 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
118742 */
118743 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
118744 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
118745 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
118746
118747
118748 struct Fts3Doclist {
118749   char *aAll;                    /* Array containing doclist (or NULL) */
118750   int nAll;                      /* Size of a[] in bytes */
118751   char *pNextDocid;              /* Pointer to next docid */
118752
118753   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
118754   int bFreeList;                 /* True if pList should be sqlite3_free()d */
118755   char *pList;                   /* Pointer to position list following iDocid */
118756   int nList;                     /* Length of position list */
118757 };
118758
118759 /*
118760 ** A "phrase" is a sequence of one or more tokens that must match in
118761 ** sequence.  A single token is the base case and the most common case.
118762 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
118763 ** nToken will be the number of tokens in the string.
118764 */
118765 struct Fts3PhraseToken {
118766   char *z;                        /* Text of the token */
118767   int n;                          /* Number of bytes in buffer z */
118768   int isPrefix;                   /* True if token ends with a "*" character */
118769   int bFirst;                     /* True if token must appear at position 0 */
118770
118771   /* Variables above this point are populated when the expression is
118772   ** parsed (by code in fts3_expr.c). Below this point the variables are
118773   ** used when evaluating the expression. */
118774   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
118775   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
118776 };
118777
118778 struct Fts3Phrase {
118779   /* Cache of doclist for this phrase. */
118780   Fts3Doclist doclist;
118781   int bIncr;                 /* True if doclist is loaded incrementally */
118782   int iDoclistToken;
118783
118784   /* Variables below this point are populated by fts3_expr.c when parsing
118785   ** a MATCH expression. Everything above is part of the evaluation phase.
118786   */
118787   int nToken;                /* Number of tokens in the phrase */
118788   int iColumn;               /* Index of column this phrase must match */
118789   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
118790 };
118791
118792 /*
118793 ** A tree of these objects forms the RHS of a MATCH operator.
118794 **
118795 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
118796 ** points to a malloced buffer, size nDoclist bytes, containing the results
118797 ** of this phrase query in FTS3 doclist format. As usual, the initial
118798 ** "Length" field found in doclists stored on disk is omitted from this
118799 ** buffer.
118800 **
118801 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
118802 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
118803 ** where nCol is the number of columns in the queried FTS table. The array
118804 ** is populated as follows:
118805 **
118806 **   aMI[iCol*3 + 0] = Undefined
118807 **   aMI[iCol*3 + 1] = Number of occurrences
118808 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
118809 **
118810 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
118811 ** when the expression node is.
118812 */
118813 struct Fts3Expr {
118814   int eType;                 /* One of the FTSQUERY_XXX values defined below */
118815   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
118816   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
118817   Fts3Expr *pLeft;           /* Left operand */
118818   Fts3Expr *pRight;          /* Right operand */
118819   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
118820
118821   /* The following are used by the fts3_eval.c module. */
118822   sqlite3_int64 iDocid;      /* Current docid */
118823   u8 bEof;                   /* True this expression is at EOF already */
118824   u8 bStart;                 /* True if iDocid is valid */
118825   u8 bDeferred;              /* True if this expression is entirely deferred */
118826
118827   u32 *aMI;
118828 };
118829
118830 /*
118831 ** Candidate values for Fts3Query.eType. Note that the order of the first
118832 ** four values is in order of precedence when parsing expressions. For
118833 ** example, the following:
118834 **
118835 **   "a OR b AND c NOT d NEAR e"
118836 **
118837 ** is equivalent to:
118838 **
118839 **   "a OR (b AND (c NOT (d NEAR e)))"
118840 */
118841 #define FTSQUERY_NEAR   1
118842 #define FTSQUERY_NOT    2
118843 #define FTSQUERY_AND    3
118844 #define FTSQUERY_OR     4
118845 #define FTSQUERY_PHRASE 5
118846
118847
118848 /* fts3_write.c */
118849 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
118850 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
118851 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
118852 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
118853 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
118854   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
118855 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
118856   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
118857 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
118858 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
118859 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
118860 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
118861
118862 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
118863 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
118864
118865 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
118866 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
118867 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
118868 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
118869 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
118870 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
118871 #else
118872 # define sqlite3Fts3FreeDeferredTokens(x)
118873 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
118874 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
118875 # define sqlite3Fts3FreeDeferredDoclists(x)
118876 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
118877 #endif
118878
118879 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
118880 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
118881
118882 /* Special values interpreted by sqlite3SegReaderCursor() */
118883 #define FTS3_SEGCURSOR_PENDING        -1
118884 #define FTS3_SEGCURSOR_ALL            -2
118885
118886 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
118887 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
118888 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
118889
118890 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
118891     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
118892
118893 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
118894 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
118895 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
118896 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
118897 #define FTS3_SEGMENT_PREFIX        0x00000008
118898 #define FTS3_SEGMENT_SCAN          0x00000010
118899 #define FTS3_SEGMENT_FIRST         0x00000020
118900
118901 /* Type passed as 4th argument to SegmentReaderIterate() */
118902 struct Fts3SegFilter {
118903   const char *zTerm;
118904   int nTerm;
118905   int iCol;
118906   int flags;
118907 };
118908
118909 struct Fts3MultiSegReader {
118910   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
118911   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
118912   int nSegment;                   /* Size of apSegment array */
118913   int nAdvance;                   /* How many seg-readers to advance */
118914   Fts3SegFilter *pFilter;         /* Pointer to filter object */
118915   char *aBuffer;                  /* Buffer to merge doclists in */
118916   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
118917
118918   int iColFilter;                 /* If >=0, filter for this column */
118919   int bRestart;
118920
118921   /* Used by fts3.c only. */
118922   int nCost;                      /* Cost of running iterator */
118923   int bLookup;                    /* True if a lookup of a single entry. */
118924
118925   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
118926   char *zTerm;                    /* Pointer to term buffer */
118927   int nTerm;                      /* Size of zTerm in bytes */
118928   char *aDoclist;                 /* Pointer to doclist buffer */
118929   int nDoclist;                   /* Size of aDoclist[] in bytes */
118930 };
118931
118932 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
118933
118934 /* fts3.c */
118935 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
118936 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
118937 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
118938 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
118939 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
118940 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
118941 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
118942 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
118943 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
118944
118945 /* fts3_tokenizer.c */
118946 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
118947 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
118948 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
118949     sqlite3_tokenizer **, char **
118950 );
118951 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
118952
118953 /* fts3_snippet.c */
118954 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
118955 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
118956   const char *, const char *, int, int
118957 );
118958 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
118959
118960 /* fts3_expr.c */
118961 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
118962   char **, int, int, int, const char *, int, Fts3Expr **
118963 );
118964 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
118965 #ifdef SQLITE_TEST
118966 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
118967 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
118968 #endif
118969
118970 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
118971   sqlite3_tokenizer_cursor **
118972 );
118973
118974 /* fts3_aux.c */
118975 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
118976
118977 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
118978
118979 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
118980     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
118981 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
118982     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
118983 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
118984 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
118985 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
118986
118987 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
118988 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
118989 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
118990 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
118991 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
118992 #endif
118993
118994 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
118995 #endif /* _FTSINT_H */
118996
118997 /************** End of fts3Int.h *********************************************/
118998 /************** Continuing where we left off in fts3.c ***********************/
118999 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119000
119001 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
119002 # define SQLITE_CORE 1
119003 #endif
119004
119005 /* #include <assert.h> */
119006 /* #include <stdlib.h> */
119007 /* #include <stddef.h> */
119008 /* #include <stdio.h> */
119009 /* #include <string.h> */
119010 /* #include <stdarg.h> */
119011
119012 #ifndef SQLITE_CORE
119013   SQLITE_EXTENSION_INIT1
119014 #endif
119015
119016 static int fts3EvalNext(Fts3Cursor *pCsr);
119017 static int fts3EvalStart(Fts3Cursor *pCsr);
119018 static int fts3TermSegReaderCursor(
119019     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
119020
119021 /*
119022 ** Write a 64-bit variable-length integer to memory starting at p[0].
119023 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
119024 ** The number of bytes written is returned.
119025 */
119026 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
119027   unsigned char *q = (unsigned char *) p;
119028   sqlite_uint64 vu = v;
119029   do{
119030     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
119031     vu >>= 7;
119032   }while( vu!=0 );
119033   q[-1] &= 0x7f;  /* turn off high bit in final byte */
119034   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
119035   return (int) (q - (unsigned char *)p);
119036 }
119037
119038 /*
119039 ** Read a 64-bit variable-length integer from memory starting at p[0].
119040 ** Return the number of bytes read, or 0 on error.
119041 ** The value is stored in *v.
119042 */
119043 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
119044   const unsigned char *q = (const unsigned char *) p;
119045   sqlite_uint64 x = 0, y = 1;
119046   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
119047     x += y * (*q++ & 0x7f);
119048     y <<= 7;
119049   }
119050   x += y * (*q++);
119051   *v = (sqlite_int64) x;
119052   return (int) (q - (unsigned char *)p);
119053 }
119054
119055 /*
119056 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
119057 ** 32-bit integer before it is returned.
119058 */
119059 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
119060  sqlite_int64 i;
119061  int ret = sqlite3Fts3GetVarint(p, &i);
119062  *pi = (int) i;
119063  return ret;
119064 }
119065
119066 /*
119067 ** Return the number of bytes required to encode v as a varint
119068 */
119069 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
119070   int i = 0;
119071   do{
119072     i++;
119073     v >>= 7;
119074   }while( v!=0 );
119075   return i;
119076 }
119077
119078 /*
119079 ** Convert an SQL-style quoted string into a normal string by removing
119080 ** the quote characters.  The conversion is done in-place.  If the
119081 ** input does not begin with a quote character, then this routine
119082 ** is a no-op.
119083 **
119084 ** Examples:
119085 **
119086 **     "abc"   becomes   abc
119087 **     'xyz'   becomes   xyz
119088 **     [pqr]   becomes   pqr
119089 **     `mno`   becomes   mno
119090 **
119091 */
119092 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
119093   char quote;                     /* Quote character (if any ) */
119094
119095   quote = z[0];
119096   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
119097     int iIn = 1;                  /* Index of next byte to read from input */
119098     int iOut = 0;                 /* Index of next byte to write to output */
119099
119100     /* If the first byte was a '[', then the close-quote character is a ']' */
119101     if( quote=='[' ) quote = ']';
119102
119103     while( ALWAYS(z[iIn]) ){
119104       if( z[iIn]==quote ){
119105         if( z[iIn+1]!=quote ) break;
119106         z[iOut++] = quote;
119107         iIn += 2;
119108       }else{
119109         z[iOut++] = z[iIn++];
119110       }
119111     }
119112     z[iOut] = '\0';
119113   }
119114 }
119115
119116 /*
119117 ** Read a single varint from the doclist at *pp and advance *pp to point
119118 ** to the first byte past the end of the varint.  Add the value of the varint
119119 ** to *pVal.
119120 */
119121 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
119122   sqlite3_int64 iVal;
119123   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
119124   *pVal += iVal;
119125 }
119126
119127 /*
119128 ** When this function is called, *pp points to the first byte following a
119129 ** varint that is part of a doclist (or position-list, or any other list
119130 ** of varints). This function moves *pp to point to the start of that varint,
119131 ** and sets *pVal by the varint value.
119132 **
119133 ** Argument pStart points to the first byte of the doclist that the
119134 ** varint is part of.
119135 */
119136 static void fts3GetReverseVarint(
119137   char **pp,
119138   char *pStart,
119139   sqlite3_int64 *pVal
119140 ){
119141   sqlite3_int64 iVal;
119142   char *p;
119143
119144   /* Pointer p now points at the first byte past the varint we are
119145   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
119146   ** clear on character p[-1]. */
119147   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
119148   p++;
119149   *pp = p;
119150
119151   sqlite3Fts3GetVarint(p, &iVal);
119152   *pVal = iVal;
119153 }
119154
119155 /*
119156 ** The xDisconnect() virtual table method.
119157 */
119158 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
119159   Fts3Table *p = (Fts3Table *)pVtab;
119160   int i;
119161
119162   assert( p->nPendingData==0 );
119163   assert( p->pSegments==0 );
119164
119165   /* Free any prepared statements held */
119166   for(i=0; i<SizeofArray(p->aStmt); i++){
119167     sqlite3_finalize(p->aStmt[i]);
119168   }
119169   sqlite3_free(p->zSegmentsTbl);
119170   sqlite3_free(p->zReadExprlist);
119171   sqlite3_free(p->zWriteExprlist);
119172   sqlite3_free(p->zContentTbl);
119173   sqlite3_free(p->zLanguageid);
119174
119175   /* Invoke the tokenizer destructor to free the tokenizer. */
119176   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
119177
119178   sqlite3_free(p);
119179   return SQLITE_OK;
119180 }
119181
119182 /*
119183 ** Construct one or more SQL statements from the format string given
119184 ** and then evaluate those statements. The success code is written
119185 ** into *pRc.
119186 **
119187 ** If *pRc is initially non-zero then this routine is a no-op.
119188 */
119189 static void fts3DbExec(
119190   int *pRc,              /* Success code */
119191   sqlite3 *db,           /* Database in which to run SQL */
119192   const char *zFormat,   /* Format string for SQL */
119193   ...                    /* Arguments to the format string */
119194 ){
119195   va_list ap;
119196   char *zSql;
119197   if( *pRc ) return;
119198   va_start(ap, zFormat);
119199   zSql = sqlite3_vmprintf(zFormat, ap);
119200   va_end(ap);
119201   if( zSql==0 ){
119202     *pRc = SQLITE_NOMEM;
119203   }else{
119204     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
119205     sqlite3_free(zSql);
119206   }
119207 }
119208
119209 /*
119210 ** The xDestroy() virtual table method.
119211 */
119212 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
119213   Fts3Table *p = (Fts3Table *)pVtab;
119214   int rc = SQLITE_OK;              /* Return code */
119215   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
119216   sqlite3 *db = p->db;             /* Database handle */
119217
119218   /* Drop the shadow tables */
119219   if( p->zContentTbl==0 ){
119220     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
119221   }
119222   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
119223   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
119224   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
119225   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
119226
119227   /* If everything has worked, invoke fts3DisconnectMethod() to free the
119228   ** memory associated with the Fts3Table structure and return SQLITE_OK.
119229   ** Otherwise, return an SQLite error code.
119230   */
119231   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
119232 }
119233
119234
119235 /*
119236 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
119237 ** passed as the first argument. This is done as part of the xConnect()
119238 ** and xCreate() methods.
119239 **
119240 ** If *pRc is non-zero when this function is called, it is a no-op.
119241 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
119242 ** before returning.
119243 */
119244 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
119245   if( *pRc==SQLITE_OK ){
119246     int i;                        /* Iterator variable */
119247     int rc;                       /* Return code */
119248     char *zSql;                   /* SQL statement passed to declare_vtab() */
119249     char *zCols;                  /* List of user defined columns */
119250     const char *zLanguageid;
119251
119252     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
119253     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
119254
119255     /* Create a list of user columns for the virtual table */
119256     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
119257     for(i=1; zCols && i<p->nColumn; i++){
119258       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
119259     }
119260
119261     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
119262     zSql = sqlite3_mprintf(
119263         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
119264         zCols, p->zName, zLanguageid
119265     );
119266     if( !zCols || !zSql ){
119267       rc = SQLITE_NOMEM;
119268     }else{
119269       rc = sqlite3_declare_vtab(p->db, zSql);
119270     }
119271
119272     sqlite3_free(zSql);
119273     sqlite3_free(zCols);
119274     *pRc = rc;
119275   }
119276 }
119277
119278 /*
119279 ** Create the %_stat table if it does not already exist.
119280 */
119281 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
119282   fts3DbExec(pRc, p->db,
119283       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
119284           "(id INTEGER PRIMARY KEY, value BLOB);",
119285       p->zDb, p->zName
119286   );
119287   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
119288 }
119289
119290 /*
119291 ** Create the backing store tables (%_content, %_segments and %_segdir)
119292 ** required by the FTS3 table passed as the only argument. This is done
119293 ** as part of the vtab xCreate() method.
119294 **
119295 ** If the p->bHasDocsize boolean is true (indicating that this is an
119296 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
119297 ** %_stat tables required by FTS4.
119298 */
119299 static int fts3CreateTables(Fts3Table *p){
119300   int rc = SQLITE_OK;             /* Return code */
119301   int i;                          /* Iterator variable */
119302   sqlite3 *db = p->db;            /* The database connection */
119303
119304   if( p->zContentTbl==0 ){
119305     const char *zLanguageid = p->zLanguageid;
119306     char *zContentCols;           /* Columns of %_content table */
119307
119308     /* Create a list of user columns for the content table */
119309     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
119310     for(i=0; zContentCols && i<p->nColumn; i++){
119311       char *z = p->azColumn[i];
119312       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
119313     }
119314     if( zLanguageid && zContentCols ){
119315       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
119316     }
119317     if( zContentCols==0 ) rc = SQLITE_NOMEM;
119318
119319     /* Create the content table */
119320     fts3DbExec(&rc, db,
119321        "CREATE TABLE %Q.'%q_content'(%s)",
119322        p->zDb, p->zName, zContentCols
119323     );
119324     sqlite3_free(zContentCols);
119325   }
119326
119327   /* Create other tables */
119328   fts3DbExec(&rc, db,
119329       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
119330       p->zDb, p->zName
119331   );
119332   fts3DbExec(&rc, db,
119333       "CREATE TABLE %Q.'%q_segdir'("
119334         "level INTEGER,"
119335         "idx INTEGER,"
119336         "start_block INTEGER,"
119337         "leaves_end_block INTEGER,"
119338         "end_block INTEGER,"
119339         "root BLOB,"
119340         "PRIMARY KEY(level, idx)"
119341       ");",
119342       p->zDb, p->zName
119343   );
119344   if( p->bHasDocsize ){
119345     fts3DbExec(&rc, db,
119346         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
119347         p->zDb, p->zName
119348     );
119349   }
119350   assert( p->bHasStat==p->bFts4 );
119351   if( p->bHasStat ){
119352     sqlite3Fts3CreateStatTable(&rc, p);
119353   }
119354   return rc;
119355 }
119356
119357 /*
119358 ** Store the current database page-size in bytes in p->nPgsz.
119359 **
119360 ** If *pRc is non-zero when this function is called, it is a no-op.
119361 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
119362 ** before returning.
119363 */
119364 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
119365   if( *pRc==SQLITE_OK ){
119366     int rc;                       /* Return code */
119367     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
119368     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
119369
119370     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
119371     if( !zSql ){
119372       rc = SQLITE_NOMEM;
119373     }else{
119374       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
119375       if( rc==SQLITE_OK ){
119376         sqlite3_step(pStmt);
119377         p->nPgsz = sqlite3_column_int(pStmt, 0);
119378         rc = sqlite3_finalize(pStmt);
119379       }else if( rc==SQLITE_AUTH ){
119380         p->nPgsz = 1024;
119381         rc = SQLITE_OK;
119382       }
119383     }
119384     assert( p->nPgsz>0 || rc!=SQLITE_OK );
119385     sqlite3_free(zSql);
119386     *pRc = rc;
119387   }
119388 }
119389
119390 /*
119391 ** "Special" FTS4 arguments are column specifications of the following form:
119392 **
119393 **   <key> = <value>
119394 **
119395 ** There may not be whitespace surrounding the "=" character. The <value>
119396 ** term may be quoted, but the <key> may not.
119397 */
119398 static int fts3IsSpecialColumn(
119399   const char *z,
119400   int *pnKey,
119401   char **pzValue
119402 ){
119403   char *zValue;
119404   const char *zCsr = z;
119405
119406   while( *zCsr!='=' ){
119407     if( *zCsr=='\0' ) return 0;
119408     zCsr++;
119409   }
119410
119411   *pnKey = (int)(zCsr-z);
119412   zValue = sqlite3_mprintf("%s", &zCsr[1]);
119413   if( zValue ){
119414     sqlite3Fts3Dequote(zValue);
119415   }
119416   *pzValue = zValue;
119417   return 1;
119418 }
119419
119420 /*
119421 ** Append the output of a printf() style formatting to an existing string.
119422 */
119423 static void fts3Appendf(
119424   int *pRc,                       /* IN/OUT: Error code */
119425   char **pz,                      /* IN/OUT: Pointer to string buffer */
119426   const char *zFormat,            /* Printf format string to append */
119427   ...                             /* Arguments for printf format string */
119428 ){
119429   if( *pRc==SQLITE_OK ){
119430     va_list ap;
119431     char *z;
119432     va_start(ap, zFormat);
119433     z = sqlite3_vmprintf(zFormat, ap);
119434     va_end(ap);
119435     if( z && *pz ){
119436       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
119437       sqlite3_free(z);
119438       z = z2;
119439     }
119440     if( z==0 ) *pRc = SQLITE_NOMEM;
119441     sqlite3_free(*pz);
119442     *pz = z;
119443   }
119444 }
119445
119446 /*
119447 ** Return a copy of input string zInput enclosed in double-quotes (") and
119448 ** with all double quote characters escaped. For example:
119449 **
119450 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
119451 **
119452 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
119453 ** is the callers responsibility to call sqlite3_free() to release this
119454 ** memory.
119455 */
119456 static char *fts3QuoteId(char const *zInput){
119457   int nRet;
119458   char *zRet;
119459   nRet = 2 + (int)strlen(zInput)*2 + 1;
119460   zRet = sqlite3_malloc(nRet);
119461   if( zRet ){
119462     int i;
119463     char *z = zRet;
119464     *(z++) = '"';
119465     for(i=0; zInput[i]; i++){
119466       if( zInput[i]=='"' ) *(z++) = '"';
119467       *(z++) = zInput[i];
119468     }
119469     *(z++) = '"';
119470     *(z++) = '\0';
119471   }
119472   return zRet;
119473 }
119474
119475 /*
119476 ** Return a list of comma separated SQL expressions and a FROM clause that
119477 ** could be used in a SELECT statement such as the following:
119478 **
119479 **     SELECT <list of expressions> FROM %_content AS x ...
119480 **
119481 ** to return the docid, followed by each column of text data in order
119482 ** from left to write. If parameter zFunc is not NULL, then instead of
119483 ** being returned directly each column of text data is passed to an SQL
119484 ** function named zFunc first. For example, if zFunc is "unzip" and the
119485 ** table has the three user-defined columns "a", "b", and "c", the following
119486 ** string is returned:
119487 **
119488 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
119489 **
119490 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
119491 ** is the responsibility of the caller to eventually free it.
119492 **
119493 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
119494 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
119495 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
119496 ** no error occurs, *pRc is left unmodified.
119497 */
119498 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
119499   char *zRet = 0;
119500   char *zFree = 0;
119501   char *zFunction;
119502   int i;
119503
119504   if( p->zContentTbl==0 ){
119505     if( !zFunc ){
119506       zFunction = "";
119507     }else{
119508       zFree = zFunction = fts3QuoteId(zFunc);
119509     }
119510     fts3Appendf(pRc, &zRet, "docid");
119511     for(i=0; i<p->nColumn; i++){
119512       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
119513     }
119514     if( p->zLanguageid ){
119515       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
119516     }
119517     sqlite3_free(zFree);
119518   }else{
119519     fts3Appendf(pRc, &zRet, "rowid");
119520     for(i=0; i<p->nColumn; i++){
119521       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
119522     }
119523     if( p->zLanguageid ){
119524       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
119525     }
119526   }
119527   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
119528       p->zDb,
119529       (p->zContentTbl ? p->zContentTbl : p->zName),
119530       (p->zContentTbl ? "" : "_content")
119531   );
119532   return zRet;
119533 }
119534
119535 /*
119536 ** Return a list of N comma separated question marks, where N is the number
119537 ** of columns in the %_content table (one for the docid plus one for each
119538 ** user-defined text column).
119539 **
119540 ** If argument zFunc is not NULL, then all but the first question mark
119541 ** is preceded by zFunc and an open bracket, and followed by a closed
119542 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
119543 ** user-defined text columns, the following string is returned:
119544 **
119545 **     "?, zip(?), zip(?), zip(?)"
119546 **
119547 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
119548 ** is the responsibility of the caller to eventually free it.
119549 **
119550 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
119551 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
119552 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
119553 ** no error occurs, *pRc is left unmodified.
119554 */
119555 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
119556   char *zRet = 0;
119557   char *zFree = 0;
119558   char *zFunction;
119559   int i;
119560
119561   if( !zFunc ){
119562     zFunction = "";
119563   }else{
119564     zFree = zFunction = fts3QuoteId(zFunc);
119565   }
119566   fts3Appendf(pRc, &zRet, "?");
119567   for(i=0; i<p->nColumn; i++){
119568     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
119569   }
119570   if( p->zLanguageid ){
119571     fts3Appendf(pRc, &zRet, ", ?");
119572   }
119573   sqlite3_free(zFree);
119574   return zRet;
119575 }
119576
119577 /*
119578 ** This function interprets the string at (*pp) as a non-negative integer
119579 ** value. It reads the integer and sets *pnOut to the value read, then
119580 ** sets *pp to point to the byte immediately following the last byte of
119581 ** the integer value.
119582 **
119583 ** Only decimal digits ('0'..'9') may be part of an integer value.
119584 **
119585 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
119586 ** the output value undefined. Otherwise SQLITE_OK is returned.
119587 **
119588 ** This function is used when parsing the "prefix=" FTS4 parameter.
119589 */
119590 static int fts3GobbleInt(const char **pp, int *pnOut){
119591   const char *p;                  /* Iterator pointer */
119592   int nInt = 0;                   /* Output value */
119593
119594   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
119595     nInt = nInt * 10 + (p[0] - '0');
119596   }
119597   if( p==*pp ) return SQLITE_ERROR;
119598   *pnOut = nInt;
119599   *pp = p;
119600   return SQLITE_OK;
119601 }
119602
119603 /*
119604 ** This function is called to allocate an array of Fts3Index structures
119605 ** representing the indexes maintained by the current FTS table. FTS tables
119606 ** always maintain the main "terms" index, but may also maintain one or
119607 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
119608 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
119609 **
119610 ** Argument zParam is passed the value of the "prefix=" option if one was
119611 ** specified, or NULL otherwise.
119612 **
119613 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
119614 ** the allocated array. *pnIndex is set to the number of elements in the
119615 ** array. If an error does occur, an SQLite error code is returned.
119616 **
119617 ** Regardless of whether or not an error is returned, it is the responsibility
119618 ** of the caller to call sqlite3_free() on the output array to free it.
119619 */
119620 static int fts3PrefixParameter(
119621   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
119622   int *pnIndex,                   /* OUT: size of *apIndex[] array */
119623   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
119624 ){
119625   struct Fts3Index *aIndex;       /* Allocated array */
119626   int nIndex = 1;                 /* Number of entries in array */
119627
119628   if( zParam && zParam[0] ){
119629     const char *p;
119630     nIndex++;
119631     for(p=zParam; *p; p++){
119632       if( *p==',' ) nIndex++;
119633     }
119634   }
119635
119636   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
119637   *apIndex = aIndex;
119638   *pnIndex = nIndex;
119639   if( !aIndex ){
119640     return SQLITE_NOMEM;
119641   }
119642
119643   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
119644   if( zParam ){
119645     const char *p = zParam;
119646     int i;
119647     for(i=1; i<nIndex; i++){
119648       int nPrefix;
119649       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
119650       aIndex[i].nPrefix = nPrefix;
119651       p++;
119652     }
119653   }
119654
119655   return SQLITE_OK;
119656 }
119657
119658 /*
119659 ** This function is called when initializing an FTS4 table that uses the
119660 ** content=xxx option. It determines the number of and names of the columns
119661 ** of the new FTS4 table.
119662 **
119663 ** The third argument passed to this function is the value passed to the
119664 ** config=xxx option (i.e. "xxx"). This function queries the database for
119665 ** a table of that name. If found, the output variables are populated
119666 ** as follows:
119667 **
119668 **   *pnCol:   Set to the number of columns table xxx has,
119669 **
119670 **   *pnStr:   Set to the total amount of space required to store a copy
119671 **             of each columns name, including the nul-terminator.
119672 **
119673 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
119674 **             the name of the corresponding column in table xxx. The array
119675 **             and its contents are allocated using a single allocation. It
119676 **             is the responsibility of the caller to free this allocation
119677 **             by eventually passing the *pazCol value to sqlite3_free().
119678 **
119679 ** If the table cannot be found, an error code is returned and the output
119680 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
119681 ** returned (and the output variables are undefined).
119682 */
119683 static int fts3ContentColumns(
119684   sqlite3 *db,                    /* Database handle */
119685   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
119686   const char *zTbl,               /* Name of content table */
119687   const char ***pazCol,           /* OUT: Malloc'd array of column names */
119688   int *pnCol,                     /* OUT: Size of array *pazCol */
119689   int *pnStr                      /* OUT: Bytes of string content */
119690 ){
119691   int rc = SQLITE_OK;             /* Return code */
119692   char *zSql;                     /* "SELECT *" statement on zTbl */
119693   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
119694
119695   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
119696   if( !zSql ){
119697     rc = SQLITE_NOMEM;
119698   }else{
119699     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
119700   }
119701   sqlite3_free(zSql);
119702
119703   if( rc==SQLITE_OK ){
119704     const char **azCol;           /* Output array */
119705     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
119706     int nCol;                     /* Number of table columns */
119707     int i;                        /* Used to iterate through columns */
119708
119709     /* Loop through the returned columns. Set nStr to the number of bytes of
119710     ** space required to store a copy of each column name, including the
119711     ** nul-terminator byte.  */
119712     nCol = sqlite3_column_count(pStmt);
119713     for(i=0; i<nCol; i++){
119714       const char *zCol = sqlite3_column_name(pStmt, i);
119715       nStr += (int)strlen(zCol) + 1;
119716     }
119717
119718     /* Allocate and populate the array to return. */
119719     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
119720     if( azCol==0 ){
119721       rc = SQLITE_NOMEM;
119722     }else{
119723       char *p = (char *)&azCol[nCol];
119724       for(i=0; i<nCol; i++){
119725         const char *zCol = sqlite3_column_name(pStmt, i);
119726         int n = (int)strlen(zCol)+1;
119727         memcpy(p, zCol, n);
119728         azCol[i] = p;
119729         p += n;
119730       }
119731     }
119732     sqlite3_finalize(pStmt);
119733
119734     /* Set the output variables. */
119735     *pnCol = nCol;
119736     *pnStr = nStr;
119737     *pazCol = azCol;
119738   }
119739
119740   return rc;
119741 }
119742
119743 /*
119744 ** This function is the implementation of both the xConnect and xCreate
119745 ** methods of the FTS3 virtual table.
119746 **
119747 ** The argv[] array contains the following:
119748 **
119749 **   argv[0]   -> module name  ("fts3" or "fts4")
119750 **   argv[1]   -> database name
119751 **   argv[2]   -> table name
119752 **   argv[...] -> "column name" and other module argument fields.
119753 */
119754 static int fts3InitVtab(
119755   int isCreate,                   /* True for xCreate, false for xConnect */
119756   sqlite3 *db,                    /* The SQLite database connection */
119757   void *pAux,                     /* Hash table containing tokenizers */
119758   int argc,                       /* Number of elements in argv array */
119759   const char * const *argv,       /* xCreate/xConnect argument array */
119760   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
119761   char **pzErr                    /* Write any error message here */
119762 ){
119763   Fts3Hash *pHash = (Fts3Hash *)pAux;
119764   Fts3Table *p = 0;               /* Pointer to allocated vtab */
119765   int rc = SQLITE_OK;             /* Return code */
119766   int i;                          /* Iterator variable */
119767   int nByte;                      /* Size of allocation used for *p */
119768   int iCol;                       /* Column index */
119769   int nString = 0;                /* Bytes required to hold all column names */
119770   int nCol = 0;                   /* Number of columns in the FTS table */
119771   char *zCsr;                     /* Space for holding column names */
119772   int nDb;                        /* Bytes required to hold database name */
119773   int nName;                      /* Bytes required to hold table name */
119774   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
119775   const char **aCol;              /* Array of column names */
119776   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
119777
119778   int nIndex;                     /* Size of aIndex[] array */
119779   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
119780
119781   /* The results of parsing supported FTS4 key=value options: */
119782   int bNoDocsize = 0;             /* True to omit %_docsize table */
119783   int bDescIdx = 0;               /* True to store descending indexes */
119784   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
119785   char *zCompress = 0;            /* compress=? parameter (or NULL) */
119786   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
119787   char *zContent = 0;             /* content=? parameter (or NULL) */
119788   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
119789
119790   assert( strlen(argv[0])==4 );
119791   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
119792        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
119793   );
119794
119795   nDb = (int)strlen(argv[1]) + 1;
119796   nName = (int)strlen(argv[2]) + 1;
119797
119798   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
119799   if( !aCol ) return SQLITE_NOMEM;
119800   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
119801
119802   /* Loop through all of the arguments passed by the user to the FTS3/4
119803   ** module (i.e. all the column names and special arguments). This loop
119804   ** does the following:
119805   **
119806   **   + Figures out the number of columns the FTSX table will have, and
119807   **     the number of bytes of space that must be allocated to store copies
119808   **     of the column names.
119809   **
119810   **   + If there is a tokenizer specification included in the arguments,
119811   **     initializes the tokenizer pTokenizer.
119812   */
119813   for(i=3; rc==SQLITE_OK && i<argc; i++){
119814     char const *z = argv[i];
119815     int nKey;
119816     char *zVal;
119817
119818     /* Check if this is a tokenizer specification */
119819     if( !pTokenizer
119820      && strlen(z)>8
119821      && 0==sqlite3_strnicmp(z, "tokenize", 8)
119822      && 0==sqlite3Fts3IsIdChar(z[8])
119823     ){
119824       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
119825     }
119826
119827     /* Check if it is an FTS4 special argument. */
119828     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
119829       struct Fts4Option {
119830         const char *zOpt;
119831         int nOpt;
119832       } aFts4Opt[] = {
119833         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
119834         { "prefix",      6 },     /* 1 -> PREFIX */
119835         { "compress",    8 },     /* 2 -> COMPRESS */
119836         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
119837         { "order",       5 },     /* 4 -> ORDER */
119838         { "content",     7 },     /* 5 -> CONTENT */
119839         { "languageid", 10 }      /* 6 -> LANGUAGEID */
119840       };
119841
119842       int iOpt;
119843       if( !zVal ){
119844         rc = SQLITE_NOMEM;
119845       }else{
119846         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
119847           struct Fts4Option *pOp = &aFts4Opt[iOpt];
119848           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
119849             break;
119850           }
119851         }
119852         if( iOpt==SizeofArray(aFts4Opt) ){
119853           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
119854           rc = SQLITE_ERROR;
119855         }else{
119856           switch( iOpt ){
119857             case 0:               /* MATCHINFO */
119858               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
119859                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
119860                 rc = SQLITE_ERROR;
119861               }
119862               bNoDocsize = 1;
119863               break;
119864
119865             case 1:               /* PREFIX */
119866               sqlite3_free(zPrefix);
119867               zPrefix = zVal;
119868               zVal = 0;
119869               break;
119870
119871             case 2:               /* COMPRESS */
119872               sqlite3_free(zCompress);
119873               zCompress = zVal;
119874               zVal = 0;
119875               break;
119876
119877             case 3:               /* UNCOMPRESS */
119878               sqlite3_free(zUncompress);
119879               zUncompress = zVal;
119880               zVal = 0;
119881               break;
119882
119883             case 4:               /* ORDER */
119884               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
119885                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
119886               ){
119887                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
119888                 rc = SQLITE_ERROR;
119889               }
119890               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
119891               break;
119892
119893             case 5:              /* CONTENT */
119894               sqlite3_free(zContent);
119895               zContent = zVal;
119896               zVal = 0;
119897               break;
119898
119899             case 6:              /* LANGUAGEID */
119900               assert( iOpt==6 );
119901               sqlite3_free(zLanguageid);
119902               zLanguageid = zVal;
119903               zVal = 0;
119904               break;
119905           }
119906         }
119907         sqlite3_free(zVal);
119908       }
119909     }
119910
119911     /* Otherwise, the argument is a column name. */
119912     else {
119913       nString += (int)(strlen(z) + 1);
119914       aCol[nCol++] = z;
119915     }
119916   }
119917
119918   /* If a content=xxx option was specified, the following:
119919   **
119920   **   1. Ignore any compress= and uncompress= options.
119921   **
119922   **   2. If no column names were specified as part of the CREATE VIRTUAL
119923   **      TABLE statement, use all columns from the content table.
119924   */
119925   if( rc==SQLITE_OK && zContent ){
119926     sqlite3_free(zCompress);
119927     sqlite3_free(zUncompress);
119928     zCompress = 0;
119929     zUncompress = 0;
119930     if( nCol==0 ){
119931       sqlite3_free((void*)aCol);
119932       aCol = 0;
119933       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
119934
119935       /* If a languageid= option was specified, remove the language id
119936       ** column from the aCol[] array. */
119937       if( rc==SQLITE_OK && zLanguageid ){
119938         int j;
119939         for(j=0; j<nCol; j++){
119940           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
119941             int k;
119942             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
119943             nCol--;
119944             break;
119945           }
119946         }
119947       }
119948     }
119949   }
119950   if( rc!=SQLITE_OK ) goto fts3_init_out;
119951
119952   if( nCol==0 ){
119953     assert( nString==0 );
119954     aCol[0] = "content";
119955     nString = 8;
119956     nCol = 1;
119957   }
119958
119959   if( pTokenizer==0 ){
119960     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
119961     if( rc!=SQLITE_OK ) goto fts3_init_out;
119962   }
119963   assert( pTokenizer );
119964
119965   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
119966   if( rc==SQLITE_ERROR ){
119967     assert( zPrefix );
119968     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
119969   }
119970   if( rc!=SQLITE_OK ) goto fts3_init_out;
119971
119972   /* Allocate and populate the Fts3Table structure. */
119973   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
119974           nCol * sizeof(char *) +              /* azColumn */
119975           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
119976           nName +                              /* zName */
119977           nDb +                                /* zDb */
119978           nString;                             /* Space for azColumn strings */
119979   p = (Fts3Table*)sqlite3_malloc(nByte);
119980   if( p==0 ){
119981     rc = SQLITE_NOMEM;
119982     goto fts3_init_out;
119983   }
119984   memset(p, 0, nByte);
119985   p->db = db;
119986   p->nColumn = nCol;
119987   p->nPendingData = 0;
119988   p->azColumn = (char **)&p[1];
119989   p->pTokenizer = pTokenizer;
119990   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
119991   p->bHasDocsize = (isFts4 && bNoDocsize==0);
119992   p->bHasStat = isFts4;
119993   p->bFts4 = isFts4;
119994   p->bDescIdx = bDescIdx;
119995   p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
119996   p->zContentTbl = zContent;
119997   p->zLanguageid = zLanguageid;
119998   zContent = 0;
119999   zLanguageid = 0;
120000   TESTONLY( p->inTransaction = -1 );
120001   TESTONLY( p->mxSavepoint = -1 );
120002
120003   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
120004   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
120005   p->nIndex = nIndex;
120006   for(i=0; i<nIndex; i++){
120007     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
120008   }
120009
120010   /* Fill in the zName and zDb fields of the vtab structure. */
120011   zCsr = (char *)&p->aIndex[nIndex];
120012   p->zName = zCsr;
120013   memcpy(zCsr, argv[2], nName);
120014   zCsr += nName;
120015   p->zDb = zCsr;
120016   memcpy(zCsr, argv[1], nDb);
120017   zCsr += nDb;
120018
120019   /* Fill in the azColumn array */
120020   for(iCol=0; iCol<nCol; iCol++){
120021     char *z;
120022     int n = 0;
120023     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
120024     memcpy(zCsr, z, n);
120025     zCsr[n] = '\0';
120026     sqlite3Fts3Dequote(zCsr);
120027     p->azColumn[iCol] = zCsr;
120028     zCsr += n+1;
120029     assert( zCsr <= &((char *)p)[nByte] );
120030   }
120031
120032   if( (zCompress==0)!=(zUncompress==0) ){
120033     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
120034     rc = SQLITE_ERROR;
120035     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
120036   }
120037   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
120038   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
120039   if( rc!=SQLITE_OK ) goto fts3_init_out;
120040
120041   /* If this is an xCreate call, create the underlying tables in the
120042   ** database. TODO: For xConnect(), it could verify that said tables exist.
120043   */
120044   if( isCreate ){
120045     rc = fts3CreateTables(p);
120046   }
120047
120048   /* Check to see if a legacy fts3 table has been "upgraded" by the
120049   ** addition of a %_stat table so that it can use incremental merge.
120050   */
120051   if( !isFts4 && !isCreate ){
120052     int rc2 = SQLITE_OK;
120053     fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
120054                p->zDb, p->zName);
120055     if( rc2==SQLITE_OK ) p->bHasStat = 1;
120056   }
120057
120058   /* Figure out the page-size for the database. This is required in order to
120059   ** estimate the cost of loading large doclists from the database.  */
120060   fts3DatabasePageSize(&rc, p);
120061   p->nNodeSize = p->nPgsz-35;
120062
120063   /* Declare the table schema to SQLite. */
120064   fts3DeclareVtab(&rc, p);
120065
120066 fts3_init_out:
120067   sqlite3_free(zPrefix);
120068   sqlite3_free(aIndex);
120069   sqlite3_free(zCompress);
120070   sqlite3_free(zUncompress);
120071   sqlite3_free(zContent);
120072   sqlite3_free(zLanguageid);
120073   sqlite3_free((void *)aCol);
120074   if( rc!=SQLITE_OK ){
120075     if( p ){
120076       fts3DisconnectMethod((sqlite3_vtab *)p);
120077     }else if( pTokenizer ){
120078       pTokenizer->pModule->xDestroy(pTokenizer);
120079     }
120080   }else{
120081     assert( p->pSegments==0 );
120082     *ppVTab = &p->base;
120083   }
120084   return rc;
120085 }
120086
120087 /*
120088 ** The xConnect() and xCreate() methods for the virtual table. All the
120089 ** work is done in function fts3InitVtab().
120090 */
120091 static int fts3ConnectMethod(
120092   sqlite3 *db,                    /* Database connection */
120093   void *pAux,                     /* Pointer to tokenizer hash table */
120094   int argc,                       /* Number of elements in argv array */
120095   const char * const *argv,       /* xCreate/xConnect argument array */
120096   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
120097   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
120098 ){
120099   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
120100 }
120101 static int fts3CreateMethod(
120102   sqlite3 *db,                    /* Database connection */
120103   void *pAux,                     /* Pointer to tokenizer hash table */
120104   int argc,                       /* Number of elements in argv array */
120105   const char * const *argv,       /* xCreate/xConnect argument array */
120106   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
120107   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
120108 ){
120109   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
120110 }
120111
120112 /*
120113 ** Implementation of the xBestIndex method for FTS3 tables. There
120114 ** are three possible strategies, in order of preference:
120115 **
120116 **   1. Direct lookup by rowid or docid.
120117 **   2. Full-text search using a MATCH operator on a non-docid column.
120118 **   3. Linear scan of %_content table.
120119 */
120120 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
120121   Fts3Table *p = (Fts3Table *)pVTab;
120122   int i;                          /* Iterator variable */
120123   int iCons = -1;                 /* Index of constraint to use */
120124   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
120125
120126   /* By default use a full table scan. This is an expensive option,
120127   ** so search through the constraints to see if a more efficient
120128   ** strategy is possible.
120129   */
120130   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120131   pInfo->estimatedCost = 500000;
120132   for(i=0; i<pInfo->nConstraint; i++){
120133     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120134     if( pCons->usable==0 ) continue;
120135
120136     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
120137     if( iCons<0
120138      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
120139      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
120140     ){
120141       pInfo->idxNum = FTS3_DOCID_SEARCH;
120142       pInfo->estimatedCost = 1.0;
120143       iCons = i;
120144     }
120145
120146     /* A MATCH constraint. Use a full-text search.
120147     **
120148     ** If there is more than one MATCH constraint available, use the first
120149     ** one encountered. If there is both a MATCH constraint and a direct
120150     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
120151     ** though the rowid/docid lookup is faster than a MATCH query, selecting
120152     ** it would lead to an "unable to use function MATCH in the requested
120153     ** context" error.
120154     */
120155     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
120156      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
120157     ){
120158       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
120159       pInfo->estimatedCost = 2.0;
120160       iCons = i;
120161     }
120162
120163     /* Equality constraint on the langid column */
120164     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
120165      && pCons->iColumn==p->nColumn + 2
120166     ){
120167       iLangidCons = i;
120168     }
120169   }
120170
120171   if( iCons>=0 ){
120172     pInfo->aConstraintUsage[iCons].argvIndex = 1;
120173     pInfo->aConstraintUsage[iCons].omit = 1;
120174   }
120175   if( iLangidCons>=0 ){
120176     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
120177   }
120178
120179   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
120180   ** docid) order. Both ascending and descending are possible.
120181   */
120182   if( pInfo->nOrderBy==1 ){
120183     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
120184     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
120185       if( pOrder->desc ){
120186         pInfo->idxStr = "DESC";
120187       }else{
120188         pInfo->idxStr = "ASC";
120189       }
120190       pInfo->orderByConsumed = 1;
120191     }
120192   }
120193
120194   assert( p->pSegments==0 );
120195   return SQLITE_OK;
120196 }
120197
120198 /*
120199 ** Implementation of xOpen method.
120200 */
120201 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
120202   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
120203
120204   UNUSED_PARAMETER(pVTab);
120205
120206   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
120207   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
120208   ** if the allocation fails, return SQLITE_NOMEM.
120209   */
120210   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
120211   if( !pCsr ){
120212     return SQLITE_NOMEM;
120213   }
120214   memset(pCsr, 0, sizeof(Fts3Cursor));
120215   return SQLITE_OK;
120216 }
120217
120218 /*
120219 ** Close the cursor.  For additional information see the documentation
120220 ** on the xClose method of the virtual table interface.
120221 */
120222 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
120223   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120224   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120225   sqlite3_finalize(pCsr->pStmt);
120226   sqlite3Fts3ExprFree(pCsr->pExpr);
120227   sqlite3Fts3FreeDeferredTokens(pCsr);
120228   sqlite3_free(pCsr->aDoclist);
120229   sqlite3_free(pCsr->aMatchinfo);
120230   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120231   sqlite3_free(pCsr);
120232   return SQLITE_OK;
120233 }
120234
120235 /*
120236 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
120237 ** compose and prepare an SQL statement of the form:
120238 **
120239 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
120240 **
120241 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
120242 ** it. If an error occurs, return an SQLite error code.
120243 **
120244 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
120245 */
120246 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
120247   int rc = SQLITE_OK;
120248   if( pCsr->pStmt==0 ){
120249     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120250     char *zSql;
120251     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
120252     if( !zSql ) return SQLITE_NOMEM;
120253     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
120254     sqlite3_free(zSql);
120255   }
120256   *ppStmt = pCsr->pStmt;
120257   return rc;
120258 }
120259
120260 /*
120261 ** Position the pCsr->pStmt statement so that it is on the row
120262 ** of the %_content table that contains the last match.  Return
120263 ** SQLITE_OK on success.
120264 */
120265 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
120266   int rc = SQLITE_OK;
120267   if( pCsr->isRequireSeek ){
120268     sqlite3_stmt *pStmt = 0;
120269
120270     rc = fts3CursorSeekStmt(pCsr, &pStmt);
120271     if( rc==SQLITE_OK ){
120272       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
120273       pCsr->isRequireSeek = 0;
120274       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
120275         return SQLITE_OK;
120276       }else{
120277         rc = sqlite3_reset(pCsr->pStmt);
120278         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
120279           /* If no row was found and no error has occured, then the %_content
120280           ** table is missing a row that is present in the full-text index.
120281           ** The data structures are corrupt.  */
120282           rc = FTS_CORRUPT_VTAB;
120283           pCsr->isEof = 1;
120284         }
120285       }
120286     }
120287   }
120288
120289   if( rc!=SQLITE_OK && pContext ){
120290     sqlite3_result_error_code(pContext, rc);
120291   }
120292   return rc;
120293 }
120294
120295 /*
120296 ** This function is used to process a single interior node when searching
120297 ** a b-tree for a term or term prefix. The node data is passed to this
120298 ** function via the zNode/nNode parameters. The term to search for is
120299 ** passed in zTerm/nTerm.
120300 **
120301 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
120302 ** of the child node that heads the sub-tree that may contain the term.
120303 **
120304 ** If piLast is not NULL, then *piLast is set to the right-most child node
120305 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
120306 ** a prefix.
120307 **
120308 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
120309 */
120310 static int fts3ScanInteriorNode(
120311   const char *zTerm,              /* Term to select leaves for */
120312   int nTerm,                      /* Size of term zTerm in bytes */
120313   const char *zNode,              /* Buffer containing segment interior node */
120314   int nNode,                      /* Size of buffer at zNode */
120315   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
120316   sqlite3_int64 *piLast           /* OUT: Selected child node */
120317 ){
120318   int rc = SQLITE_OK;             /* Return code */
120319   const char *zCsr = zNode;       /* Cursor to iterate through node */
120320   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
120321   char *zBuffer = 0;              /* Buffer to load terms into */
120322   int nAlloc = 0;                 /* Size of allocated buffer */
120323   int isFirstTerm = 1;            /* True when processing first term on page */
120324   sqlite3_int64 iChild;           /* Block id of child node to descend to */
120325
120326   /* Skip over the 'height' varint that occurs at the start of every
120327   ** interior node. Then load the blockid of the left-child of the b-tree
120328   ** node into variable iChild.
120329   **
120330   ** Even if the data structure on disk is corrupted, this (reading two
120331   ** varints from the buffer) does not risk an overread. If zNode is a
120332   ** root node, then the buffer comes from a SELECT statement. SQLite does
120333   ** not make this guarantee explicitly, but in practice there are always
120334   ** either more than 20 bytes of allocated space following the nNode bytes of
120335   ** contents, or two zero bytes. Or, if the node is read from the %_segments
120336   ** table, then there are always 20 bytes of zeroed padding following the
120337   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
120338   */
120339   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
120340   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
120341   if( zCsr>zEnd ){
120342     return FTS_CORRUPT_VTAB;
120343   }
120344
120345   while( zCsr<zEnd && (piFirst || piLast) ){
120346     int cmp;                      /* memcmp() result */
120347     int nSuffix;                  /* Size of term suffix */
120348     int nPrefix = 0;              /* Size of term prefix */
120349     int nBuffer;                  /* Total term size */
120350
120351     /* Load the next term on the node into zBuffer. Use realloc() to expand
120352     ** the size of zBuffer if required.  */
120353     if( !isFirstTerm ){
120354       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
120355     }
120356     isFirstTerm = 0;
120357     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
120358
120359     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
120360       rc = FTS_CORRUPT_VTAB;
120361       goto finish_scan;
120362     }
120363     if( nPrefix+nSuffix>nAlloc ){
120364       char *zNew;
120365       nAlloc = (nPrefix+nSuffix) * 2;
120366       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
120367       if( !zNew ){
120368         rc = SQLITE_NOMEM;
120369         goto finish_scan;
120370       }
120371       zBuffer = zNew;
120372     }
120373     assert( zBuffer );
120374     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
120375     nBuffer = nPrefix + nSuffix;
120376     zCsr += nSuffix;
120377
120378     /* Compare the term we are searching for with the term just loaded from
120379     ** the interior node. If the specified term is greater than or equal
120380     ** to the term from the interior node, then all terms on the sub-tree
120381     ** headed by node iChild are smaller than zTerm. No need to search
120382     ** iChild.
120383     **
120384     ** If the interior node term is larger than the specified term, then
120385     ** the tree headed by iChild may contain the specified term.
120386     */
120387     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
120388     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
120389       *piFirst = iChild;
120390       piFirst = 0;
120391     }
120392
120393     if( piLast && cmp<0 ){
120394       *piLast = iChild;
120395       piLast = 0;
120396     }
120397
120398     iChild++;
120399   };
120400
120401   if( piFirst ) *piFirst = iChild;
120402   if( piLast ) *piLast = iChild;
120403
120404  finish_scan:
120405   sqlite3_free(zBuffer);
120406   return rc;
120407 }
120408
120409
120410 /*
120411 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
120412 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
120413 ** contains a term. This function searches the sub-tree headed by the zNode
120414 ** node for the range of leaf nodes that may contain the specified term
120415 ** or terms for which the specified term is a prefix.
120416 **
120417 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
120418 ** left-most leaf node in the tree that may contain the specified term.
120419 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
120420 ** right-most leaf node that may contain a term for which the specified
120421 ** term is a prefix.
120422 **
120423 ** It is possible that the range of returned leaf nodes does not contain
120424 ** the specified term or any terms for which it is a prefix. However, if the
120425 ** segment does contain any such terms, they are stored within the identified
120426 ** range. Because this function only inspects interior segment nodes (and
120427 ** never loads leaf nodes into memory), it is not possible to be sure.
120428 **
120429 ** If an error occurs, an error code other than SQLITE_OK is returned.
120430 */
120431 static int fts3SelectLeaf(
120432   Fts3Table *p,                   /* Virtual table handle */
120433   const char *zTerm,              /* Term to select leaves for */
120434   int nTerm,                      /* Size of term zTerm in bytes */
120435   const char *zNode,              /* Buffer containing segment interior node */
120436   int nNode,                      /* Size of buffer at zNode */
120437   sqlite3_int64 *piLeaf,          /* Selected leaf node */
120438   sqlite3_int64 *piLeaf2          /* Selected leaf node */
120439 ){
120440   int rc;                         /* Return code */
120441   int iHeight;                    /* Height of this node in tree */
120442
120443   assert( piLeaf || piLeaf2 );
120444
120445   sqlite3Fts3GetVarint32(zNode, &iHeight);
120446   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
120447   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
120448
120449   if( rc==SQLITE_OK && iHeight>1 ){
120450     char *zBlob = 0;              /* Blob read from %_segments table */
120451     int nBlob;                    /* Size of zBlob in bytes */
120452
120453     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
120454       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
120455       if( rc==SQLITE_OK ){
120456         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
120457       }
120458       sqlite3_free(zBlob);
120459       piLeaf = 0;
120460       zBlob = 0;
120461     }
120462
120463     if( rc==SQLITE_OK ){
120464       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
120465     }
120466     if( rc==SQLITE_OK ){
120467       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
120468     }
120469     sqlite3_free(zBlob);
120470   }
120471
120472   return rc;
120473 }
120474
120475 /*
120476 ** This function is used to create delta-encoded serialized lists of FTS3
120477 ** varints. Each call to this function appends a single varint to a list.
120478 */
120479 static void fts3PutDeltaVarint(
120480   char **pp,                      /* IN/OUT: Output pointer */
120481   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
120482   sqlite3_int64 iVal              /* Write this value to the list */
120483 ){
120484   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
120485   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
120486   *piPrev = iVal;
120487 }
120488
120489 /*
120490 ** When this function is called, *ppPoslist is assumed to point to the
120491 ** start of a position-list. After it returns, *ppPoslist points to the
120492 ** first byte after the position-list.
120493 **
120494 ** A position list is list of positions (delta encoded) and columns for
120495 ** a single document record of a doclist.  So, in other words, this
120496 ** routine advances *ppPoslist so that it points to the next docid in
120497 ** the doclist, or to the first byte past the end of the doclist.
120498 **
120499 ** If pp is not NULL, then the contents of the position list are copied
120500 ** to *pp. *pp is set to point to the first byte past the last byte copied
120501 ** before this function returns.
120502 */
120503 static void fts3PoslistCopy(char **pp, char **ppPoslist){
120504   char *pEnd = *ppPoslist;
120505   char c = 0;
120506
120507   /* The end of a position list is marked by a zero encoded as an FTS3
120508   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
120509   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
120510   ** of some other, multi-byte, value.
120511   **
120512   ** The following while-loop moves pEnd to point to the first byte that is not
120513   ** immediately preceded by a byte with the 0x80 bit set. Then increments
120514   ** pEnd once more so that it points to the byte immediately following the
120515   ** last byte in the position-list.
120516   */
120517   while( *pEnd | c ){
120518     c = *pEnd++ & 0x80;
120519     testcase( c!=0 && (*pEnd)==0 );
120520   }
120521   pEnd++;  /* Advance past the POS_END terminator byte */
120522
120523   if( pp ){
120524     int n = (int)(pEnd - *ppPoslist);
120525     char *p = *pp;
120526     memcpy(p, *ppPoslist, n);
120527     p += n;
120528     *pp = p;
120529   }
120530   *ppPoslist = pEnd;
120531 }
120532
120533 /*
120534 ** When this function is called, *ppPoslist is assumed to point to the
120535 ** start of a column-list. After it returns, *ppPoslist points to the
120536 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
120537 **
120538 ** A column-list is list of delta-encoded positions for a single column
120539 ** within a single document within a doclist.
120540 **
120541 ** The column-list is terminated either by a POS_COLUMN varint (1) or
120542 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
120543 ** the POS_COLUMN or POS_END that terminates the column-list.
120544 **
120545 ** If pp is not NULL, then the contents of the column-list are copied
120546 ** to *pp. *pp is set to point to the first byte past the last byte copied
120547 ** before this function returns.  The POS_COLUMN or POS_END terminator
120548 ** is not copied into *pp.
120549 */
120550 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
120551   char *pEnd = *ppPoslist;
120552   char c = 0;
120553
120554   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
120555   ** not part of a multi-byte varint.
120556   */
120557   while( 0xFE & (*pEnd | c) ){
120558     c = *pEnd++ & 0x80;
120559     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
120560   }
120561   if( pp ){
120562     int n = (int)(pEnd - *ppPoslist);
120563     char *p = *pp;
120564     memcpy(p, *ppPoslist, n);
120565     p += n;
120566     *pp = p;
120567   }
120568   *ppPoslist = pEnd;
120569 }
120570
120571 /*
120572 ** Value used to signify the end of an position-list. This is safe because
120573 ** it is not possible to have a document with 2^31 terms.
120574 */
120575 #define POSITION_LIST_END 0x7fffffff
120576
120577 /*
120578 ** This function is used to help parse position-lists. When this function is
120579 ** called, *pp may point to the start of the next varint in the position-list
120580 ** being parsed, or it may point to 1 byte past the end of the position-list
120581 ** (in which case **pp will be a terminator bytes POS_END (0) or
120582 ** (1)).
120583 **
120584 ** If *pp points past the end of the current position-list, set *pi to
120585 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
120586 ** increment the current value of *pi by the value read, and set *pp to
120587 ** point to the next value before returning.
120588 **
120589 ** Before calling this routine *pi must be initialized to the value of
120590 ** the previous position, or zero if we are reading the first position
120591 ** in the position-list.  Because positions are delta-encoded, the value
120592 ** of the previous position is needed in order to compute the value of
120593 ** the next position.
120594 */
120595 static void fts3ReadNextPos(
120596   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
120597   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
120598 ){
120599   if( (**pp)&0xFE ){
120600     fts3GetDeltaVarint(pp, pi);
120601     *pi -= 2;
120602   }else{
120603     *pi = POSITION_LIST_END;
120604   }
120605 }
120606
120607 /*
120608 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
120609 ** the value of iCol encoded as a varint to *pp.   This will start a new
120610 ** column list.
120611 **
120612 ** Set *pp to point to the byte just after the last byte written before
120613 ** returning (do not modify it if iCol==0). Return the total number of bytes
120614 ** written (0 if iCol==0).
120615 */
120616 static int fts3PutColNumber(char **pp, int iCol){
120617   int n = 0;                      /* Number of bytes written */
120618   if( iCol ){
120619     char *p = *pp;                /* Output pointer */
120620     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
120621     *p = 0x01;
120622     *pp = &p[n];
120623   }
120624   return n;
120625 }
120626
120627 /*
120628 ** Compute the union of two position lists.  The output written
120629 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
120630 ** order and with any duplicates removed.  All pointers are
120631 ** updated appropriately.   The caller is responsible for insuring
120632 ** that there is enough space in *pp to hold the complete output.
120633 */
120634 static void fts3PoslistMerge(
120635   char **pp,                      /* Output buffer */
120636   char **pp1,                     /* Left input list */
120637   char **pp2                      /* Right input list */
120638 ){
120639   char *p = *pp;
120640   char *p1 = *pp1;
120641   char *p2 = *pp2;
120642
120643   while( *p1 || *p2 ){
120644     int iCol1;         /* The current column index in pp1 */
120645     int iCol2;         /* The current column index in pp2 */
120646
120647     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
120648     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
120649     else iCol1 = 0;
120650
120651     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
120652     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
120653     else iCol2 = 0;
120654
120655     if( iCol1==iCol2 ){
120656       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
120657       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
120658       sqlite3_int64 iPrev = 0;
120659       int n = fts3PutColNumber(&p, iCol1);
120660       p1 += n;
120661       p2 += n;
120662
120663       /* At this point, both p1 and p2 point to the start of column-lists
120664       ** for the same column (the column with index iCol1 and iCol2).
120665       ** A column-list is a list of non-negative delta-encoded varints, each
120666       ** incremented by 2 before being stored. Each list is terminated by a
120667       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
120668       ** and writes the results to buffer p. p is left pointing to the byte
120669       ** after the list written. No terminator (POS_END or POS_COLUMN) is
120670       ** written to the output.
120671       */
120672       fts3GetDeltaVarint(&p1, &i1);
120673       fts3GetDeltaVarint(&p2, &i2);
120674       do {
120675         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
120676         iPrev -= 2;
120677         if( i1==i2 ){
120678           fts3ReadNextPos(&p1, &i1);
120679           fts3ReadNextPos(&p2, &i2);
120680         }else if( i1<i2 ){
120681           fts3ReadNextPos(&p1, &i1);
120682         }else{
120683           fts3ReadNextPos(&p2, &i2);
120684         }
120685       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
120686     }else if( iCol1<iCol2 ){
120687       p1 += fts3PutColNumber(&p, iCol1);
120688       fts3ColumnlistCopy(&p, &p1);
120689     }else{
120690       p2 += fts3PutColNumber(&p, iCol2);
120691       fts3ColumnlistCopy(&p, &p2);
120692     }
120693   }
120694
120695   *p++ = POS_END;
120696   *pp = p;
120697   *pp1 = p1 + 1;
120698   *pp2 = p2 + 1;
120699 }
120700
120701 /*
120702 ** This function is used to merge two position lists into one. When it is
120703 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
120704 ** the part of a doclist that follows each document id. For example, if a row
120705 ** contains:
120706 **
120707 **     'a b c'|'x y z'|'a b b a'
120708 **
120709 ** Then the position list for this row for token 'b' would consist of:
120710 **
120711 **     0x02 0x01 0x02 0x03 0x03 0x00
120712 **
120713 ** When this function returns, both *pp1 and *pp2 are left pointing to the
120714 ** byte following the 0x00 terminator of their respective position lists.
120715 **
120716 ** If isSaveLeft is 0, an entry is added to the output position list for
120717 ** each position in *pp2 for which there exists one or more positions in
120718 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
120719 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
120720 ** slots before it.
120721 **
120722 ** e.g. nToken==1 searches for adjacent positions.
120723 */
120724 static int fts3PoslistPhraseMerge(
120725   char **pp,                      /* IN/OUT: Preallocated output buffer */
120726   int nToken,                     /* Maximum difference in token positions */
120727   int isSaveLeft,                 /* Save the left position */
120728   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
120729   char **pp1,                     /* IN/OUT: Left input list */
120730   char **pp2                      /* IN/OUT: Right input list */
120731 ){
120732   char *p = *pp;
120733   char *p1 = *pp1;
120734   char *p2 = *pp2;
120735   int iCol1 = 0;
120736   int iCol2 = 0;
120737
120738   /* Never set both isSaveLeft and isExact for the same invocation. */
120739   assert( isSaveLeft==0 || isExact==0 );
120740
120741   assert( p!=0 && *p1!=0 && *p2!=0 );
120742   if( *p1==POS_COLUMN ){
120743     p1++;
120744     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
120745   }
120746   if( *p2==POS_COLUMN ){
120747     p2++;
120748     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
120749   }
120750
120751   while( 1 ){
120752     if( iCol1==iCol2 ){
120753       char *pSave = p;
120754       sqlite3_int64 iPrev = 0;
120755       sqlite3_int64 iPos1 = 0;
120756       sqlite3_int64 iPos2 = 0;
120757
120758       if( iCol1 ){
120759         *p++ = POS_COLUMN;
120760         p += sqlite3Fts3PutVarint(p, iCol1);
120761       }
120762
120763       assert( *p1!=POS_END && *p1!=POS_COLUMN );
120764       assert( *p2!=POS_END && *p2!=POS_COLUMN );
120765       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
120766       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
120767
120768       while( 1 ){
120769         if( iPos2==iPos1+nToken
120770          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
120771         ){
120772           sqlite3_int64 iSave;
120773           iSave = isSaveLeft ? iPos1 : iPos2;
120774           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
120775           pSave = 0;
120776           assert( p );
120777         }
120778         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
120779           if( (*p2&0xFE)==0 ) break;
120780           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
120781         }else{
120782           if( (*p1&0xFE)==0 ) break;
120783           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
120784         }
120785       }
120786
120787       if( pSave ){
120788         assert( pp && p );
120789         p = pSave;
120790       }
120791
120792       fts3ColumnlistCopy(0, &p1);
120793       fts3ColumnlistCopy(0, &p2);
120794       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
120795       if( 0==*p1 || 0==*p2 ) break;
120796
120797       p1++;
120798       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
120799       p2++;
120800       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
120801     }
120802
120803     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
120804     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
120805     ** end of the position list, or the 0x01 that precedes the next
120806     ** column-number in the position list.
120807     */
120808     else if( iCol1<iCol2 ){
120809       fts3ColumnlistCopy(0, &p1);
120810       if( 0==*p1 ) break;
120811       p1++;
120812       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
120813     }else{
120814       fts3ColumnlistCopy(0, &p2);
120815       if( 0==*p2 ) break;
120816       p2++;
120817       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
120818     }
120819   }
120820
120821   fts3PoslistCopy(0, &p2);
120822   fts3PoslistCopy(0, &p1);
120823   *pp1 = p1;
120824   *pp2 = p2;
120825   if( *pp==p ){
120826     return 0;
120827   }
120828   *p++ = 0x00;
120829   *pp = p;
120830   return 1;
120831 }
120832
120833 /*
120834 ** Merge two position-lists as required by the NEAR operator. The argument
120835 ** position lists correspond to the left and right phrases of an expression
120836 ** like:
120837 **
120838 **     "phrase 1" NEAR "phrase number 2"
120839 **
120840 ** Position list *pp1 corresponds to the left-hand side of the NEAR
120841 ** expression and *pp2 to the right. As usual, the indexes in the position
120842 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
120843 ** in the example above).
120844 **
120845 ** The output position list - written to *pp - is a copy of *pp2 with those
120846 ** entries that are not sufficiently NEAR entries in *pp1 removed.
120847 */
120848 static int fts3PoslistNearMerge(
120849   char **pp,                      /* Output buffer */
120850   char *aTmp,                     /* Temporary buffer space */
120851   int nRight,                     /* Maximum difference in token positions */
120852   int nLeft,                      /* Maximum difference in token positions */
120853   char **pp1,                     /* IN/OUT: Left input list */
120854   char **pp2                      /* IN/OUT: Right input list */
120855 ){
120856   char *p1 = *pp1;
120857   char *p2 = *pp2;
120858
120859   char *pTmp1 = aTmp;
120860   char *pTmp2;
120861   char *aTmp2;
120862   int res = 1;
120863
120864   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
120865   aTmp2 = pTmp2 = pTmp1;
120866   *pp1 = p1;
120867   *pp2 = p2;
120868   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
120869   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
120870     fts3PoslistMerge(pp, &aTmp, &aTmp2);
120871   }else if( pTmp1!=aTmp ){
120872     fts3PoslistCopy(pp, &aTmp);
120873   }else if( pTmp2!=aTmp2 ){
120874     fts3PoslistCopy(pp, &aTmp2);
120875   }else{
120876     res = 0;
120877   }
120878
120879   return res;
120880 }
120881
120882 /*
120883 ** An instance of this function is used to merge together the (potentially
120884 ** large number of) doclists for each term that matches a prefix query.
120885 ** See function fts3TermSelectMerge() for details.
120886 */
120887 typedef struct TermSelect TermSelect;
120888 struct TermSelect {
120889   char *aaOutput[16];             /* Malloc'd output buffers */
120890   int anOutput[16];               /* Size each output buffer in bytes */
120891 };
120892
120893 /*
120894 ** This function is used to read a single varint from a buffer. Parameter
120895 ** pEnd points 1 byte past the end of the buffer. When this function is
120896 ** called, if *pp points to pEnd or greater, then the end of the buffer
120897 ** has been reached. In this case *pp is set to 0 and the function returns.
120898 **
120899 ** If *pp does not point to or past pEnd, then a single varint is read
120900 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
120901 **
120902 ** If bDescIdx is false, the value read is added to *pVal before returning.
120903 ** If it is true, the value read is subtracted from *pVal before this
120904 ** function returns.
120905 */
120906 static void fts3GetDeltaVarint3(
120907   char **pp,                      /* IN/OUT: Point to read varint from */
120908   char *pEnd,                     /* End of buffer */
120909   int bDescIdx,                   /* True if docids are descending */
120910   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
120911 ){
120912   if( *pp>=pEnd ){
120913     *pp = 0;
120914   }else{
120915     sqlite3_int64 iVal;
120916     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
120917     if( bDescIdx ){
120918       *pVal -= iVal;
120919     }else{
120920       *pVal += iVal;
120921     }
120922   }
120923 }
120924
120925 /*
120926 ** This function is used to write a single varint to a buffer. The varint
120927 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
120928 ** end of the value written.
120929 **
120930 ** If *pbFirst is zero when this function is called, the value written to
120931 ** the buffer is that of parameter iVal.
120932 **
120933 ** If *pbFirst is non-zero when this function is called, then the value
120934 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
120935 ** (if bDescIdx is non-zero).
120936 **
120937 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
120938 ** to the value of parameter iVal.
120939 */
120940 static void fts3PutDeltaVarint3(
120941   char **pp,                      /* IN/OUT: Output pointer */
120942   int bDescIdx,                   /* True for descending docids */
120943   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
120944   int *pbFirst,                   /* IN/OUT: True after first int written */
120945   sqlite3_int64 iVal              /* Write this value to the list */
120946 ){
120947   sqlite3_int64 iWrite;
120948   if( bDescIdx==0 || *pbFirst==0 ){
120949     iWrite = iVal - *piPrev;
120950   }else{
120951     iWrite = *piPrev - iVal;
120952   }
120953   assert( *pbFirst || *piPrev==0 );
120954   assert( *pbFirst==0 || iWrite>0 );
120955   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
120956   *piPrev = iVal;
120957   *pbFirst = 1;
120958 }
120959
120960
120961 /*
120962 ** This macro is used by various functions that merge doclists. The two
120963 ** arguments are 64-bit docid values. If the value of the stack variable
120964 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
120965 ** Otherwise, (i2-i1).
120966 **
120967 ** Using this makes it easier to write code that can merge doclists that are
120968 ** sorted in either ascending or descending order.
120969 */
120970 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
120971
120972 /*
120973 ** This function does an "OR" merge of two doclists (output contains all
120974 ** positions contained in either argument doclist). If the docids in the
120975 ** input doclists are sorted in ascending order, parameter bDescDoclist
120976 ** should be false. If they are sorted in ascending order, it should be
120977 ** passed a non-zero value.
120978 **
120979 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
120980 ** containing the output doclist and SQLITE_OK is returned. In this case
120981 ** *pnOut is set to the number of bytes in the output doclist.
120982 **
120983 ** If an error occurs, an SQLite error code is returned. The output values
120984 ** are undefined in this case.
120985 */
120986 static int fts3DoclistOrMerge(
120987   int bDescDoclist,               /* True if arguments are desc */
120988   char *a1, int n1,               /* First doclist */
120989   char *a2, int n2,               /* Second doclist */
120990   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
120991 ){
120992   sqlite3_int64 i1 = 0;
120993   sqlite3_int64 i2 = 0;
120994   sqlite3_int64 iPrev = 0;
120995   char *pEnd1 = &a1[n1];
120996   char *pEnd2 = &a2[n2];
120997   char *p1 = a1;
120998   char *p2 = a2;
120999   char *p;
121000   char *aOut;
121001   int bFirstOut = 0;
121002
121003   *paOut = 0;
121004   *pnOut = 0;
121005
121006   /* Allocate space for the output. Both the input and output doclists
121007   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
121008   ** then the first docid in each list is simply encoded as a varint. For
121009   ** each subsequent docid, the varint stored is the difference between the
121010   ** current and previous docid (a positive number - since the list is in
121011   ** ascending order).
121012   **
121013   ** The first docid written to the output is therefore encoded using the
121014   ** same number of bytes as it is in whichever of the input lists it is
121015   ** read from. And each subsequent docid read from the same input list
121016   ** consumes either the same or less bytes as it did in the input (since
121017   ** the difference between it and the previous value in the output must
121018   ** be a positive value less than or equal to the delta value read from
121019   ** the input list). The same argument applies to all but the first docid
121020   ** read from the 'other' list. And to the contents of all position lists
121021   ** that will be copied and merged from the input to the output.
121022   **
121023   ** However, if the first docid copied to the output is a negative number,
121024   ** then the encoding of the first docid from the 'other' input list may
121025   ** be larger in the output than it was in the input (since the delta value
121026   ** may be a larger positive integer than the actual docid).
121027   **
121028   ** The space required to store the output is therefore the sum of the
121029   ** sizes of the two inputs, plus enough space for exactly one of the input
121030   ** docids to grow.
121031   **
121032   ** A symetric argument may be made if the doclists are in descending
121033   ** order.
121034   */
121035   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
121036   if( !aOut ) return SQLITE_NOMEM;
121037
121038   p = aOut;
121039   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
121040   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
121041   while( p1 || p2 ){
121042     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
121043
121044     if( p2 && p1 && iDiff==0 ){
121045       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121046       fts3PoslistMerge(&p, &p1, &p2);
121047       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121048       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121049     }else if( !p2 || (p1 && iDiff<0) ){
121050       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121051       fts3PoslistCopy(&p, &p1);
121052       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121053     }else{
121054       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
121055       fts3PoslistCopy(&p, &p2);
121056       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121057     }
121058   }
121059
121060   *paOut = aOut;
121061   *pnOut = (int)(p-aOut);
121062   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
121063   return SQLITE_OK;
121064 }
121065
121066 /*
121067 ** This function does a "phrase" merge of two doclists. In a phrase merge,
121068 ** the output contains a copy of each position from the right-hand input
121069 ** doclist for which there is a position in the left-hand input doclist
121070 ** exactly nDist tokens before it.
121071 **
121072 ** If the docids in the input doclists are sorted in ascending order,
121073 ** parameter bDescDoclist should be false. If they are sorted in ascending
121074 ** order, it should be passed a non-zero value.
121075 **
121076 ** The right-hand input doclist is overwritten by this function.
121077 */
121078 static void fts3DoclistPhraseMerge(
121079   int bDescDoclist,               /* True if arguments are desc */
121080   int nDist,                      /* Distance from left to right (1=adjacent) */
121081   char *aLeft, int nLeft,         /* Left doclist */
121082   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
121083 ){
121084   sqlite3_int64 i1 = 0;
121085   sqlite3_int64 i2 = 0;
121086   sqlite3_int64 iPrev = 0;
121087   char *pEnd1 = &aLeft[nLeft];
121088   char *pEnd2 = &aRight[*pnRight];
121089   char *p1 = aLeft;
121090   char *p2 = aRight;
121091   char *p;
121092   int bFirstOut = 0;
121093   char *aOut = aRight;
121094
121095   assert( nDist>0 );
121096
121097   p = aOut;
121098   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
121099   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
121100
121101   while( p1 && p2 ){
121102     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
121103     if( iDiff==0 ){
121104       char *pSave = p;
121105       sqlite3_int64 iPrevSave = iPrev;
121106       int bFirstOutSave = bFirstOut;
121107
121108       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121109       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
121110         p = pSave;
121111         iPrev = iPrevSave;
121112         bFirstOut = bFirstOutSave;
121113       }
121114       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121115       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121116     }else if( iDiff<0 ){
121117       fts3PoslistCopy(0, &p1);
121118       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121119     }else{
121120       fts3PoslistCopy(0, &p2);
121121       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121122     }
121123   }
121124
121125   *pnRight = (int)(p - aOut);
121126 }
121127
121128 /*
121129 ** Argument pList points to a position list nList bytes in size. This
121130 ** function checks to see if the position list contains any entries for
121131 ** a token in position 0 (of any column). If so, it writes argument iDelta
121132 ** to the output buffer pOut, followed by a position list consisting only
121133 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
121134 ** The value returned is the number of bytes written to pOut (if any).
121135 */
121136 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
121137   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
121138   char *pList,                    /* Position list (no 0x00 term) */
121139   int nList,                      /* Size of pList in bytes */
121140   char *pOut                      /* Write output here */
121141 ){
121142   int nOut = 0;
121143   int bWritten = 0;               /* True once iDelta has been written */
121144   char *p = pList;
121145   char *pEnd = &pList[nList];
121146
121147   if( *p!=0x01 ){
121148     if( *p==0x02 ){
121149       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
121150       pOut[nOut++] = 0x02;
121151       bWritten = 1;
121152     }
121153     fts3ColumnlistCopy(0, &p);
121154   }
121155
121156   while( p<pEnd && *p==0x01 ){
121157     sqlite3_int64 iCol;
121158     p++;
121159     p += sqlite3Fts3GetVarint(p, &iCol);
121160     if( *p==0x02 ){
121161       if( bWritten==0 ){
121162         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
121163         bWritten = 1;
121164       }
121165       pOut[nOut++] = 0x01;
121166       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
121167       pOut[nOut++] = 0x02;
121168     }
121169     fts3ColumnlistCopy(0, &p);
121170   }
121171   if( bWritten ){
121172     pOut[nOut++] = 0x00;
121173   }
121174
121175   return nOut;
121176 }
121177
121178
121179 /*
121180 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
121181 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
121182 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
121183 **
121184 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
121185 ** the responsibility of the caller to free any doclists left in the
121186 ** TermSelect.aaOutput[] array.
121187 */
121188 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
121189   char *aOut = 0;
121190   int nOut = 0;
121191   int i;
121192
121193   /* Loop through the doclists in the aaOutput[] array. Merge them all
121194   ** into a single doclist.
121195   */
121196   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
121197     if( pTS->aaOutput[i] ){
121198       if( !aOut ){
121199         aOut = pTS->aaOutput[i];
121200         nOut = pTS->anOutput[i];
121201         pTS->aaOutput[i] = 0;
121202       }else{
121203         int nNew;
121204         char *aNew;
121205
121206         int rc = fts3DoclistOrMerge(p->bDescIdx,
121207             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
121208         );
121209         if( rc!=SQLITE_OK ){
121210           sqlite3_free(aOut);
121211           return rc;
121212         }
121213
121214         sqlite3_free(pTS->aaOutput[i]);
121215         sqlite3_free(aOut);
121216         pTS->aaOutput[i] = 0;
121217         aOut = aNew;
121218         nOut = nNew;
121219       }
121220     }
121221   }
121222
121223   pTS->aaOutput[0] = aOut;
121224   pTS->anOutput[0] = nOut;
121225   return SQLITE_OK;
121226 }
121227
121228 /*
121229 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
121230 ** as the first argument. The merge is an "OR" merge (see function
121231 ** fts3DoclistOrMerge() for details).
121232 **
121233 ** This function is called with the doclist for each term that matches
121234 ** a queried prefix. It merges all these doclists into one, the doclist
121235 ** for the specified prefix. Since there can be a very large number of
121236 ** doclists to merge, the merging is done pair-wise using the TermSelect
121237 ** object.
121238 **
121239 ** This function returns SQLITE_OK if the merge is successful, or an
121240 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
121241 */
121242 static int fts3TermSelectMerge(
121243   Fts3Table *p,                   /* FTS table handle */
121244   TermSelect *pTS,                /* TermSelect object to merge into */
121245   char *aDoclist,                 /* Pointer to doclist */
121246   int nDoclist                    /* Size of aDoclist in bytes */
121247 ){
121248   if( pTS->aaOutput[0]==0 ){
121249     /* If this is the first term selected, copy the doclist to the output
121250     ** buffer using memcpy(). */
121251     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
121252     pTS->anOutput[0] = nDoclist;
121253     if( pTS->aaOutput[0] ){
121254       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
121255     }else{
121256       return SQLITE_NOMEM;
121257     }
121258   }else{
121259     char *aMerge = aDoclist;
121260     int nMerge = nDoclist;
121261     int iOut;
121262
121263     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
121264       if( pTS->aaOutput[iOut]==0 ){
121265         assert( iOut>0 );
121266         pTS->aaOutput[iOut] = aMerge;
121267         pTS->anOutput[iOut] = nMerge;
121268         break;
121269       }else{
121270         char *aNew;
121271         int nNew;
121272
121273         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
121274             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
121275         );
121276         if( rc!=SQLITE_OK ){
121277           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
121278           return rc;
121279         }
121280
121281         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
121282         sqlite3_free(pTS->aaOutput[iOut]);
121283         pTS->aaOutput[iOut] = 0;
121284
121285         aMerge = aNew;
121286         nMerge = nNew;
121287         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
121288           pTS->aaOutput[iOut] = aMerge;
121289           pTS->anOutput[iOut] = nMerge;
121290         }
121291       }
121292     }
121293   }
121294   return SQLITE_OK;
121295 }
121296
121297 /*
121298 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
121299 */
121300 static int fts3SegReaderCursorAppend(
121301   Fts3MultiSegReader *pCsr,
121302   Fts3SegReader *pNew
121303 ){
121304   if( (pCsr->nSegment%16)==0 ){
121305     Fts3SegReader **apNew;
121306     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
121307     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
121308     if( !apNew ){
121309       sqlite3Fts3SegReaderFree(pNew);
121310       return SQLITE_NOMEM;
121311     }
121312     pCsr->apSegment = apNew;
121313   }
121314   pCsr->apSegment[pCsr->nSegment++] = pNew;
121315   return SQLITE_OK;
121316 }
121317
121318 /*
121319 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
121320 ** 8th argument.
121321 **
121322 ** This function returns SQLITE_OK if successful, or an SQLite error code
121323 ** otherwise.
121324 */
121325 static int fts3SegReaderCursor(
121326   Fts3Table *p,                   /* FTS3 table handle */
121327   int iLangid,                    /* Language id */
121328   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
121329   int iLevel,                     /* Level of segments to scan */
121330   const char *zTerm,              /* Term to query for */
121331   int nTerm,                      /* Size of zTerm in bytes */
121332   int isPrefix,                   /* True for a prefix search */
121333   int isScan,                     /* True to scan from zTerm to EOF */
121334   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
121335 ){
121336   int rc = SQLITE_OK;             /* Error code */
121337   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
121338   int rc2;                        /* Result of sqlite3_reset() */
121339
121340   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
121341   ** for the pending-terms. If this is a scan, then this call must be being
121342   ** made by an fts4aux module, not an FTS table. In this case calling
121343   ** Fts3SegReaderPending might segfault, as the data structures used by
121344   ** fts4aux are not completely populated. So it's easiest to filter these
121345   ** calls out here.  */
121346   if( iLevel<0 && p->aIndex ){
121347     Fts3SegReader *pSeg = 0;
121348     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
121349     if( rc==SQLITE_OK && pSeg ){
121350       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
121351     }
121352   }
121353
121354   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
121355     if( rc==SQLITE_OK ){
121356       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
121357     }
121358
121359     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
121360       Fts3SegReader *pSeg = 0;
121361
121362       /* Read the values returned by the SELECT into local variables. */
121363       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
121364       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
121365       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
121366       int nRoot = sqlite3_column_bytes(pStmt, 4);
121367       char const *zRoot = sqlite3_column_blob(pStmt, 4);
121368
121369       /* If zTerm is not NULL, and this segment is not stored entirely on its
121370       ** root node, the range of leaves scanned can be reduced. Do this. */
121371       if( iStartBlock && zTerm ){
121372         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
121373         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
121374         if( rc!=SQLITE_OK ) goto finished;
121375         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
121376       }
121377
121378       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
121379           (isPrefix==0 && isScan==0),
121380           iStartBlock, iLeavesEndBlock,
121381           iEndBlock, zRoot, nRoot, &pSeg
121382       );
121383       if( rc!=SQLITE_OK ) goto finished;
121384       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
121385     }
121386   }
121387
121388  finished:
121389   rc2 = sqlite3_reset(pStmt);
121390   if( rc==SQLITE_DONE ) rc = rc2;
121391
121392   return rc;
121393 }
121394
121395 /*
121396 ** Set up a cursor object for iterating through a full-text index or a
121397 ** single level therein.
121398 */
121399 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
121400   Fts3Table *p,                   /* FTS3 table handle */
121401   int iLangid,                    /* Language-id to search */
121402   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
121403   int iLevel,                     /* Level of segments to scan */
121404   const char *zTerm,              /* Term to query for */
121405   int nTerm,                      /* Size of zTerm in bytes */
121406   int isPrefix,                   /* True for a prefix search */
121407   int isScan,                     /* True to scan from zTerm to EOF */
121408   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
121409 ){
121410   assert( iIndex>=0 && iIndex<p->nIndex );
121411   assert( iLevel==FTS3_SEGCURSOR_ALL
121412       ||  iLevel==FTS3_SEGCURSOR_PENDING
121413       ||  iLevel>=0
121414   );
121415   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
121416   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
121417   assert( isPrefix==0 || isScan==0 );
121418
121419   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
121420   return fts3SegReaderCursor(
121421       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
121422   );
121423 }
121424
121425 /*
121426 ** In addition to its current configuration, have the Fts3MultiSegReader
121427 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
121428 **
121429 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121430 */
121431 static int fts3SegReaderCursorAddZero(
121432   Fts3Table *p,                   /* FTS virtual table handle */
121433   int iLangid,
121434   const char *zTerm,              /* Term to scan doclist of */
121435   int nTerm,                      /* Number of bytes in zTerm */
121436   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
121437 ){
121438   return fts3SegReaderCursor(p,
121439       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
121440   );
121441 }
121442
121443 /*
121444 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
121445 ** if isPrefix is true, to scan the doclist for all terms for which
121446 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
121447 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
121448 ** an SQLite error code.
121449 **
121450 ** It is the responsibility of the caller to free this object by eventually
121451 ** passing it to fts3SegReaderCursorFree()
121452 **
121453 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
121454 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
121455 */
121456 static int fts3TermSegReaderCursor(
121457   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
121458   const char *zTerm,              /* Term to query for */
121459   int nTerm,                      /* Size of zTerm in bytes */
121460   int isPrefix,                   /* True for a prefix search */
121461   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
121462 ){
121463   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
121464   int rc = SQLITE_NOMEM;          /* Return code */
121465
121466   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
121467   if( pSegcsr ){
121468     int i;
121469     int bFound = 0;               /* True once an index has been found */
121470     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
121471
121472     if( isPrefix ){
121473       for(i=1; bFound==0 && i<p->nIndex; i++){
121474         if( p->aIndex[i].nPrefix==nTerm ){
121475           bFound = 1;
121476           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
121477               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
121478           );
121479           pSegcsr->bLookup = 1;
121480         }
121481       }
121482
121483       for(i=1; bFound==0 && i<p->nIndex; i++){
121484         if( p->aIndex[i].nPrefix==nTerm+1 ){
121485           bFound = 1;
121486           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
121487               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
121488           );
121489           if( rc==SQLITE_OK ){
121490             rc = fts3SegReaderCursorAddZero(
121491                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
121492             );
121493           }
121494         }
121495       }
121496     }
121497
121498     if( bFound==0 ){
121499       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
121500           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
121501       );
121502       pSegcsr->bLookup = !isPrefix;
121503     }
121504   }
121505
121506   *ppSegcsr = pSegcsr;
121507   return rc;
121508 }
121509
121510 /*
121511 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
121512 */
121513 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
121514   sqlite3Fts3SegReaderFinish(pSegcsr);
121515   sqlite3_free(pSegcsr);
121516 }
121517
121518 /*
121519 ** This function retreives the doclist for the specified term (or term
121520 ** prefix) from the database.
121521 */
121522 static int fts3TermSelect(
121523   Fts3Table *p,                   /* Virtual table handle */
121524   Fts3PhraseToken *pTok,          /* Token to query for */
121525   int iColumn,                    /* Column to query (or -ve for all columns) */
121526   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
121527   char **ppOut                    /* OUT: Malloced result buffer */
121528 ){
121529   int rc;                         /* Return code */
121530   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
121531   TermSelect tsc;                 /* Object for pair-wise doclist merging */
121532   Fts3SegFilter filter;           /* Segment term filter configuration */
121533
121534   pSegcsr = pTok->pSegcsr;
121535   memset(&tsc, 0, sizeof(TermSelect));
121536
121537   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
121538         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
121539         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
121540         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
121541   filter.iCol = iColumn;
121542   filter.zTerm = pTok->z;
121543   filter.nTerm = pTok->n;
121544
121545   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
121546   while( SQLITE_OK==rc
121547       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
121548   ){
121549     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
121550   }
121551
121552   if( rc==SQLITE_OK ){
121553     rc = fts3TermSelectFinishMerge(p, &tsc);
121554   }
121555   if( rc==SQLITE_OK ){
121556     *ppOut = tsc.aaOutput[0];
121557     *pnOut = tsc.anOutput[0];
121558   }else{
121559     int i;
121560     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
121561       sqlite3_free(tsc.aaOutput[i]);
121562     }
121563   }
121564
121565   fts3SegReaderCursorFree(pSegcsr);
121566   pTok->pSegcsr = 0;
121567   return rc;
121568 }
121569
121570 /*
121571 ** This function counts the total number of docids in the doclist stored
121572 ** in buffer aList[], size nList bytes.
121573 **
121574 ** If the isPoslist argument is true, then it is assumed that the doclist
121575 ** contains a position-list following each docid. Otherwise, it is assumed
121576 ** that the doclist is simply a list of docids stored as delta encoded
121577 ** varints.
121578 */
121579 static int fts3DoclistCountDocids(char *aList, int nList){
121580   int nDoc = 0;                   /* Return value */
121581   if( aList ){
121582     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
121583     char *p = aList;              /* Cursor */
121584     while( p<aEnd ){
121585       nDoc++;
121586       while( (*p++)&0x80 );     /* Skip docid varint */
121587       fts3PoslistCopy(0, &p);   /* Skip over position list */
121588     }
121589   }
121590
121591   return nDoc;
121592 }
121593
121594 /*
121595 ** Advance the cursor to the next row in the %_content table that
121596 ** matches the search criteria.  For a MATCH search, this will be
121597 ** the next row that matches. For a full-table scan, this will be
121598 ** simply the next row in the %_content table.  For a docid lookup,
121599 ** this routine simply sets the EOF flag.
121600 **
121601 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
121602 ** even if we reach end-of-file.  The fts3EofMethod() will be called
121603 ** subsequently to determine whether or not an EOF was hit.
121604 */
121605 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
121606   int rc;
121607   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
121608   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
121609     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
121610       pCsr->isEof = 1;
121611       rc = sqlite3_reset(pCsr->pStmt);
121612     }else{
121613       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
121614       rc = SQLITE_OK;
121615     }
121616   }else{
121617     rc = fts3EvalNext((Fts3Cursor *)pCursor);
121618   }
121619   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
121620   return rc;
121621 }
121622
121623 /*
121624 ** This is the xFilter interface for the virtual table.  See
121625 ** the virtual table xFilter method documentation for additional
121626 ** information.
121627 **
121628 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
121629 ** the %_content table.
121630 **
121631 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
121632 ** in the %_content table.
121633 **
121634 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
121635 ** column on the left-hand side of the MATCH operator is column
121636 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
121637 ** side of the MATCH operator.
121638 */
121639 static int fts3FilterMethod(
121640   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
121641   int idxNum,                     /* Strategy index */
121642   const char *idxStr,             /* Unused */
121643   int nVal,                       /* Number of elements in apVal */
121644   sqlite3_value **apVal           /* Arguments for the indexing scheme */
121645 ){
121646   int rc;
121647   char *zSql;                     /* SQL statement used to access %_content */
121648   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
121649   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
121650
121651   UNUSED_PARAMETER(idxStr);
121652   UNUSED_PARAMETER(nVal);
121653
121654   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
121655   assert( nVal==0 || nVal==1 || nVal==2 );
121656   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
121657   assert( p->pSegments==0 );
121658
121659   /* In case the cursor has been used before, clear it now. */
121660   sqlite3_finalize(pCsr->pStmt);
121661   sqlite3_free(pCsr->aDoclist);
121662   sqlite3Fts3ExprFree(pCsr->pExpr);
121663   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
121664
121665   if( idxStr ){
121666     pCsr->bDesc = (idxStr[0]=='D');
121667   }else{
121668     pCsr->bDesc = p->bDescIdx;
121669   }
121670   pCsr->eSearch = (i16)idxNum;
121671
121672   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
121673     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
121674     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
121675
121676     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
121677       return SQLITE_NOMEM;
121678     }
121679
121680     pCsr->iLangid = 0;
121681     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
121682
121683     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
121684         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
121685     );
121686     if( rc!=SQLITE_OK ){
121687       if( rc==SQLITE_ERROR ){
121688         static const char *zErr = "malformed MATCH expression: [%s]";
121689         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
121690       }
121691       return rc;
121692     }
121693
121694     rc = sqlite3Fts3ReadLock(p);
121695     if( rc!=SQLITE_OK ) return rc;
121696
121697     rc = fts3EvalStart(pCsr);
121698
121699     sqlite3Fts3SegmentsClose(p);
121700     if( rc!=SQLITE_OK ) return rc;
121701     pCsr->pNextId = pCsr->aDoclist;
121702     pCsr->iPrevId = 0;
121703   }
121704
121705   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
121706   ** statement loops through all rows of the %_content table. For a
121707   ** full-text query or docid lookup, the statement retrieves a single
121708   ** row by docid.
121709   */
121710   if( idxNum==FTS3_FULLSCAN_SEARCH ){
121711     zSql = sqlite3_mprintf(
121712         "SELECT %s ORDER BY rowid %s",
121713         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
121714     );
121715     if( zSql ){
121716       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
121717       sqlite3_free(zSql);
121718     }else{
121719       rc = SQLITE_NOMEM;
121720     }
121721   }else if( idxNum==FTS3_DOCID_SEARCH ){
121722     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
121723     if( rc==SQLITE_OK ){
121724       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
121725     }
121726   }
121727   if( rc!=SQLITE_OK ) return rc;
121728
121729   return fts3NextMethod(pCursor);
121730 }
121731
121732 /*
121733 ** This is the xEof method of the virtual table. SQLite calls this
121734 ** routine to find out if it has reached the end of a result set.
121735 */
121736 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
121737   return ((Fts3Cursor *)pCursor)->isEof;
121738 }
121739
121740 /*
121741 ** This is the xRowid method. The SQLite core calls this routine to
121742 ** retrieve the rowid for the current row of the result set. fts3
121743 ** exposes %_content.docid as the rowid for the virtual table. The
121744 ** rowid should be written to *pRowid.
121745 */
121746 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
121747   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
121748   *pRowid = pCsr->iPrevId;
121749   return SQLITE_OK;
121750 }
121751
121752 /*
121753 ** This is the xColumn method, called by SQLite to request a value from
121754 ** the row that the supplied cursor currently points to.
121755 **
121756 ** If:
121757 **
121758 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
121759 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
121760 **   (iCol == p->nColumn+1) -> Docid column
121761 **   (iCol == p->nColumn+2) -> Langid column
121762 */
121763 static int fts3ColumnMethod(
121764   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
121765   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
121766   int iCol                        /* Index of column to read value from */
121767 ){
121768   int rc = SQLITE_OK;             /* Return Code */
121769   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
121770   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
121771
121772   /* The column value supplied by SQLite must be in range. */
121773   assert( iCol>=0 && iCol<=p->nColumn+2 );
121774
121775   if( iCol==p->nColumn+1 ){
121776     /* This call is a request for the "docid" column. Since "docid" is an
121777     ** alias for "rowid", use the xRowid() method to obtain the value.
121778     */
121779     sqlite3_result_int64(pCtx, pCsr->iPrevId);
121780   }else if( iCol==p->nColumn ){
121781     /* The extra column whose name is the same as the table.
121782     ** Return a blob which is a pointer to the cursor.  */
121783     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
121784   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
121785     sqlite3_result_int64(pCtx, pCsr->iLangid);
121786   }else{
121787     /* The requested column is either a user column (one that contains
121788     ** indexed data), or the language-id column.  */
121789     rc = fts3CursorSeek(0, pCsr);
121790
121791     if( rc==SQLITE_OK ){
121792       if( iCol==p->nColumn+2 ){
121793         int iLangid = 0;
121794         if( p->zLanguageid ){
121795           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
121796         }
121797         sqlite3_result_int(pCtx, iLangid);
121798       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
121799         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
121800       }
121801     }
121802   }
121803
121804   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
121805   return rc;
121806 }
121807
121808 /*
121809 ** This function is the implementation of the xUpdate callback used by
121810 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
121811 ** inserted, updated or deleted.
121812 */
121813 static int fts3UpdateMethod(
121814   sqlite3_vtab *pVtab,            /* Virtual table handle */
121815   int nArg,                       /* Size of argument array */
121816   sqlite3_value **apVal,          /* Array of arguments */
121817   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
121818 ){
121819   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
121820 }
121821
121822 /*
121823 ** Implementation of xSync() method. Flush the contents of the pending-terms
121824 ** hash-table to the database.
121825 */
121826 static int fts3SyncMethod(sqlite3_vtab *pVtab){
121827
121828   /* Following an incremental-merge operation, assuming that the input
121829   ** segments are not completely consumed (the usual case), they are updated
121830   ** in place to remove the entries that have already been merged. This
121831   ** involves updating the leaf block that contains the smallest unmerged
121832   ** entry and each block (if any) between the leaf and the root node. So
121833   ** if the height of the input segment b-trees is N, and input segments
121834   ** are merged eight at a time, updating the input segments at the end
121835   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
121836   ** small - often between 0 and 2. So the overhead of the incremental
121837   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
121838   ** dwarfing the actual productive work accomplished, the incremental merge
121839   ** is only attempted if it will write at least 64 leaf blocks. Hence
121840   ** nMinMerge.
121841   **
121842   ** Of course, updating the input segments also involves deleting a bunch
121843   ** of blocks from the segments table. But this is not considered overhead
121844   ** as it would also be required by a crisis-merge that used the same input
121845   ** segments.
121846   */
121847   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
121848
121849   Fts3Table *p = (Fts3Table*)pVtab;
121850   int rc = sqlite3Fts3PendingTermsFlush(p);
121851
121852   if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
121853     int mxLevel = 0;              /* Maximum relative level value in db */
121854     int A;                        /* Incr-merge parameter A */
121855
121856     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
121857     assert( rc==SQLITE_OK || mxLevel==0 );
121858     A = p->nLeafAdd * mxLevel;
121859     A += (A/2);
121860     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
121861   }
121862   sqlite3Fts3SegmentsClose(p);
121863   return rc;
121864 }
121865
121866 /*
121867 ** Implementation of xBegin() method. This is a no-op.
121868 */
121869 static int fts3BeginMethod(sqlite3_vtab *pVtab){
121870   Fts3Table *p = (Fts3Table*)pVtab;
121871   UNUSED_PARAMETER(pVtab);
121872   assert( p->pSegments==0 );
121873   assert( p->nPendingData==0 );
121874   assert( p->inTransaction!=1 );
121875   TESTONLY( p->inTransaction = 1 );
121876   TESTONLY( p->mxSavepoint = -1; );
121877   p->nLeafAdd = 0;
121878   return SQLITE_OK;
121879 }
121880
121881 /*
121882 ** Implementation of xCommit() method. This is a no-op. The contents of
121883 ** the pending-terms hash-table have already been flushed into the database
121884 ** by fts3SyncMethod().
121885 */
121886 static int fts3CommitMethod(sqlite3_vtab *pVtab){
121887   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
121888   UNUSED_PARAMETER(pVtab);
121889   assert( p->nPendingData==0 );
121890   assert( p->inTransaction!=0 );
121891   assert( p->pSegments==0 );
121892   TESTONLY( p->inTransaction = 0 );
121893   TESTONLY( p->mxSavepoint = -1; );
121894   return SQLITE_OK;
121895 }
121896
121897 /*
121898 ** Implementation of xRollback(). Discard the contents of the pending-terms
121899 ** hash-table. Any changes made to the database are reverted by SQLite.
121900 */
121901 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
121902   Fts3Table *p = (Fts3Table*)pVtab;
121903   sqlite3Fts3PendingTermsClear(p);
121904   assert( p->inTransaction!=0 );
121905   TESTONLY( p->inTransaction = 0 );
121906   TESTONLY( p->mxSavepoint = -1; );
121907   return SQLITE_OK;
121908 }
121909
121910 /*
121911 ** When called, *ppPoslist must point to the byte immediately following the
121912 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
121913 ** moves *ppPoslist so that it instead points to the first byte of the
121914 ** same position list.
121915 */
121916 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
121917   char *p = &(*ppPoslist)[-2];
121918   char c = 0;
121919
121920   while( p>pStart && (c=*p--)==0 );
121921   while( p>pStart && (*p & 0x80) | c ){
121922     c = *p--;
121923   }
121924   if( p>pStart ){ p = &p[2]; }
121925   while( *p++&0x80 );
121926   *ppPoslist = p;
121927 }
121928
121929 /*
121930 ** Helper function used by the implementation of the overloaded snippet(),
121931 ** offsets() and optimize() SQL functions.
121932 **
121933 ** If the value passed as the third argument is a blob of size
121934 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
121935 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
121936 ** message is written to context pContext and SQLITE_ERROR returned. The
121937 ** string passed via zFunc is used as part of the error message.
121938 */
121939 static int fts3FunctionArg(
121940   sqlite3_context *pContext,      /* SQL function call context */
121941   const char *zFunc,              /* Function name */
121942   sqlite3_value *pVal,            /* argv[0] passed to function */
121943   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
121944 ){
121945   Fts3Cursor *pRet;
121946   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
121947    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
121948   ){
121949     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
121950     sqlite3_result_error(pContext, zErr, -1);
121951     sqlite3_free(zErr);
121952     return SQLITE_ERROR;
121953   }
121954   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
121955   *ppCsr = pRet;
121956   return SQLITE_OK;
121957 }
121958
121959 /*
121960 ** Implementation of the snippet() function for FTS3
121961 */
121962 static void fts3SnippetFunc(
121963   sqlite3_context *pContext,      /* SQLite function call context */
121964   int nVal,                       /* Size of apVal[] array */
121965   sqlite3_value **apVal           /* Array of arguments */
121966 ){
121967   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
121968   const char *zStart = "<b>";
121969   const char *zEnd = "</b>";
121970   const char *zEllipsis = "<b>...</b>";
121971   int iCol = -1;
121972   int nToken = 15;                /* Default number of tokens in snippet */
121973
121974   /* There must be at least one argument passed to this function (otherwise
121975   ** the non-overloaded version would have been called instead of this one).
121976   */
121977   assert( nVal>=1 );
121978
121979   if( nVal>6 ){
121980     sqlite3_result_error(pContext,
121981         "wrong number of arguments to function snippet()", -1);
121982     return;
121983   }
121984   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
121985
121986   switch( nVal ){
121987     case 6: nToken = sqlite3_value_int(apVal[5]);
121988     case 5: iCol = sqlite3_value_int(apVal[4]);
121989     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
121990     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
121991     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
121992   }
121993   if( !zEllipsis || !zEnd || !zStart ){
121994     sqlite3_result_error_nomem(pContext);
121995   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
121996     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
121997   }
121998 }
121999
122000 /*
122001 ** Implementation of the offsets() function for FTS3
122002 */
122003 static void fts3OffsetsFunc(
122004   sqlite3_context *pContext,      /* SQLite function call context */
122005   int nVal,                       /* Size of argument array */
122006   sqlite3_value **apVal           /* Array of arguments */
122007 ){
122008   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122009
122010   UNUSED_PARAMETER(nVal);
122011
122012   assert( nVal==1 );
122013   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
122014   assert( pCsr );
122015   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
122016     sqlite3Fts3Offsets(pContext, pCsr);
122017   }
122018 }
122019
122020 /*
122021 ** Implementation of the special optimize() function for FTS3. This
122022 ** function merges all segments in the database to a single segment.
122023 ** Example usage is:
122024 **
122025 **   SELECT optimize(t) FROM t LIMIT 1;
122026 **
122027 ** where 't' is the name of an FTS3 table.
122028 */
122029 static void fts3OptimizeFunc(
122030   sqlite3_context *pContext,      /* SQLite function call context */
122031   int nVal,                       /* Size of argument array */
122032   sqlite3_value **apVal           /* Array of arguments */
122033 ){
122034   int rc;                         /* Return code */
122035   Fts3Table *p;                   /* Virtual table handle */
122036   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
122037
122038   UNUSED_PARAMETER(nVal);
122039
122040   assert( nVal==1 );
122041   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
122042   p = (Fts3Table *)pCursor->base.pVtab;
122043   assert( p );
122044
122045   rc = sqlite3Fts3Optimize(p);
122046
122047   switch( rc ){
122048     case SQLITE_OK:
122049       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
122050       break;
122051     case SQLITE_DONE:
122052       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
122053       break;
122054     default:
122055       sqlite3_result_error_code(pContext, rc);
122056       break;
122057   }
122058 }
122059
122060 /*
122061 ** Implementation of the matchinfo() function for FTS3
122062 */
122063 static void fts3MatchinfoFunc(
122064   sqlite3_context *pContext,      /* SQLite function call context */
122065   int nVal,                       /* Size of argument array */
122066   sqlite3_value **apVal           /* Array of arguments */
122067 ){
122068   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122069   assert( nVal==1 || nVal==2 );
122070   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
122071     const char *zArg = 0;
122072     if( nVal>1 ){
122073       zArg = (const char *)sqlite3_value_text(apVal[1]);
122074     }
122075     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
122076   }
122077 }
122078
122079 /*
122080 ** This routine implements the xFindFunction method for the FTS3
122081 ** virtual table.
122082 */
122083 static int fts3FindFunctionMethod(
122084   sqlite3_vtab *pVtab,            /* Virtual table handle */
122085   int nArg,                       /* Number of SQL function arguments */
122086   const char *zName,              /* Name of SQL function */
122087   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
122088   void **ppArg                    /* Unused */
122089 ){
122090   struct Overloaded {
122091     const char *zName;
122092     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
122093   } aOverload[] = {
122094     { "snippet", fts3SnippetFunc },
122095     { "offsets", fts3OffsetsFunc },
122096     { "optimize", fts3OptimizeFunc },
122097     { "matchinfo", fts3MatchinfoFunc },
122098   };
122099   int i;                          /* Iterator variable */
122100
122101   UNUSED_PARAMETER(pVtab);
122102   UNUSED_PARAMETER(nArg);
122103   UNUSED_PARAMETER(ppArg);
122104
122105   for(i=0; i<SizeofArray(aOverload); i++){
122106     if( strcmp(zName, aOverload[i].zName)==0 ){
122107       *pxFunc = aOverload[i].xFunc;
122108       return 1;
122109     }
122110   }
122111
122112   /* No function of the specified name was found. Return 0. */
122113   return 0;
122114 }
122115
122116 /*
122117 ** Implementation of FTS3 xRename method. Rename an fts3 table.
122118 */
122119 static int fts3RenameMethod(
122120   sqlite3_vtab *pVtab,            /* Virtual table handle */
122121   const char *zName               /* New name of table */
122122 ){
122123   Fts3Table *p = (Fts3Table *)pVtab;
122124   sqlite3 *db = p->db;            /* Database connection */
122125   int rc;                         /* Return Code */
122126
122127   /* As it happens, the pending terms table is always empty here. This is
122128   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
122129   ** always opens a savepoint transaction. And the xSavepoint() method
122130   ** flushes the pending terms table. But leave the (no-op) call to
122131   ** PendingTermsFlush() in in case that changes.
122132   */
122133   assert( p->nPendingData==0 );
122134   rc = sqlite3Fts3PendingTermsFlush(p);
122135
122136   if( p->zContentTbl==0 ){
122137     fts3DbExec(&rc, db,
122138       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
122139       p->zDb, p->zName, zName
122140     );
122141   }
122142
122143   if( p->bHasDocsize ){
122144     fts3DbExec(&rc, db,
122145       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
122146       p->zDb, p->zName, zName
122147     );
122148   }
122149   if( p->bHasStat ){
122150     fts3DbExec(&rc, db,
122151       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
122152       p->zDb, p->zName, zName
122153     );
122154   }
122155   fts3DbExec(&rc, db,
122156     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
122157     p->zDb, p->zName, zName
122158   );
122159   fts3DbExec(&rc, db,
122160     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
122161     p->zDb, p->zName, zName
122162   );
122163   return rc;
122164 }
122165
122166 /*
122167 ** The xSavepoint() method.
122168 **
122169 ** Flush the contents of the pending-terms table to disk.
122170 */
122171 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
122172   int rc = SQLITE_OK;
122173   UNUSED_PARAMETER(iSavepoint);
122174   assert( ((Fts3Table *)pVtab)->inTransaction );
122175   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
122176   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
122177   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
122178     rc = fts3SyncMethod(pVtab);
122179   }
122180   return rc;
122181 }
122182
122183 /*
122184 ** The xRelease() method.
122185 **
122186 ** This is a no-op.
122187 */
122188 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
122189   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
122190   UNUSED_PARAMETER(iSavepoint);
122191   UNUSED_PARAMETER(pVtab);
122192   assert( p->inTransaction );
122193   assert( p->mxSavepoint >= iSavepoint );
122194   TESTONLY( p->mxSavepoint = iSavepoint-1 );
122195   return SQLITE_OK;
122196 }
122197
122198 /*
122199 ** The xRollbackTo() method.
122200 **
122201 ** Discard the contents of the pending terms table.
122202 */
122203 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
122204   Fts3Table *p = (Fts3Table*)pVtab;
122205   UNUSED_PARAMETER(iSavepoint);
122206   assert( p->inTransaction );
122207   assert( p->mxSavepoint >= iSavepoint );
122208   TESTONLY( p->mxSavepoint = iSavepoint );
122209   sqlite3Fts3PendingTermsClear(p);
122210   return SQLITE_OK;
122211 }
122212
122213 static const sqlite3_module fts3Module = {
122214   /* iVersion      */ 2,
122215   /* xCreate       */ fts3CreateMethod,
122216   /* xConnect      */ fts3ConnectMethod,
122217   /* xBestIndex    */ fts3BestIndexMethod,
122218   /* xDisconnect   */ fts3DisconnectMethod,
122219   /* xDestroy      */ fts3DestroyMethod,
122220   /* xOpen         */ fts3OpenMethod,
122221   /* xClose        */ fts3CloseMethod,
122222   /* xFilter       */ fts3FilterMethod,
122223   /* xNext         */ fts3NextMethod,
122224   /* xEof          */ fts3EofMethod,
122225   /* xColumn       */ fts3ColumnMethod,
122226   /* xRowid        */ fts3RowidMethod,
122227   /* xUpdate       */ fts3UpdateMethod,
122228   /* xBegin        */ fts3BeginMethod,
122229   /* xSync         */ fts3SyncMethod,
122230   /* xCommit       */ fts3CommitMethod,
122231   /* xRollback     */ fts3RollbackMethod,
122232   /* xFindFunction */ fts3FindFunctionMethod,
122233   /* xRename */       fts3RenameMethod,
122234   /* xSavepoint    */ fts3SavepointMethod,
122235   /* xRelease      */ fts3ReleaseMethod,
122236   /* xRollbackTo   */ fts3RollbackToMethod,
122237 };
122238
122239 /*
122240 ** This function is registered as the module destructor (called when an
122241 ** FTS3 enabled database connection is closed). It frees the memory
122242 ** allocated for the tokenizer hash table.
122243 */
122244 static void hashDestroy(void *p){
122245   Fts3Hash *pHash = (Fts3Hash *)p;
122246   sqlite3Fts3HashClear(pHash);
122247   sqlite3_free(pHash);
122248 }
122249
122250 /*
122251 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
122252 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
122253 ** respectively. The following three forward declarations are for functions
122254 ** declared in these files used to retrieve the respective implementations.
122255 **
122256 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
122257 ** to by the argument to point to the "simple" tokenizer implementation.
122258 ** And so on.
122259 */
122260 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122261 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122262 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122263 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
122264 #endif
122265 #ifdef SQLITE_ENABLE_ICU
122266 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122267 #endif
122268
122269 /*
122270 ** Initialise the fts3 extension. If this extension is built as part
122271 ** of the sqlite library, then this function is called directly by
122272 ** SQLite. If fts3 is built as a dynamically loadable extension, this
122273 ** function is called by the sqlite3_extension_init() entry point.
122274 */
122275 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
122276   int rc = SQLITE_OK;
122277   Fts3Hash *pHash = 0;
122278   const sqlite3_tokenizer_module *pSimple = 0;
122279   const sqlite3_tokenizer_module *pPorter = 0;
122280 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122281   const sqlite3_tokenizer_module *pUnicode = 0;
122282 #endif
122283
122284 #ifdef SQLITE_ENABLE_ICU
122285   const sqlite3_tokenizer_module *pIcu = 0;
122286   sqlite3Fts3IcuTokenizerModule(&pIcu);
122287 #endif
122288
122289 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122290   sqlite3Fts3UnicodeTokenizer(&pUnicode);
122291 #endif
122292
122293 #ifdef SQLITE_TEST
122294   rc = sqlite3Fts3InitTerm(db);
122295   if( rc!=SQLITE_OK ) return rc;
122296 #endif
122297
122298   rc = sqlite3Fts3InitAux(db);
122299   if( rc!=SQLITE_OK ) return rc;
122300
122301   sqlite3Fts3SimpleTokenizerModule(&pSimple);
122302   sqlite3Fts3PorterTokenizerModule(&pPorter);
122303
122304   /* Allocate and initialise the hash-table used to store tokenizers. */
122305   pHash = sqlite3_malloc(sizeof(Fts3Hash));
122306   if( !pHash ){
122307     rc = SQLITE_NOMEM;
122308   }else{
122309     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
122310   }
122311
122312   /* Load the built-in tokenizers into the hash table */
122313   if( rc==SQLITE_OK ){
122314     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
122315      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
122316
122317 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122318      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
122319 #endif
122320 #ifdef SQLITE_ENABLE_ICU
122321      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
122322 #endif
122323     ){
122324       rc = SQLITE_NOMEM;
122325     }
122326   }
122327
122328 #ifdef SQLITE_TEST
122329   if( rc==SQLITE_OK ){
122330     rc = sqlite3Fts3ExprInitTestInterface(db);
122331   }
122332 #endif
122333
122334   /* Create the virtual table wrapper around the hash-table and overload
122335   ** the two scalar functions. If this is successful, register the
122336   ** module with sqlite.
122337   */
122338   if( SQLITE_OK==rc
122339    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
122340    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
122341    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
122342    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
122343    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
122344    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
122345   ){
122346     rc = sqlite3_create_module_v2(
122347         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
122348     );
122349     if( rc==SQLITE_OK ){
122350       rc = sqlite3_create_module_v2(
122351           db, "fts4", &fts3Module, (void *)pHash, 0
122352       );
122353     }
122354     return rc;
122355   }
122356
122357   /* An error has occurred. Delete the hash table and return the error code. */
122358   assert( rc!=SQLITE_OK );
122359   if( pHash ){
122360     sqlite3Fts3HashClear(pHash);
122361     sqlite3_free(pHash);
122362   }
122363   return rc;
122364 }
122365
122366 /*
122367 ** Allocate an Fts3MultiSegReader for each token in the expression headed
122368 ** by pExpr.
122369 **
122370 ** An Fts3SegReader object is a cursor that can seek or scan a range of
122371 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
122372 ** Fts3SegReader objects internally to provide an interface to seek or scan
122373 ** within the union of all segments of a b-tree. Hence the name.
122374 **
122375 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
122376 ** segment b-tree (if the term is not a prefix or it is a prefix for which
122377 ** there exists prefix b-tree of the right length) then it may be traversed
122378 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
122379 ** doclist and then traversed.
122380 */
122381 static void fts3EvalAllocateReaders(
122382   Fts3Cursor *pCsr,               /* FTS cursor handle */
122383   Fts3Expr *pExpr,                /* Allocate readers for this expression */
122384   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
122385   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
122386   int *pRc                        /* IN/OUT: Error code */
122387 ){
122388   if( pExpr && SQLITE_OK==*pRc ){
122389     if( pExpr->eType==FTSQUERY_PHRASE ){
122390       int i;
122391       int nToken = pExpr->pPhrase->nToken;
122392       *pnToken += nToken;
122393       for(i=0; i<nToken; i++){
122394         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
122395         int rc = fts3TermSegReaderCursor(pCsr,
122396             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
122397         );
122398         if( rc!=SQLITE_OK ){
122399           *pRc = rc;
122400           return;
122401         }
122402       }
122403       assert( pExpr->pPhrase->iDoclistToken==0 );
122404       pExpr->pPhrase->iDoclistToken = -1;
122405     }else{
122406       *pnOr += (pExpr->eType==FTSQUERY_OR);
122407       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
122408       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
122409     }
122410   }
122411 }
122412
122413 /*
122414 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
122415 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
122416 **
122417 ** This function assumes that pList points to a buffer allocated using
122418 ** sqlite3_malloc(). This function takes responsibility for eventually
122419 ** freeing the buffer.
122420 */
122421 static void fts3EvalPhraseMergeToken(
122422   Fts3Table *pTab,                /* FTS Table pointer */
122423   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
122424   int iToken,                     /* Token pList/nList corresponds to */
122425   char *pList,                    /* Pointer to doclist */
122426   int nList                       /* Number of bytes in pList */
122427 ){
122428   assert( iToken!=p->iDoclistToken );
122429
122430   if( pList==0 ){
122431     sqlite3_free(p->doclist.aAll);
122432     p->doclist.aAll = 0;
122433     p->doclist.nAll = 0;
122434   }
122435
122436   else if( p->iDoclistToken<0 ){
122437     p->doclist.aAll = pList;
122438     p->doclist.nAll = nList;
122439   }
122440
122441   else if( p->doclist.aAll==0 ){
122442     sqlite3_free(pList);
122443   }
122444
122445   else {
122446     char *pLeft;
122447     char *pRight;
122448     int nLeft;
122449     int nRight;
122450     int nDiff;
122451
122452     if( p->iDoclistToken<iToken ){
122453       pLeft = p->doclist.aAll;
122454       nLeft = p->doclist.nAll;
122455       pRight = pList;
122456       nRight = nList;
122457       nDiff = iToken - p->iDoclistToken;
122458     }else{
122459       pRight = p->doclist.aAll;
122460       nRight = p->doclist.nAll;
122461       pLeft = pList;
122462       nLeft = nList;
122463       nDiff = p->iDoclistToken - iToken;
122464     }
122465
122466     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
122467     sqlite3_free(pLeft);
122468     p->doclist.aAll = pRight;
122469     p->doclist.nAll = nRight;
122470   }
122471
122472   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
122473 }
122474
122475 /*
122476 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
122477 ** does not take deferred tokens into account.
122478 **
122479 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122480 */
122481 static int fts3EvalPhraseLoad(
122482   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122483   Fts3Phrase *p                   /* Phrase object */
122484 ){
122485   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122486   int iToken;
122487   int rc = SQLITE_OK;
122488
122489   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
122490     Fts3PhraseToken *pToken = &p->aToken[iToken];
122491     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
122492
122493     if( pToken->pSegcsr ){
122494       int nThis = 0;
122495       char *pThis = 0;
122496       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
122497       if( rc==SQLITE_OK ){
122498         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
122499       }
122500     }
122501     assert( pToken->pSegcsr==0 );
122502   }
122503
122504   return rc;
122505 }
122506
122507 /*
122508 ** This function is called on each phrase after the position lists for
122509 ** any deferred tokens have been loaded into memory. It updates the phrases
122510 ** current position list to include only those positions that are really
122511 ** instances of the phrase (after considering deferred tokens). If this
122512 ** means that the phrase does not appear in the current row, doclist.pList
122513 ** and doclist.nList are both zeroed.
122514 **
122515 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122516 */
122517 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
122518   int iToken;                     /* Used to iterate through phrase tokens */
122519   char *aPoslist = 0;             /* Position list for deferred tokens */
122520   int nPoslist = 0;               /* Number of bytes in aPoslist */
122521   int iPrev = -1;                 /* Token number of previous deferred token */
122522
122523   assert( pPhrase->doclist.bFreeList==0 );
122524
122525   for(iToken=0; iToken<pPhrase->nToken; iToken++){
122526     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
122527     Fts3DeferredToken *pDeferred = pToken->pDeferred;
122528
122529     if( pDeferred ){
122530       char *pList;
122531       int nList;
122532       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
122533       if( rc!=SQLITE_OK ) return rc;
122534
122535       if( pList==0 ){
122536         sqlite3_free(aPoslist);
122537         pPhrase->doclist.pList = 0;
122538         pPhrase->doclist.nList = 0;
122539         return SQLITE_OK;
122540
122541       }else if( aPoslist==0 ){
122542         aPoslist = pList;
122543         nPoslist = nList;
122544
122545       }else{
122546         char *aOut = pList;
122547         char *p1 = aPoslist;
122548         char *p2 = aOut;
122549
122550         assert( iPrev>=0 );
122551         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
122552         sqlite3_free(aPoslist);
122553         aPoslist = pList;
122554         nPoslist = (int)(aOut - aPoslist);
122555         if( nPoslist==0 ){
122556           sqlite3_free(aPoslist);
122557           pPhrase->doclist.pList = 0;
122558           pPhrase->doclist.nList = 0;
122559           return SQLITE_OK;
122560         }
122561       }
122562       iPrev = iToken;
122563     }
122564   }
122565
122566   if( iPrev>=0 ){
122567     int nMaxUndeferred = pPhrase->iDoclistToken;
122568     if( nMaxUndeferred<0 ){
122569       pPhrase->doclist.pList = aPoslist;
122570       pPhrase->doclist.nList = nPoslist;
122571       pPhrase->doclist.iDocid = pCsr->iPrevId;
122572       pPhrase->doclist.bFreeList = 1;
122573     }else{
122574       int nDistance;
122575       char *p1;
122576       char *p2;
122577       char *aOut;
122578
122579       if( nMaxUndeferred>iPrev ){
122580         p1 = aPoslist;
122581         p2 = pPhrase->doclist.pList;
122582         nDistance = nMaxUndeferred - iPrev;
122583       }else{
122584         p1 = pPhrase->doclist.pList;
122585         p2 = aPoslist;
122586         nDistance = iPrev - nMaxUndeferred;
122587       }
122588
122589       aOut = (char *)sqlite3_malloc(nPoslist+8);
122590       if( !aOut ){
122591         sqlite3_free(aPoslist);
122592         return SQLITE_NOMEM;
122593       }
122594
122595       pPhrase->doclist.pList = aOut;
122596       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
122597         pPhrase->doclist.bFreeList = 1;
122598         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
122599       }else{
122600         sqlite3_free(aOut);
122601         pPhrase->doclist.pList = 0;
122602         pPhrase->doclist.nList = 0;
122603       }
122604       sqlite3_free(aPoslist);
122605     }
122606   }
122607
122608   return SQLITE_OK;
122609 }
122610
122611 /*
122612 ** This function is called for each Fts3Phrase in a full-text query
122613 ** expression to initialize the mechanism for returning rows. Once this
122614 ** function has been called successfully on an Fts3Phrase, it may be
122615 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
122616 **
122617 ** If parameter bOptOk is true, then the phrase may (or may not) use the
122618 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
122619 ** memory within this call.
122620 **
122621 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122622 */
122623 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
122624   int rc;                         /* Error code */
122625   Fts3PhraseToken *pFirst = &p->aToken[0];
122626   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122627
122628   if( pCsr->bDesc==pTab->bDescIdx
122629    && bOptOk==1
122630    && p->nToken==1
122631    && pFirst->pSegcsr
122632    && pFirst->pSegcsr->bLookup
122633    && pFirst->bFirst==0
122634   ){
122635     /* Use the incremental approach. */
122636     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
122637     rc = sqlite3Fts3MsrIncrStart(
122638         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
122639     p->bIncr = 1;
122640
122641   }else{
122642     /* Load the full doclist for the phrase into memory. */
122643     rc = fts3EvalPhraseLoad(pCsr, p);
122644     p->bIncr = 0;
122645   }
122646
122647   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
122648   return rc;
122649 }
122650
122651 /*
122652 ** This function is used to iterate backwards (from the end to start)
122653 ** through doclists. It is used by this module to iterate through phrase
122654 ** doclists in reverse and by the fts3_write.c module to iterate through
122655 ** pending-terms lists when writing to databases with "order=desc".
122656 **
122657 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
122658 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
122659 ** function iterates from the end of the doclist to the beginning.
122660 */
122661 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
122662   int bDescIdx,                   /* True if the doclist is desc */
122663   char *aDoclist,                 /* Pointer to entire doclist */
122664   int nDoclist,                   /* Length of aDoclist in bytes */
122665   char **ppIter,                  /* IN/OUT: Iterator pointer */
122666   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
122667   int *pnList,                    /* OUT: List length pointer */
122668   u8 *pbEof                       /* OUT: End-of-file flag */
122669 ){
122670   char *p = *ppIter;
122671
122672   assert( nDoclist>0 );
122673   assert( *pbEof==0 );
122674   assert( p || *piDocid==0 );
122675   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
122676
122677   if( p==0 ){
122678     sqlite3_int64 iDocid = 0;
122679     char *pNext = 0;
122680     char *pDocid = aDoclist;
122681     char *pEnd = &aDoclist[nDoclist];
122682     int iMul = 1;
122683
122684     while( pDocid<pEnd ){
122685       sqlite3_int64 iDelta;
122686       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
122687       iDocid += (iMul * iDelta);
122688       pNext = pDocid;
122689       fts3PoslistCopy(0, &pDocid);
122690       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
122691       iMul = (bDescIdx ? -1 : 1);
122692     }
122693
122694     *pnList = (int)(pEnd - pNext);
122695     *ppIter = pNext;
122696     *piDocid = iDocid;
122697   }else{
122698     int iMul = (bDescIdx ? -1 : 1);
122699     sqlite3_int64 iDelta;
122700     fts3GetReverseVarint(&p, aDoclist, &iDelta);
122701     *piDocid -= (iMul * iDelta);
122702
122703     if( p==aDoclist ){
122704       *pbEof = 1;
122705     }else{
122706       char *pSave = p;
122707       fts3ReversePoslist(aDoclist, &p);
122708       *pnList = (int)(pSave - p);
122709     }
122710     *ppIter = p;
122711   }
122712 }
122713
122714 /*
122715 ** Iterate forwards through a doclist.
122716 */
122717 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
122718   int bDescIdx,                   /* True if the doclist is desc */
122719   char *aDoclist,                 /* Pointer to entire doclist */
122720   int nDoclist,                   /* Length of aDoclist in bytes */
122721   char **ppIter,                  /* IN/OUT: Iterator pointer */
122722   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
122723   u8 *pbEof                       /* OUT: End-of-file flag */
122724 ){
122725   char *p = *ppIter;
122726
122727   assert( nDoclist>0 );
122728   assert( *pbEof==0 );
122729   assert( p || *piDocid==0 );
122730   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
122731
122732   if( p==0 ){
122733     p = aDoclist;
122734     p += sqlite3Fts3GetVarint(p, piDocid);
122735   }else{
122736     fts3PoslistCopy(0, &p);
122737     if( p>=&aDoclist[nDoclist] ){
122738       *pbEof = 1;
122739     }else{
122740       sqlite3_int64 iVar;
122741       p += sqlite3Fts3GetVarint(p, &iVar);
122742       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
122743     }
122744   }
122745
122746   *ppIter = p;
122747 }
122748
122749 /*
122750 ** Attempt to move the phrase iterator to point to the next matching docid.
122751 ** If an error occurs, return an SQLite error code. Otherwise, return
122752 ** SQLITE_OK.
122753 **
122754 ** If there is no "next" entry and no error occurs, then *pbEof is set to
122755 ** 1 before returning. Otherwise, if no error occurs and the iterator is
122756 ** successfully advanced, *pbEof is set to 0.
122757 */
122758 static int fts3EvalPhraseNext(
122759   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122760   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
122761   u8 *pbEof                       /* OUT: Set to 1 if EOF */
122762 ){
122763   int rc = SQLITE_OK;
122764   Fts3Doclist *pDL = &p->doclist;
122765   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
122766
122767   if( p->bIncr ){
122768     assert( p->nToken==1 );
122769     assert( pDL->pNextDocid==0 );
122770     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
122771         &pDL->iDocid, &pDL->pList, &pDL->nList
122772     );
122773     if( rc==SQLITE_OK && !pDL->pList ){
122774       *pbEof = 1;
122775     }
122776   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
122777     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
122778         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
122779     );
122780     pDL->pList = pDL->pNextDocid;
122781   }else{
122782     char *pIter;                            /* Used to iterate through aAll */
122783     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
122784     if( pDL->pNextDocid ){
122785       pIter = pDL->pNextDocid;
122786     }else{
122787       pIter = pDL->aAll;
122788     }
122789
122790     if( pIter>=pEnd ){
122791       /* We have already reached the end of this doclist. EOF. */
122792       *pbEof = 1;
122793     }else{
122794       sqlite3_int64 iDelta;
122795       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
122796       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
122797         pDL->iDocid += iDelta;
122798       }else{
122799         pDL->iDocid -= iDelta;
122800       }
122801       pDL->pList = pIter;
122802       fts3PoslistCopy(0, &pIter);
122803       pDL->nList = (int)(pIter - pDL->pList);
122804
122805       /* pIter now points just past the 0x00 that terminates the position-
122806       ** list for document pDL->iDocid. However, if this position-list was
122807       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
122808       ** point to the start of the next docid value. The following line deals
122809       ** with this case by advancing pIter past the zero-padding added by
122810       ** fts3EvalNearTrim().  */
122811       while( pIter<pEnd && *pIter==0 ) pIter++;
122812
122813       pDL->pNextDocid = pIter;
122814       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
122815       *pbEof = 0;
122816     }
122817   }
122818
122819   return rc;
122820 }
122821
122822 /*
122823 **
122824 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
122825 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
122826 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
122827 ** expressions for which all descendent tokens are deferred.
122828 **
122829 ** If parameter bOptOk is zero, then it is guaranteed that the
122830 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
122831 ** each phrase in the expression (subject to deferred token processing).
122832 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
122833 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
122834 **
122835 ** If an error occurs within this function, *pRc is set to an SQLite error
122836 ** code before returning.
122837 */
122838 static void fts3EvalStartReaders(
122839   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122840   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
122841   int bOptOk,                     /* True to enable incremental loading */
122842   int *pRc                        /* IN/OUT: Error code */
122843 ){
122844   if( pExpr && SQLITE_OK==*pRc ){
122845     if( pExpr->eType==FTSQUERY_PHRASE ){
122846       int i;
122847       int nToken = pExpr->pPhrase->nToken;
122848       for(i=0; i<nToken; i++){
122849         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
122850       }
122851       pExpr->bDeferred = (i==nToken);
122852       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
122853     }else{
122854       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
122855       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
122856       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
122857     }
122858   }
122859 }
122860
122861 /*
122862 ** An array of the following structures is assembled as part of the process
122863 ** of selecting tokens to defer before the query starts executing (as part
122864 ** of the xFilter() method). There is one element in the array for each
122865 ** token in the FTS expression.
122866 **
122867 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
122868 ** to phrases that are connected only by AND and NEAR operators (not OR or
122869 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
122870 ** separately. The root of a tokens AND/NEAR cluster is stored in
122871 ** Fts3TokenAndCost.pRoot.
122872 */
122873 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
122874 struct Fts3TokenAndCost {
122875   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
122876   int iToken;                     /* Position of token in phrase */
122877   Fts3PhraseToken *pToken;        /* The token itself */
122878   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
122879   int nOvfl;                      /* Number of overflow pages to load doclist */
122880   int iCol;                       /* The column the token must match */
122881 };
122882
122883 /*
122884 ** This function is used to populate an allocated Fts3TokenAndCost array.
122885 **
122886 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
122887 ** Otherwise, if an error occurs during execution, *pRc is set to an
122888 ** SQLite error code.
122889 */
122890 static void fts3EvalTokenCosts(
122891   Fts3Cursor *pCsr,               /* FTS Cursor handle */
122892   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
122893   Fts3Expr *pExpr,                /* Expression to consider */
122894   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
122895   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
122896   int *pRc                        /* IN/OUT: Error code */
122897 ){
122898   if( *pRc==SQLITE_OK ){
122899     if( pExpr->eType==FTSQUERY_PHRASE ){
122900       Fts3Phrase *pPhrase = pExpr->pPhrase;
122901       int i;
122902       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
122903         Fts3TokenAndCost *pTC = (*ppTC)++;
122904         pTC->pPhrase = pPhrase;
122905         pTC->iToken = i;
122906         pTC->pRoot = pRoot;
122907         pTC->pToken = &pPhrase->aToken[i];
122908         pTC->iCol = pPhrase->iColumn;
122909         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
122910       }
122911     }else if( pExpr->eType!=FTSQUERY_NOT ){
122912       assert( pExpr->eType==FTSQUERY_OR
122913            || pExpr->eType==FTSQUERY_AND
122914            || pExpr->eType==FTSQUERY_NEAR
122915       );
122916       assert( pExpr->pLeft && pExpr->pRight );
122917       if( pExpr->eType==FTSQUERY_OR ){
122918         pRoot = pExpr->pLeft;
122919         **ppOr = pRoot;
122920         (*ppOr)++;
122921       }
122922       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
122923       if( pExpr->eType==FTSQUERY_OR ){
122924         pRoot = pExpr->pRight;
122925         **ppOr = pRoot;
122926         (*ppOr)++;
122927       }
122928       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
122929     }
122930   }
122931 }
122932
122933 /*
122934 ** Determine the average document (row) size in pages. If successful,
122935 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
122936 ** an SQLite error code.
122937 **
122938 ** The average document size in pages is calculated by first calculating
122939 ** determining the average size in bytes, B. If B is less than the amount
122940 ** of data that will fit on a single leaf page of an intkey table in
122941 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
122942 ** the number of overflow pages consumed by a record B bytes in size.
122943 */
122944 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
122945   if( pCsr->nRowAvg==0 ){
122946     /* The average document size, which is required to calculate the cost
122947     ** of each doclist, has not yet been determined. Read the required
122948     ** data from the %_stat table to calculate it.
122949     **
122950     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
122951     ** varints, where nCol is the number of columns in the FTS3 table.
122952     ** The first varint is the number of documents currently stored in
122953     ** the table. The following nCol varints contain the total amount of
122954     ** data stored in all rows of each column of the table, from left
122955     ** to right.
122956     */
122957     int rc;
122958     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
122959     sqlite3_stmt *pStmt;
122960     sqlite3_int64 nDoc = 0;
122961     sqlite3_int64 nByte = 0;
122962     const char *pEnd;
122963     const char *a;
122964
122965     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
122966     if( rc!=SQLITE_OK ) return rc;
122967     a = sqlite3_column_blob(pStmt, 0);
122968     assert( a );
122969
122970     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
122971     a += sqlite3Fts3GetVarint(a, &nDoc);
122972     while( a<pEnd ){
122973       a += sqlite3Fts3GetVarint(a, &nByte);
122974     }
122975     if( nDoc==0 || nByte==0 ){
122976       sqlite3_reset(pStmt);
122977       return FTS_CORRUPT_VTAB;
122978     }
122979
122980     pCsr->nDoc = nDoc;
122981     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
122982     assert( pCsr->nRowAvg>0 );
122983     rc = sqlite3_reset(pStmt);
122984     if( rc!=SQLITE_OK ) return rc;
122985   }
122986
122987   *pnPage = pCsr->nRowAvg;
122988   return SQLITE_OK;
122989 }
122990
122991 /*
122992 ** This function is called to select the tokens (if any) that will be
122993 ** deferred. The array aTC[] has already been populated when this is
122994 ** called.
122995 **
122996 ** This function is called once for each AND/NEAR cluster in the
122997 ** expression. Each invocation determines which tokens to defer within
122998 ** the cluster with root node pRoot. See comments above the definition
122999 ** of struct Fts3TokenAndCost for more details.
123000 **
123001 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
123002 ** called on each token to defer. Otherwise, an SQLite error code is
123003 ** returned.
123004 */
123005 static int fts3EvalSelectDeferred(
123006   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123007   Fts3Expr *pRoot,                /* Consider tokens with this root node */
123008   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
123009   int nTC                         /* Number of entries in aTC[] */
123010 ){
123011   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123012   int nDocSize = 0;               /* Number of pages per doc loaded */
123013   int rc = SQLITE_OK;             /* Return code */
123014   int ii;                         /* Iterator variable for various purposes */
123015   int nOvfl = 0;                  /* Total overflow pages used by doclists */
123016   int nToken = 0;                 /* Total number of tokens in cluster */
123017
123018   int nMinEst = 0;                /* The minimum count for any phrase so far. */
123019   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
123020
123021   /* Tokens are never deferred for FTS tables created using the content=xxx
123022   ** option. The reason being that it is not guaranteed that the content
123023   ** table actually contains the same data as the index. To prevent this from
123024   ** causing any problems, the deferred token optimization is completely
123025   ** disabled for content=xxx tables. */
123026   if( pTab->zContentTbl ){
123027     return SQLITE_OK;
123028   }
123029
123030   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
123031   ** associated with the tokens spill onto overflow pages, or if there is
123032   ** only 1 token, exit early. No tokens to defer in this case. */
123033   for(ii=0; ii<nTC; ii++){
123034     if( aTC[ii].pRoot==pRoot ){
123035       nOvfl += aTC[ii].nOvfl;
123036       nToken++;
123037     }
123038   }
123039   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
123040
123041   /* Obtain the average docsize (in pages). */
123042   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
123043   assert( rc!=SQLITE_OK || nDocSize>0 );
123044
123045
123046   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
123047   ** of the number of overflow pages that will be loaded by the pager layer
123048   ** to retrieve the entire doclist for the token from the full-text index.
123049   ** Load the doclists for tokens that are either:
123050   **
123051   **   a. The cheapest token in the entire query (i.e. the one visited by the
123052   **      first iteration of this loop), or
123053   **
123054   **   b. Part of a multi-token phrase.
123055   **
123056   ** After each token doclist is loaded, merge it with the others from the
123057   ** same phrase and count the number of documents that the merged doclist
123058   ** contains. Set variable "nMinEst" to the smallest number of documents in
123059   ** any phrase doclist for which 1 or more token doclists have been loaded.
123060   ** Let nOther be the number of other phrases for which it is certain that
123061   ** one or more tokens will not be deferred.
123062   **
123063   ** Then, for each token, defer it if loading the doclist would result in
123064   ** loading N or more overflow pages into memory, where N is computed as:
123065   **
123066   **    (nMinEst + 4^nOther - 1) / (4^nOther)
123067   */
123068   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
123069     int iTC;                      /* Used to iterate through aTC[] array. */
123070     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
123071
123072     /* Set pTC to point to the cheapest remaining token. */
123073     for(iTC=0; iTC<nTC; iTC++){
123074       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
123075        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
123076       ){
123077         pTC = &aTC[iTC];
123078       }
123079     }
123080     assert( pTC );
123081
123082     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
123083       /* The number of overflow pages to load for this (and therefore all
123084       ** subsequent) tokens is greater than the estimated number of pages
123085       ** that will be loaded if all subsequent tokens are deferred.
123086       */
123087       Fts3PhraseToken *pToken = pTC->pToken;
123088       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
123089       fts3SegReaderCursorFree(pToken->pSegcsr);
123090       pToken->pSegcsr = 0;
123091     }else{
123092       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
123093       ** for-loop. Except, limit the value to 2^24 to prevent it from
123094       ** overflowing the 32-bit integer it is stored in. */
123095       if( ii<12 ) nLoad4 = nLoad4*4;
123096
123097       if( ii==0 || pTC->pPhrase->nToken>1 ){
123098         /* Either this is the cheapest token in the entire query, or it is
123099         ** part of a multi-token phrase. Either way, the entire doclist will
123100         ** (eventually) be loaded into memory. It may as well be now. */
123101         Fts3PhraseToken *pToken = pTC->pToken;
123102         int nList = 0;
123103         char *pList = 0;
123104         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
123105         assert( rc==SQLITE_OK || pList==0 );
123106         if( rc==SQLITE_OK ){
123107           int nCount;
123108           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
123109           nCount = fts3DoclistCountDocids(
123110               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
123111           );
123112           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
123113         }
123114       }
123115     }
123116     pTC->pToken = 0;
123117   }
123118
123119   return rc;
123120 }
123121
123122 /*
123123 ** This function is called from within the xFilter method. It initializes
123124 ** the full-text query currently stored in pCsr->pExpr. To iterate through
123125 ** the results of a query, the caller does:
123126 **
123127 **    fts3EvalStart(pCsr);
123128 **    while( 1 ){
123129 **      fts3EvalNext(pCsr);
123130 **      if( pCsr->bEof ) break;
123131 **      ... return row pCsr->iPrevId to the caller ...
123132 **    }
123133 */
123134 static int fts3EvalStart(Fts3Cursor *pCsr){
123135   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123136   int rc = SQLITE_OK;
123137   int nToken = 0;
123138   int nOr = 0;
123139
123140   /* Allocate a MultiSegReader for each token in the expression. */
123141   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
123142
123143   /* Determine which, if any, tokens in the expression should be deferred. */
123144 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
123145   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
123146     Fts3TokenAndCost *aTC;
123147     Fts3Expr **apOr;
123148     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
123149         sizeof(Fts3TokenAndCost) * nToken
123150       + sizeof(Fts3Expr *) * nOr * 2
123151     );
123152     apOr = (Fts3Expr **)&aTC[nToken];
123153
123154     if( !aTC ){
123155       rc = SQLITE_NOMEM;
123156     }else{
123157       int ii;
123158       Fts3TokenAndCost *pTC = aTC;
123159       Fts3Expr **ppOr = apOr;
123160
123161       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
123162       nToken = (int)(pTC-aTC);
123163       nOr = (int)(ppOr-apOr);
123164
123165       if( rc==SQLITE_OK ){
123166         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
123167         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
123168           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
123169         }
123170       }
123171
123172       sqlite3_free(aTC);
123173     }
123174   }
123175 #endif
123176
123177   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
123178   return rc;
123179 }
123180
123181 /*
123182 ** Invalidate the current position list for phrase pPhrase.
123183 */
123184 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
123185   if( pPhrase->doclist.bFreeList ){
123186     sqlite3_free(pPhrase->doclist.pList);
123187   }
123188   pPhrase->doclist.pList = 0;
123189   pPhrase->doclist.nList = 0;
123190   pPhrase->doclist.bFreeList = 0;
123191 }
123192
123193 /*
123194 ** This function is called to edit the position list associated with
123195 ** the phrase object passed as the fifth argument according to a NEAR
123196 ** condition. For example:
123197 **
123198 **     abc NEAR/5 "def ghi"
123199 **
123200 ** Parameter nNear is passed the NEAR distance of the expression (5 in
123201 ** the example above). When this function is called, *paPoslist points to
123202 ** the position list, and *pnToken is the number of phrase tokens in, the
123203 ** phrase on the other side of the NEAR operator to pPhrase. For example,
123204 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
123205 ** the position list associated with phrase "abc".
123206 **
123207 ** All positions in the pPhrase position list that are not sufficiently
123208 ** close to a position in the *paPoslist position list are removed. If this
123209 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
123210 **
123211 ** Before returning, *paPoslist is set to point to the position lsit
123212 ** associated with pPhrase. And *pnToken is set to the number of tokens in
123213 ** pPhrase.
123214 */
123215 static int fts3EvalNearTrim(
123216   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
123217   char *aTmp,                     /* Temporary space to use */
123218   char **paPoslist,               /* IN/OUT: Position list */
123219   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
123220   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
123221 ){
123222   int nParam1 = nNear + pPhrase->nToken;
123223   int nParam2 = nNear + *pnToken;
123224   int nNew;
123225   char *p2;
123226   char *pOut;
123227   int res;
123228
123229   assert( pPhrase->doclist.pList );
123230
123231   p2 = pOut = pPhrase->doclist.pList;
123232   res = fts3PoslistNearMerge(
123233     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
123234   );
123235   if( res ){
123236     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
123237     assert( pPhrase->doclist.pList[nNew]=='\0' );
123238     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
123239     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
123240     pPhrase->doclist.nList = nNew;
123241     *paPoslist = pPhrase->doclist.pList;
123242     *pnToken = pPhrase->nToken;
123243   }
123244
123245   return res;
123246 }
123247
123248 /*
123249 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
123250 ** Otherwise, it advances the expression passed as the second argument to
123251 ** point to the next matching row in the database. Expressions iterate through
123252 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
123253 ** or descending if it is non-zero.
123254 **
123255 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
123256 ** successful, the following variables in pExpr are set:
123257 **
123258 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
123259 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
123260 **
123261 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
123262 ** at EOF, then the following variables are populated with the position list
123263 ** for the phrase for the visited row:
123264 **
123265 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
123266 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
123267 **
123268 ** It says above that this function advances the expression to the next
123269 ** matching row. This is usually true, but there are the following exceptions:
123270 **
123271 **   1. Deferred tokens are not taken into account. If a phrase consists
123272 **      entirely of deferred tokens, it is assumed to match every row in
123273 **      the db. In this case the position-list is not populated at all.
123274 **
123275 **      Or, if a phrase contains one or more deferred tokens and one or
123276 **      more non-deferred tokens, then the expression is advanced to the
123277 **      next possible match, considering only non-deferred tokens. In other
123278 **      words, if the phrase is "A B C", and "B" is deferred, the expression
123279 **      is advanced to the next row that contains an instance of "A * C",
123280 **      where "*" may match any single token. The position list in this case
123281 **      is populated as for "A * C" before returning.
123282 **
123283 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
123284 **      advanced to point to the next row that matches "x AND y".
123285 **
123286 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
123287 ** really a match, taking into account deferred tokens and NEAR operators.
123288 */
123289 static void fts3EvalNextRow(
123290   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123291   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
123292   int *pRc                        /* IN/OUT: Error code */
123293 ){
123294   if( *pRc==SQLITE_OK ){
123295     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
123296     assert( pExpr->bEof==0 );
123297     pExpr->bStart = 1;
123298
123299     switch( pExpr->eType ){
123300       case FTSQUERY_NEAR:
123301       case FTSQUERY_AND: {
123302         Fts3Expr *pLeft = pExpr->pLeft;
123303         Fts3Expr *pRight = pExpr->pRight;
123304         assert( !pLeft->bDeferred || !pRight->bDeferred );
123305
123306         if( pLeft->bDeferred ){
123307           /* LHS is entirely deferred. So we assume it matches every row.
123308           ** Advance the RHS iterator to find the next row visited. */
123309           fts3EvalNextRow(pCsr, pRight, pRc);
123310           pExpr->iDocid = pRight->iDocid;
123311           pExpr->bEof = pRight->bEof;
123312         }else if( pRight->bDeferred ){
123313           /* RHS is entirely deferred. So we assume it matches every row.
123314           ** Advance the LHS iterator to find the next row visited. */
123315           fts3EvalNextRow(pCsr, pLeft, pRc);
123316           pExpr->iDocid = pLeft->iDocid;
123317           pExpr->bEof = pLeft->bEof;
123318         }else{
123319           /* Neither the RHS or LHS are deferred. */
123320           fts3EvalNextRow(pCsr, pLeft, pRc);
123321           fts3EvalNextRow(pCsr, pRight, pRc);
123322           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
123323             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123324             if( iDiff==0 ) break;
123325             if( iDiff<0 ){
123326               fts3EvalNextRow(pCsr, pLeft, pRc);
123327             }else{
123328               fts3EvalNextRow(pCsr, pRight, pRc);
123329             }
123330           }
123331           pExpr->iDocid = pLeft->iDocid;
123332           pExpr->bEof = (pLeft->bEof || pRight->bEof);
123333         }
123334         break;
123335       }
123336
123337       case FTSQUERY_OR: {
123338         Fts3Expr *pLeft = pExpr->pLeft;
123339         Fts3Expr *pRight = pExpr->pRight;
123340         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123341
123342         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
123343         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
123344
123345         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
123346           fts3EvalNextRow(pCsr, pLeft, pRc);
123347         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
123348           fts3EvalNextRow(pCsr, pRight, pRc);
123349         }else{
123350           fts3EvalNextRow(pCsr, pLeft, pRc);
123351           fts3EvalNextRow(pCsr, pRight, pRc);
123352         }
123353
123354         pExpr->bEof = (pLeft->bEof && pRight->bEof);
123355         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123356         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
123357           pExpr->iDocid = pLeft->iDocid;
123358         }else{
123359           pExpr->iDocid = pRight->iDocid;
123360         }
123361
123362         break;
123363       }
123364
123365       case FTSQUERY_NOT: {
123366         Fts3Expr *pLeft = pExpr->pLeft;
123367         Fts3Expr *pRight = pExpr->pRight;
123368
123369         if( pRight->bStart==0 ){
123370           fts3EvalNextRow(pCsr, pRight, pRc);
123371           assert( *pRc!=SQLITE_OK || pRight->bStart );
123372         }
123373
123374         fts3EvalNextRow(pCsr, pLeft, pRc);
123375         if( pLeft->bEof==0 ){
123376           while( !*pRc
123377               && !pRight->bEof
123378               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
123379           ){
123380             fts3EvalNextRow(pCsr, pRight, pRc);
123381           }
123382         }
123383         pExpr->iDocid = pLeft->iDocid;
123384         pExpr->bEof = pLeft->bEof;
123385         break;
123386       }
123387
123388       default: {
123389         Fts3Phrase *pPhrase = pExpr->pPhrase;
123390         fts3EvalInvalidatePoslist(pPhrase);
123391         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
123392         pExpr->iDocid = pPhrase->doclist.iDocid;
123393         break;
123394       }
123395     }
123396   }
123397 }
123398
123399 /*
123400 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
123401 ** cluster, then this function returns 1 immediately.
123402 **
123403 ** Otherwise, it checks if the current row really does match the NEAR
123404 ** expression, using the data currently stored in the position lists
123405 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
123406 **
123407 ** If the current row is a match, the position list associated with each
123408 ** phrase in the NEAR expression is edited in place to contain only those
123409 ** phrase instances sufficiently close to their peers to satisfy all NEAR
123410 ** constraints. In this case it returns 1. If the NEAR expression does not
123411 ** match the current row, 0 is returned. The position lists may or may not
123412 ** be edited if 0 is returned.
123413 */
123414 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
123415   int res = 1;
123416
123417   /* The following block runs if pExpr is the root of a NEAR query.
123418   ** For example, the query:
123419   **
123420   **         "w" NEAR "x" NEAR "y" NEAR "z"
123421   **
123422   ** which is represented in tree form as:
123423   **
123424   **                               |
123425   **                          +--NEAR--+      <-- root of NEAR query
123426   **                          |        |
123427   **                     +--NEAR--+   "z"
123428   **                     |        |
123429   **                +--NEAR--+   "y"
123430   **                |        |
123431   **               "w"      "x"
123432   **
123433   ** The right-hand child of a NEAR node is always a phrase. The
123434   ** left-hand child may be either a phrase or a NEAR node. There are
123435   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
123436   */
123437   if( *pRc==SQLITE_OK
123438    && pExpr->eType==FTSQUERY_NEAR
123439    && pExpr->bEof==0
123440    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
123441   ){
123442     Fts3Expr *p;
123443     int nTmp = 0;                 /* Bytes of temp space */
123444     char *aTmp;                   /* Temp space for PoslistNearMerge() */
123445
123446     /* Allocate temporary working space. */
123447     for(p=pExpr; p->pLeft; p=p->pLeft){
123448       nTmp += p->pRight->pPhrase->doclist.nList;
123449     }
123450     nTmp += p->pPhrase->doclist.nList;
123451     if( nTmp==0 ){
123452       res = 0;
123453     }else{
123454       aTmp = sqlite3_malloc(nTmp*2);
123455       if( !aTmp ){
123456         *pRc = SQLITE_NOMEM;
123457         res = 0;
123458       }else{
123459         char *aPoslist = p->pPhrase->doclist.pList;
123460         int nToken = p->pPhrase->nToken;
123461
123462         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
123463           Fts3Phrase *pPhrase = p->pRight->pPhrase;
123464           int nNear = p->nNear;
123465           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
123466         }
123467
123468         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
123469         nToken = pExpr->pRight->pPhrase->nToken;
123470         for(p=pExpr->pLeft; p && res; p=p->pLeft){
123471           int nNear;
123472           Fts3Phrase *pPhrase;
123473           assert( p->pParent && p->pParent->pLeft==p );
123474           nNear = p->pParent->nNear;
123475           pPhrase = (
123476               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
123477               );
123478           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
123479         }
123480       }
123481
123482       sqlite3_free(aTmp);
123483     }
123484   }
123485
123486   return res;
123487 }
123488
123489 /*
123490 ** This function is a helper function for fts3EvalTestDeferredAndNear().
123491 ** Assuming no error occurs or has occurred, It returns non-zero if the
123492 ** expression passed as the second argument matches the row that pCsr
123493 ** currently points to, or zero if it does not.
123494 **
123495 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
123496 ** If an error occurs during execution of this function, *pRc is set to
123497 ** the appropriate SQLite error code. In this case the returned value is
123498 ** undefined.
123499 */
123500 static int fts3EvalTestExpr(
123501   Fts3Cursor *pCsr,               /* FTS cursor handle */
123502   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
123503   int *pRc                        /* IN/OUT: Error code */
123504 ){
123505   int bHit = 1;                   /* Return value */
123506   if( *pRc==SQLITE_OK ){
123507     switch( pExpr->eType ){
123508       case FTSQUERY_NEAR:
123509       case FTSQUERY_AND:
123510         bHit = (
123511             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
123512          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
123513          && fts3EvalNearTest(pExpr, pRc)
123514         );
123515
123516         /* If the NEAR expression does not match any rows, zero the doclist for
123517         ** all phrases involved in the NEAR. This is because the snippet(),
123518         ** offsets() and matchinfo() functions are not supposed to recognize
123519         ** any instances of phrases that are part of unmatched NEAR queries.
123520         ** For example if this expression:
123521         **
123522         **    ... MATCH 'a OR (b NEAR c)'
123523         **
123524         ** is matched against a row containing:
123525         **
123526         **        'a b d e'
123527         **
123528         ** then any snippet() should ony highlight the "a" term, not the "b"
123529         ** (as "b" is part of a non-matching NEAR clause).
123530         */
123531         if( bHit==0
123532          && pExpr->eType==FTSQUERY_NEAR
123533          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
123534         ){
123535           Fts3Expr *p;
123536           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
123537             if( p->pRight->iDocid==pCsr->iPrevId ){
123538               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
123539             }
123540           }
123541           if( p->iDocid==pCsr->iPrevId ){
123542             fts3EvalInvalidatePoslist(p->pPhrase);
123543           }
123544         }
123545
123546         break;
123547
123548       case FTSQUERY_OR: {
123549         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
123550         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
123551         bHit = bHit1 || bHit2;
123552         break;
123553       }
123554
123555       case FTSQUERY_NOT:
123556         bHit = (
123557             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
123558          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
123559         );
123560         break;
123561
123562       default: {
123563 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
123564         if( pCsr->pDeferred
123565          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
123566         ){
123567           Fts3Phrase *pPhrase = pExpr->pPhrase;
123568           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
123569           if( pExpr->bDeferred ){
123570             fts3EvalInvalidatePoslist(pPhrase);
123571           }
123572           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
123573           bHit = (pPhrase->doclist.pList!=0);
123574           pExpr->iDocid = pCsr->iPrevId;
123575         }else
123576 #endif
123577         {
123578           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
123579         }
123580         break;
123581       }
123582     }
123583   }
123584   return bHit;
123585 }
123586
123587 /*
123588 ** This function is called as the second part of each xNext operation when
123589 ** iterating through the results of a full-text query. At this point the
123590 ** cursor points to a row that matches the query expression, with the
123591 ** following caveats:
123592 **
123593 **   * Up until this point, "NEAR" operators in the expression have been
123594 **     treated as "AND".
123595 **
123596 **   * Deferred tokens have not yet been considered.
123597 **
123598 ** If *pRc is not SQLITE_OK when this function is called, it immediately
123599 ** returns 0. Otherwise, it tests whether or not after considering NEAR
123600 ** operators and deferred tokens the current row is still a match for the
123601 ** expression. It returns 1 if both of the following are true:
123602 **
123603 **   1. *pRc is SQLITE_OK when this function returns, and
123604 **
123605 **   2. After scanning the current FTS table row for the deferred tokens,
123606 **      it is determined that the row does *not* match the query.
123607 **
123608 ** Or, if no error occurs and it seems the current row does match the FTS
123609 ** query, return 0.
123610 */
123611 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
123612   int rc = *pRc;
123613   int bMiss = 0;
123614   if( rc==SQLITE_OK ){
123615
123616     /* If there are one or more deferred tokens, load the current row into
123617     ** memory and scan it to determine the position list for each deferred
123618     ** token. Then, see if this row is really a match, considering deferred
123619     ** tokens and NEAR operators (neither of which were taken into account
123620     ** earlier, by fts3EvalNextRow()).
123621     */
123622     if( pCsr->pDeferred ){
123623       rc = fts3CursorSeek(0, pCsr);
123624       if( rc==SQLITE_OK ){
123625         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
123626       }
123627     }
123628     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
123629
123630     /* Free the position-lists accumulated for each deferred token above. */
123631     sqlite3Fts3FreeDeferredDoclists(pCsr);
123632     *pRc = rc;
123633   }
123634   return (rc==SQLITE_OK && bMiss);
123635 }
123636
123637 /*
123638 ** Advance to the next document that matches the FTS expression in
123639 ** Fts3Cursor.pExpr.
123640 */
123641 static int fts3EvalNext(Fts3Cursor *pCsr){
123642   int rc = SQLITE_OK;             /* Return Code */
123643   Fts3Expr *pExpr = pCsr->pExpr;
123644   assert( pCsr->isEof==0 );
123645   if( pExpr==0 ){
123646     pCsr->isEof = 1;
123647   }else{
123648     do {
123649       if( pCsr->isRequireSeek==0 ){
123650         sqlite3_reset(pCsr->pStmt);
123651       }
123652       assert( sqlite3_data_count(pCsr->pStmt)==0 );
123653       fts3EvalNextRow(pCsr, pExpr, &rc);
123654       pCsr->isEof = pExpr->bEof;
123655       pCsr->isRequireSeek = 1;
123656       pCsr->isMatchinfoNeeded = 1;
123657       pCsr->iPrevId = pExpr->iDocid;
123658     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
123659   }
123660   return rc;
123661 }
123662
123663 /*
123664 ** Restart interation for expression pExpr so that the next call to
123665 ** fts3EvalNext() visits the first row. Do not allow incremental
123666 ** loading or merging of phrase doclists for this iteration.
123667 **
123668 ** If *pRc is other than SQLITE_OK when this function is called, it is
123669 ** a no-op. If an error occurs within this function, *pRc is set to an
123670 ** SQLite error code before returning.
123671 */
123672 static void fts3EvalRestart(
123673   Fts3Cursor *pCsr,
123674   Fts3Expr *pExpr,
123675   int *pRc
123676 ){
123677   if( pExpr && *pRc==SQLITE_OK ){
123678     Fts3Phrase *pPhrase = pExpr->pPhrase;
123679
123680     if( pPhrase ){
123681       fts3EvalInvalidatePoslist(pPhrase);
123682       if( pPhrase->bIncr ){
123683         assert( pPhrase->nToken==1 );
123684         assert( pPhrase->aToken[0].pSegcsr );
123685         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
123686         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
123687       }
123688
123689       pPhrase->doclist.pNextDocid = 0;
123690       pPhrase->doclist.iDocid = 0;
123691     }
123692
123693     pExpr->iDocid = 0;
123694     pExpr->bEof = 0;
123695     pExpr->bStart = 0;
123696
123697     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
123698     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
123699   }
123700 }
123701
123702 /*
123703 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
123704 ** expression rooted at pExpr, the cursor iterates through all rows matched
123705 ** by pExpr, calling this function for each row. This function increments
123706 ** the values in Fts3Expr.aMI[] according to the position-list currently
123707 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
123708 ** expression nodes.
123709 */
123710 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
123711   if( pExpr ){
123712     Fts3Phrase *pPhrase = pExpr->pPhrase;
123713     if( pPhrase && pPhrase->doclist.pList ){
123714       int iCol = 0;
123715       char *p = pPhrase->doclist.pList;
123716
123717       assert( *p );
123718       while( 1 ){
123719         u8 c = 0;
123720         int iCnt = 0;
123721         while( 0xFE & (*p | c) ){
123722           if( (c&0x80)==0 ) iCnt++;
123723           c = *p++ & 0x80;
123724         }
123725
123726         /* aMI[iCol*3 + 1] = Number of occurrences
123727         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
123728         */
123729         pExpr->aMI[iCol*3 + 1] += iCnt;
123730         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
123731         if( *p==0x00 ) break;
123732         p++;
123733         p += sqlite3Fts3GetVarint32(p, &iCol);
123734       }
123735     }
123736
123737     fts3EvalUpdateCounts(pExpr->pLeft);
123738     fts3EvalUpdateCounts(pExpr->pRight);
123739   }
123740 }
123741
123742 /*
123743 ** Expression pExpr must be of type FTSQUERY_PHRASE.
123744 **
123745 ** If it is not already allocated and populated, this function allocates and
123746 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
123747 ** of a NEAR expression, then it also allocates and populates the same array
123748 ** for all other phrases that are part of the NEAR expression.
123749 **
123750 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
123751 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
123752 */
123753 static int fts3EvalGatherStats(
123754   Fts3Cursor *pCsr,               /* Cursor object */
123755   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
123756 ){
123757   int rc = SQLITE_OK;             /* Return code */
123758
123759   assert( pExpr->eType==FTSQUERY_PHRASE );
123760   if( pExpr->aMI==0 ){
123761     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123762     Fts3Expr *pRoot;                /* Root of NEAR expression */
123763     Fts3Expr *p;                    /* Iterator used for several purposes */
123764
123765     sqlite3_int64 iPrevId = pCsr->iPrevId;
123766     sqlite3_int64 iDocid;
123767     u8 bEof;
123768
123769     /* Find the root of the NEAR expression */
123770     pRoot = pExpr;
123771     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
123772       pRoot = pRoot->pParent;
123773     }
123774     iDocid = pRoot->iDocid;
123775     bEof = pRoot->bEof;
123776     assert( pRoot->bStart );
123777
123778     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
123779     for(p=pRoot; p; p=p->pLeft){
123780       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
123781       assert( pE->aMI==0 );
123782       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
123783       if( !pE->aMI ) return SQLITE_NOMEM;
123784       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
123785     }
123786
123787     fts3EvalRestart(pCsr, pRoot, &rc);
123788
123789     while( pCsr->isEof==0 && rc==SQLITE_OK ){
123790
123791       do {
123792         /* Ensure the %_content statement is reset. */
123793         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
123794         assert( sqlite3_data_count(pCsr->pStmt)==0 );
123795
123796         /* Advance to the next document */
123797         fts3EvalNextRow(pCsr, pRoot, &rc);
123798         pCsr->isEof = pRoot->bEof;
123799         pCsr->isRequireSeek = 1;
123800         pCsr->isMatchinfoNeeded = 1;
123801         pCsr->iPrevId = pRoot->iDocid;
123802       }while( pCsr->isEof==0
123803            && pRoot->eType==FTSQUERY_NEAR
123804            && fts3EvalTestDeferredAndNear(pCsr, &rc)
123805       );
123806
123807       if( rc==SQLITE_OK && pCsr->isEof==0 ){
123808         fts3EvalUpdateCounts(pRoot);
123809       }
123810     }
123811
123812     pCsr->isEof = 0;
123813     pCsr->iPrevId = iPrevId;
123814
123815     if( bEof ){
123816       pRoot->bEof = bEof;
123817     }else{
123818       /* Caution: pRoot may iterate through docids in ascending or descending
123819       ** order. For this reason, even though it seems more defensive, the
123820       ** do loop can not be written:
123821       **
123822       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
123823       */
123824       fts3EvalRestart(pCsr, pRoot, &rc);
123825       do {
123826         fts3EvalNextRow(pCsr, pRoot, &rc);
123827         assert( pRoot->bEof==0 );
123828       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
123829       fts3EvalTestDeferredAndNear(pCsr, &rc);
123830     }
123831   }
123832   return rc;
123833 }
123834
123835 /*
123836 ** This function is used by the matchinfo() module to query a phrase
123837 ** expression node for the following information:
123838 **
123839 **   1. The total number of occurrences of the phrase in each column of
123840 **      the FTS table (considering all rows), and
123841 **
123842 **   2. For each column, the number of rows in the table for which the
123843 **      column contains at least one instance of the phrase.
123844 **
123845 ** If no error occurs, SQLITE_OK is returned and the values for each column
123846 ** written into the array aiOut as follows:
123847 **
123848 **   aiOut[iCol*3 + 1] = Number of occurrences
123849 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
123850 **
123851 ** Caveats:
123852 **
123853 **   * If a phrase consists entirely of deferred tokens, then all output
123854 **     values are set to the number of documents in the table. In other
123855 **     words we assume that very common tokens occur exactly once in each
123856 **     column of each row of the table.
123857 **
123858 **   * If a phrase contains some deferred tokens (and some non-deferred
123859 **     tokens), count the potential occurrence identified by considering
123860 **     the non-deferred tokens instead of actual phrase occurrences.
123861 **
123862 **   * If the phrase is part of a NEAR expression, then only phrase instances
123863 **     that meet the NEAR constraint are included in the counts.
123864 */
123865 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
123866   Fts3Cursor *pCsr,               /* FTS cursor handle */
123867   Fts3Expr *pExpr,                /* Phrase expression */
123868   u32 *aiOut                      /* Array to write results into (see above) */
123869 ){
123870   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123871   int rc = SQLITE_OK;
123872   int iCol;
123873
123874   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
123875     assert( pCsr->nDoc>0 );
123876     for(iCol=0; iCol<pTab->nColumn; iCol++){
123877       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
123878       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
123879     }
123880   }else{
123881     rc = fts3EvalGatherStats(pCsr, pExpr);
123882     if( rc==SQLITE_OK ){
123883       assert( pExpr->aMI );
123884       for(iCol=0; iCol<pTab->nColumn; iCol++){
123885         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
123886         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
123887       }
123888     }
123889   }
123890
123891   return rc;
123892 }
123893
123894 /*
123895 ** The expression pExpr passed as the second argument to this function
123896 ** must be of type FTSQUERY_PHRASE.
123897 **
123898 ** The returned value is either NULL or a pointer to a buffer containing
123899 ** a position-list indicating the occurrences of the phrase in column iCol
123900 ** of the current row.
123901 **
123902 ** More specifically, the returned buffer contains 1 varint for each
123903 ** occurence of the phrase in the column, stored using the normal (delta+2)
123904 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
123905 ** if the requested column contains "a b X c d X X" and the position-list
123906 ** for 'X' is requested, the buffer returned may contain:
123907 **
123908 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
123909 **
123910 ** This function works regardless of whether or not the phrase is deferred,
123911 ** incremental, or neither.
123912 */
123913 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
123914   Fts3Cursor *pCsr,               /* FTS3 cursor object */
123915   Fts3Expr *pExpr,                /* Phrase to return doclist for */
123916   int iCol,                       /* Column to return position list for */
123917   char **ppOut                    /* OUT: Pointer to position list */
123918 ){
123919   Fts3Phrase *pPhrase = pExpr->pPhrase;
123920   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123921   char *pIter;
123922   int iThis;
123923   sqlite3_int64 iDocid;
123924
123925   /* If this phrase is applies specifically to some column other than
123926   ** column iCol, return a NULL pointer.  */
123927   *ppOut = 0;
123928   assert( iCol>=0 && iCol<pTab->nColumn );
123929   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
123930     return SQLITE_OK;
123931   }
123932
123933   iDocid = pExpr->iDocid;
123934   pIter = pPhrase->doclist.pList;
123935   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
123936     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
123937     int bOr = 0;
123938     u8 bEof = 0;
123939     Fts3Expr *p;
123940
123941     /* Check if this phrase descends from an OR expression node. If not,
123942     ** return NULL. Otherwise, the entry that corresponds to docid
123943     ** pCsr->iPrevId may lie earlier in the doclist buffer. */
123944     for(p=pExpr->pParent; p; p=p->pParent){
123945       if( p->eType==FTSQUERY_OR ) bOr = 1;
123946     }
123947     if( bOr==0 ) return SQLITE_OK;
123948
123949     /* This is the descendent of an OR node. In this case we cannot use
123950     ** an incremental phrase. Load the entire doclist for the phrase
123951     ** into memory in this case.  */
123952     if( pPhrase->bIncr ){
123953       int rc = SQLITE_OK;
123954       int bEofSave = pExpr->bEof;
123955       fts3EvalRestart(pCsr, pExpr, &rc);
123956       while( rc==SQLITE_OK && !pExpr->bEof ){
123957         fts3EvalNextRow(pCsr, pExpr, &rc);
123958         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
123959       }
123960       pIter = pPhrase->doclist.pList;
123961       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
123962       if( rc!=SQLITE_OK ) return rc;
123963     }
123964
123965     if( pExpr->bEof ){
123966       pIter = 0;
123967       iDocid = 0;
123968     }
123969     bEof = (pPhrase->doclist.nAll==0);
123970     assert( bDescDoclist==0 || bDescDoclist==1 );
123971     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
123972
123973     if( pCsr->bDesc==bDescDoclist ){
123974       int dummy;
123975       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
123976         sqlite3Fts3DoclistPrev(
123977             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
123978             &pIter, &iDocid, &dummy, &bEof
123979         );
123980       }
123981     }else{
123982       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
123983         sqlite3Fts3DoclistNext(
123984             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
123985             &pIter, &iDocid, &bEof
123986         );
123987       }
123988     }
123989
123990     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
123991   }
123992   if( pIter==0 ) return SQLITE_OK;
123993
123994   if( *pIter==0x01 ){
123995     pIter++;
123996     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
123997   }else{
123998     iThis = 0;
123999   }
124000   while( iThis<iCol ){
124001     fts3ColumnlistCopy(0, &pIter);
124002     if( *pIter==0x00 ) return 0;
124003     pIter++;
124004     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
124005   }
124006
124007   *ppOut = ((iCol==iThis)?pIter:0);
124008   return SQLITE_OK;
124009 }
124010
124011 /*
124012 ** Free all components of the Fts3Phrase structure that were allocated by
124013 ** the eval module. Specifically, this means to free:
124014 **
124015 **   * the contents of pPhrase->doclist, and
124016 **   * any Fts3MultiSegReader objects held by phrase tokens.
124017 */
124018 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
124019   if( pPhrase ){
124020     int i;
124021     sqlite3_free(pPhrase->doclist.aAll);
124022     fts3EvalInvalidatePoslist(pPhrase);
124023     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
124024     for(i=0; i<pPhrase->nToken; i++){
124025       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
124026       pPhrase->aToken[i].pSegcsr = 0;
124027     }
124028   }
124029 }
124030
124031
124032 /*
124033 ** Return SQLITE_CORRUPT_VTAB.
124034 */
124035 #ifdef SQLITE_DEBUG
124036 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
124037   return SQLITE_CORRUPT_VTAB;
124038 }
124039 #endif
124040
124041 #if !SQLITE_CORE
124042 /*
124043 ** Initialize API pointer table, if required.
124044 */
124045 SQLITE_API int sqlite3_extension_init(
124046   sqlite3 *db,
124047   char **pzErrMsg,
124048   const sqlite3_api_routines *pApi
124049 ){
124050   SQLITE_EXTENSION_INIT2(pApi)
124051   return sqlite3Fts3Init(db);
124052 }
124053 #endif
124054
124055 #endif
124056
124057 /************** End of fts3.c ************************************************/
124058 /************** Begin file fts3_aux.c ****************************************/
124059 /*
124060 ** 2011 Jan 27
124061 **
124062 ** The author disclaims copyright to this source code.  In place of
124063 ** a legal notice, here is a blessing:
124064 **
124065 **    May you do good and not evil.
124066 **    May you find forgiveness for yourself and forgive others.
124067 **    May you share freely, never taking more than you give.
124068 **
124069 ******************************************************************************
124070 **
124071 */
124072 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124073
124074 /* #include <string.h> */
124075 /* #include <assert.h> */
124076
124077 typedef struct Fts3auxTable Fts3auxTable;
124078 typedef struct Fts3auxCursor Fts3auxCursor;
124079
124080 struct Fts3auxTable {
124081   sqlite3_vtab base;              /* Base class used by SQLite core */
124082   Fts3Table *pFts3Tab;
124083 };
124084
124085 struct Fts3auxCursor {
124086   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
124087   Fts3MultiSegReader csr;        /* Must be right after "base" */
124088   Fts3SegFilter filter;
124089   char *zStop;
124090   int nStop;                      /* Byte-length of string zStop */
124091   int isEof;                      /* True if cursor is at EOF */
124092   sqlite3_int64 iRowid;           /* Current rowid */
124093
124094   int iCol;                       /* Current value of 'col' column */
124095   int nStat;                      /* Size of aStat[] array */
124096   struct Fts3auxColstats {
124097     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
124098     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
124099   } *aStat;
124100 };
124101
124102 /*
124103 ** Schema of the terms table.
124104 */
124105 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
124106
124107 /*
124108 ** This function does all the work for both the xConnect and xCreate methods.
124109 ** These tables have no persistent representation of their own, so xConnect
124110 ** and xCreate are identical operations.
124111 */
124112 static int fts3auxConnectMethod(
124113   sqlite3 *db,                    /* Database connection */
124114   void *pUnused,                  /* Unused */
124115   int argc,                       /* Number of elements in argv array */
124116   const char * const *argv,       /* xCreate/xConnect argument array */
124117   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
124118   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
124119 ){
124120   char const *zDb;                /* Name of database (e.g. "main") */
124121   char const *zFts3;              /* Name of fts3 table */
124122   int nDb;                        /* Result of strlen(zDb) */
124123   int nFts3;                      /* Result of strlen(zFts3) */
124124   int nByte;                      /* Bytes of space to allocate here */
124125   int rc;                         /* value returned by declare_vtab() */
124126   Fts3auxTable *p;                /* Virtual table object to return */
124127
124128   UNUSED_PARAMETER(pUnused);
124129
124130   /* The user should specify a single argument - the name of an fts3 table. */
124131   if( argc!=4 ){
124132     *pzErr = sqlite3_mprintf(
124133         "wrong number of arguments to fts4aux constructor"
124134     );
124135     return SQLITE_ERROR;
124136   }
124137
124138   zDb = argv[1];
124139   nDb = (int)strlen(zDb);
124140   zFts3 = argv[3];
124141   nFts3 = (int)strlen(zFts3);
124142
124143   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
124144   if( rc!=SQLITE_OK ) return rc;
124145
124146   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
124147   p = (Fts3auxTable *)sqlite3_malloc(nByte);
124148   if( !p ) return SQLITE_NOMEM;
124149   memset(p, 0, nByte);
124150
124151   p->pFts3Tab = (Fts3Table *)&p[1];
124152   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
124153   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
124154   p->pFts3Tab->db = db;
124155   p->pFts3Tab->nIndex = 1;
124156
124157   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
124158   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
124159   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
124160
124161   *ppVtab = (sqlite3_vtab *)p;
124162   return SQLITE_OK;
124163 }
124164
124165 /*
124166 ** This function does the work for both the xDisconnect and xDestroy methods.
124167 ** These tables have no persistent representation of their own, so xDisconnect
124168 ** and xDestroy are identical operations.
124169 */
124170 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
124171   Fts3auxTable *p = (Fts3auxTable *)pVtab;
124172   Fts3Table *pFts3 = p->pFts3Tab;
124173   int i;
124174
124175   /* Free any prepared statements held */
124176   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
124177     sqlite3_finalize(pFts3->aStmt[i]);
124178   }
124179   sqlite3_free(pFts3->zSegmentsTbl);
124180   sqlite3_free(p);
124181   return SQLITE_OK;
124182 }
124183
124184 #define FTS4AUX_EQ_CONSTRAINT 1
124185 #define FTS4AUX_GE_CONSTRAINT 2
124186 #define FTS4AUX_LE_CONSTRAINT 4
124187
124188 /*
124189 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
124190 */
124191 static int fts3auxBestIndexMethod(
124192   sqlite3_vtab *pVTab,
124193   sqlite3_index_info *pInfo
124194 ){
124195   int i;
124196   int iEq = -1;
124197   int iGe = -1;
124198   int iLe = -1;
124199
124200   UNUSED_PARAMETER(pVTab);
124201
124202   /* This vtab delivers always results in "ORDER BY term ASC" order. */
124203   if( pInfo->nOrderBy==1
124204    && pInfo->aOrderBy[0].iColumn==0
124205    && pInfo->aOrderBy[0].desc==0
124206   ){
124207     pInfo->orderByConsumed = 1;
124208   }
124209
124210   /* Search for equality and range constraints on the "term" column. */
124211   for(i=0; i<pInfo->nConstraint; i++){
124212     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
124213       int op = pInfo->aConstraint[i].op;
124214       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
124215       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
124216       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
124217       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
124218       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
124219     }
124220   }
124221
124222   if( iEq>=0 ){
124223     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
124224     pInfo->aConstraintUsage[iEq].argvIndex = 1;
124225     pInfo->estimatedCost = 5;
124226   }else{
124227     pInfo->idxNum = 0;
124228     pInfo->estimatedCost = 20000;
124229     if( iGe>=0 ){
124230       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
124231       pInfo->aConstraintUsage[iGe].argvIndex = 1;
124232       pInfo->estimatedCost /= 2;
124233     }
124234     if( iLe>=0 ){
124235       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
124236       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
124237       pInfo->estimatedCost /= 2;
124238     }
124239   }
124240
124241   return SQLITE_OK;
124242 }
124243
124244 /*
124245 ** xOpen - Open a cursor.
124246 */
124247 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
124248   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
124249
124250   UNUSED_PARAMETER(pVTab);
124251
124252   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
124253   if( !pCsr ) return SQLITE_NOMEM;
124254   memset(pCsr, 0, sizeof(Fts3auxCursor));
124255
124256   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
124257   return SQLITE_OK;
124258 }
124259
124260 /*
124261 ** xClose - Close a cursor.
124262 */
124263 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
124264   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
124265   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124266
124267   sqlite3Fts3SegmentsClose(pFts3);
124268   sqlite3Fts3SegReaderFinish(&pCsr->csr);
124269   sqlite3_free((void *)pCsr->filter.zTerm);
124270   sqlite3_free(pCsr->zStop);
124271   sqlite3_free(pCsr->aStat);
124272   sqlite3_free(pCsr);
124273   return SQLITE_OK;
124274 }
124275
124276 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
124277   if( nSize>pCsr->nStat ){
124278     struct Fts3auxColstats *aNew;
124279     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
124280         sizeof(struct Fts3auxColstats) * nSize
124281     );
124282     if( aNew==0 ) return SQLITE_NOMEM;
124283     memset(&aNew[pCsr->nStat], 0,
124284         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
124285     );
124286     pCsr->aStat = aNew;
124287     pCsr->nStat = nSize;
124288   }
124289   return SQLITE_OK;
124290 }
124291
124292 /*
124293 ** xNext - Advance the cursor to the next row, if any.
124294 */
124295 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
124296   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124297   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
124298   int rc;
124299
124300   /* Increment our pretend rowid value. */
124301   pCsr->iRowid++;
124302
124303   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
124304     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
124305   }
124306
124307   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
124308   if( rc==SQLITE_ROW ){
124309     int i = 0;
124310     int nDoclist = pCsr->csr.nDoclist;
124311     char *aDoclist = pCsr->csr.aDoclist;
124312     int iCol;
124313
124314     int eState = 0;
124315
124316     if( pCsr->zStop ){
124317       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
124318       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
124319       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
124320         pCsr->isEof = 1;
124321         return SQLITE_OK;
124322       }
124323     }
124324
124325     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
124326     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
124327     iCol = 0;
124328
124329     while( i<nDoclist ){
124330       sqlite3_int64 v = 0;
124331
124332       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
124333       switch( eState ){
124334         /* State 0. In this state the integer just read was a docid. */
124335         case 0:
124336           pCsr->aStat[0].nDoc++;
124337           eState = 1;
124338           iCol = 0;
124339           break;
124340
124341         /* State 1. In this state we are expecting either a 1, indicating
124342         ** that the following integer will be a column number, or the
124343         ** start of a position list for column 0.
124344         **
124345         ** The only difference between state 1 and state 2 is that if the
124346         ** integer encountered in state 1 is not 0 or 1, then we need to
124347         ** increment the column 0 "nDoc" count for this term.
124348         */
124349         case 1:
124350           assert( iCol==0 );
124351           if( v>1 ){
124352             pCsr->aStat[1].nDoc++;
124353           }
124354           eState = 2;
124355           /* fall through */
124356
124357         case 2:
124358           if( v==0 ){       /* 0x00. Next integer will be a docid. */
124359             eState = 0;
124360           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
124361             eState = 3;
124362           }else{            /* 2 or greater. A position. */
124363             pCsr->aStat[iCol+1].nOcc++;
124364             pCsr->aStat[0].nOcc++;
124365           }
124366           break;
124367
124368         /* State 3. The integer just read is a column number. */
124369         default: assert( eState==3 );
124370           iCol = (int)v;
124371           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
124372           pCsr->aStat[iCol+1].nDoc++;
124373           eState = 2;
124374           break;
124375       }
124376     }
124377
124378     pCsr->iCol = 0;
124379     rc = SQLITE_OK;
124380   }else{
124381     pCsr->isEof = 1;
124382   }
124383   return rc;
124384 }
124385
124386 /*
124387 ** xFilter - Initialize a cursor to point at the start of its data.
124388 */
124389 static int fts3auxFilterMethod(
124390   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
124391   int idxNum,                     /* Strategy index */
124392   const char *idxStr,             /* Unused */
124393   int nVal,                       /* Number of elements in apVal */
124394   sqlite3_value **apVal           /* Arguments for the indexing scheme */
124395 ){
124396   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124397   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
124398   int rc;
124399   int isScan;
124400
124401   UNUSED_PARAMETER(nVal);
124402   UNUSED_PARAMETER(idxStr);
124403
124404   assert( idxStr==0 );
124405   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
124406        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
124407        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
124408   );
124409   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
124410
124411   /* In case this cursor is being reused, close and zero it. */
124412   testcase(pCsr->filter.zTerm);
124413   sqlite3Fts3SegReaderFinish(&pCsr->csr);
124414   sqlite3_free((void *)pCsr->filter.zTerm);
124415   sqlite3_free(pCsr->aStat);
124416   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
124417
124418   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
124419   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
124420
124421   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
124422     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
124423     if( zStr ){
124424       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
124425       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
124426       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
124427     }
124428   }
124429   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
124430     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
124431     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
124432     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
124433     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
124434   }
124435
124436   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
124437       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
124438   );
124439   if( rc==SQLITE_OK ){
124440     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
124441   }
124442
124443   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
124444   return rc;
124445 }
124446
124447 /*
124448 ** xEof - Return true if the cursor is at EOF, or false otherwise.
124449 */
124450 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
124451   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124452   return pCsr->isEof;
124453 }
124454
124455 /*
124456 ** xColumn - Return a column value.
124457 */
124458 static int fts3auxColumnMethod(
124459   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
124460   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
124461   int iCol                        /* Index of column to read value from */
124462 ){
124463   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
124464
124465   assert( p->isEof==0 );
124466   if( iCol==0 ){        /* Column "term" */
124467     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
124468   }else if( iCol==1 ){  /* Column "col" */
124469     if( p->iCol ){
124470       sqlite3_result_int(pContext, p->iCol-1);
124471     }else{
124472       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
124473     }
124474   }else if( iCol==2 ){  /* Column "documents" */
124475     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
124476   }else{                /* Column "occurrences" */
124477     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
124478   }
124479
124480   return SQLITE_OK;
124481 }
124482
124483 /*
124484 ** xRowid - Return the current rowid for the cursor.
124485 */
124486 static int fts3auxRowidMethod(
124487   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
124488   sqlite_int64 *pRowid            /* OUT: Rowid value */
124489 ){
124490   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124491   *pRowid = pCsr->iRowid;
124492   return SQLITE_OK;
124493 }
124494
124495 /*
124496 ** Register the fts3aux module with database connection db. Return SQLITE_OK
124497 ** if successful or an error code if sqlite3_create_module() fails.
124498 */
124499 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
124500   static const sqlite3_module fts3aux_module = {
124501      0,                           /* iVersion      */
124502      fts3auxConnectMethod,        /* xCreate       */
124503      fts3auxConnectMethod,        /* xConnect      */
124504      fts3auxBestIndexMethod,      /* xBestIndex    */
124505      fts3auxDisconnectMethod,     /* xDisconnect   */
124506      fts3auxDisconnectMethod,     /* xDestroy      */
124507      fts3auxOpenMethod,           /* xOpen         */
124508      fts3auxCloseMethod,          /* xClose        */
124509      fts3auxFilterMethod,         /* xFilter       */
124510      fts3auxNextMethod,           /* xNext         */
124511      fts3auxEofMethod,            /* xEof          */
124512      fts3auxColumnMethod,         /* xColumn       */
124513      fts3auxRowidMethod,          /* xRowid        */
124514      0,                           /* xUpdate       */
124515      0,                           /* xBegin        */
124516      0,                           /* xSync         */
124517      0,                           /* xCommit       */
124518      0,                           /* xRollback     */
124519      0,                           /* xFindFunction */
124520      0,                           /* xRename       */
124521      0,                           /* xSavepoint    */
124522      0,                           /* xRelease      */
124523      0                            /* xRollbackTo   */
124524   };
124525   int rc;                         /* Return code */
124526
124527   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
124528   return rc;
124529 }
124530
124531 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124532
124533 /************** End of fts3_aux.c ********************************************/
124534 /************** Begin file fts3_expr.c ***************************************/
124535 /*
124536 ** 2008 Nov 28
124537 **
124538 ** The author disclaims copyright to this source code.  In place of
124539 ** a legal notice, here is a blessing:
124540 **
124541 **    May you do good and not evil.
124542 **    May you find forgiveness for yourself and forgive others.
124543 **    May you share freely, never taking more than you give.
124544 **
124545 ******************************************************************************
124546 **
124547 ** This module contains code that implements a parser for fts3 query strings
124548 ** (the right-hand argument to the MATCH operator). Because the supported
124549 ** syntax is relatively simple, the whole tokenizer/parser system is
124550 ** hand-coded.
124551 */
124552 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124553
124554 /*
124555 ** By default, this module parses the legacy syntax that has been
124556 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
124557 ** is defined, then it uses the new syntax. The differences between
124558 ** the new and the old syntaxes are:
124559 **
124560 **  a) The new syntax supports parenthesis. The old does not.
124561 **
124562 **  b) The new syntax supports the AND and NOT operators. The old does not.
124563 **
124564 **  c) The old syntax supports the "-" token qualifier. This is not
124565 **     supported by the new syntax (it is replaced by the NOT operator).
124566 **
124567 **  d) When using the old syntax, the OR operator has a greater precedence
124568 **     than an implicit AND. When using the new, both implicity and explicit
124569 **     AND operators have a higher precedence than OR.
124570 **
124571 ** If compiled with SQLITE_TEST defined, then this module exports the
124572 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
124573 ** to zero causes the module to use the old syntax. If it is set to
124574 ** non-zero the new syntax is activated. This is so both syntaxes can
124575 ** be tested using a single build of testfixture.
124576 **
124577 ** The following describes the syntax supported by the fts3 MATCH
124578 ** operator in a similar format to that used by the lemon parser
124579 ** generator. This module does not use actually lemon, it uses a
124580 ** custom parser.
124581 **
124582 **   query ::= andexpr (OR andexpr)*.
124583 **
124584 **   andexpr ::= notexpr (AND? notexpr)*.
124585 **
124586 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
124587 **   notexpr ::= LP query RP.
124588 **
124589 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
124590 **
124591 **   distance_opt ::= .
124592 **   distance_opt ::= / INTEGER.
124593 **
124594 **   phrase ::= TOKEN.
124595 **   phrase ::= COLUMN:TOKEN.
124596 **   phrase ::= "TOKEN TOKEN TOKEN...".
124597 */
124598
124599 #ifdef SQLITE_TEST
124600 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
124601 #else
124602 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
124603 #  define sqlite3_fts3_enable_parentheses 1
124604 # else
124605 #  define sqlite3_fts3_enable_parentheses 0
124606 # endif
124607 #endif
124608
124609 /*
124610 ** Default span for NEAR operators.
124611 */
124612 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
124613
124614 /* #include <string.h> */
124615 /* #include <assert.h> */
124616
124617 /*
124618 ** isNot:
124619 **   This variable is used by function getNextNode(). When getNextNode() is
124620 **   called, it sets ParseContext.isNot to true if the 'next node' is a
124621 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
124622 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
124623 **   zero.
124624 */
124625 typedef struct ParseContext ParseContext;
124626 struct ParseContext {
124627   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
124628   int iLangid;                        /* Language id used with tokenizer */
124629   const char **azCol;                 /* Array of column names for fts3 table */
124630   int bFts4;                          /* True to allow FTS4-only syntax */
124631   int nCol;                           /* Number of entries in azCol[] */
124632   int iDefaultCol;                    /* Default column to query */
124633   int isNot;                          /* True if getNextNode() sees a unary - */
124634   sqlite3_context *pCtx;              /* Write error message here */
124635   int nNest;                          /* Number of nested brackets */
124636 };
124637
124638 /*
124639 ** This function is equivalent to the standard isspace() function.
124640 **
124641 ** The standard isspace() can be awkward to use safely, because although it
124642 ** is defined to accept an argument of type int, its behaviour when passed
124643 ** an integer that falls outside of the range of the unsigned char type
124644 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
124645 ** is defined to accept an argument of type char, and always returns 0 for
124646 ** any values that fall outside of the range of the unsigned char type (i.e.
124647 ** negative values).
124648 */
124649 static int fts3isspace(char c){
124650   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
124651 }
124652
124653 /*
124654 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
124655 ** zero the memory before returning a pointer to it. If unsuccessful,
124656 ** return NULL.
124657 */
124658 static void *fts3MallocZero(int nByte){
124659   void *pRet = sqlite3_malloc(nByte);
124660   if( pRet ) memset(pRet, 0, nByte);
124661   return pRet;
124662 }
124663
124664 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
124665   sqlite3_tokenizer *pTokenizer,
124666   int iLangid,
124667   const char *z,
124668   int n,
124669   sqlite3_tokenizer_cursor **ppCsr
124670 ){
124671   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
124672   sqlite3_tokenizer_cursor *pCsr = 0;
124673   int rc;
124674
124675   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
124676   assert( rc==SQLITE_OK || pCsr==0 );
124677   if( rc==SQLITE_OK ){
124678     pCsr->pTokenizer = pTokenizer;
124679     if( pModule->iVersion>=1 ){
124680       rc = pModule->xLanguageid(pCsr, iLangid);
124681       if( rc!=SQLITE_OK ){
124682         pModule->xClose(pCsr);
124683         pCsr = 0;
124684       }
124685     }
124686   }
124687   *ppCsr = pCsr;
124688   return rc;
124689 }
124690
124691
124692 /*
124693 ** Extract the next token from buffer z (length n) using the tokenizer
124694 ** and other information (column names etc.) in pParse. Create an Fts3Expr
124695 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
124696 ** single token and set *ppExpr to point to it. If the end of the buffer is
124697 ** reached before a token is found, set *ppExpr to zero. It is the
124698 ** responsibility of the caller to eventually deallocate the allocated
124699 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
124700 **
124701 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
124702 ** fails.
124703 */
124704 static int getNextToken(
124705   ParseContext *pParse,                   /* fts3 query parse context */
124706   int iCol,                               /* Value for Fts3Phrase.iColumn */
124707   const char *z, int n,                   /* Input string */
124708   Fts3Expr **ppExpr,                      /* OUT: expression */
124709   int *pnConsumed                         /* OUT: Number of bytes consumed */
124710 ){
124711   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
124712   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
124713   int rc;
124714   sqlite3_tokenizer_cursor *pCursor;
124715   Fts3Expr *pRet = 0;
124716   int nConsumed = 0;
124717
124718   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
124719   if( rc==SQLITE_OK ){
124720     const char *zToken;
124721     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
124722     int nByte;                               /* total space to allocate */
124723
124724     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
124725     if( rc==SQLITE_OK ){
124726       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
124727       pRet = (Fts3Expr *)fts3MallocZero(nByte);
124728       if( !pRet ){
124729         rc = SQLITE_NOMEM;
124730       }else{
124731         pRet->eType = FTSQUERY_PHRASE;
124732         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
124733         pRet->pPhrase->nToken = 1;
124734         pRet->pPhrase->iColumn = iCol;
124735         pRet->pPhrase->aToken[0].n = nToken;
124736         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
124737         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
124738
124739         if( iEnd<n && z[iEnd]=='*' ){
124740           pRet->pPhrase->aToken[0].isPrefix = 1;
124741           iEnd++;
124742         }
124743
124744         while( 1 ){
124745           if( !sqlite3_fts3_enable_parentheses
124746            && iStart>0 && z[iStart-1]=='-'
124747           ){
124748             pParse->isNot = 1;
124749             iStart--;
124750           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
124751             pRet->pPhrase->aToken[0].bFirst = 1;
124752             iStart--;
124753           }else{
124754             break;
124755           }
124756         }
124757
124758       }
124759       nConsumed = iEnd;
124760     }
124761
124762     pModule->xClose(pCursor);
124763   }
124764
124765   *pnConsumed = nConsumed;
124766   *ppExpr = pRet;
124767   return rc;
124768 }
124769
124770
124771 /*
124772 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
124773 ** then free the old allocation.
124774 */
124775 static void *fts3ReallocOrFree(void *pOrig, int nNew){
124776   void *pRet = sqlite3_realloc(pOrig, nNew);
124777   if( !pRet ){
124778     sqlite3_free(pOrig);
124779   }
124780   return pRet;
124781 }
124782
124783 /*
124784 ** Buffer zInput, length nInput, contains the contents of a quoted string
124785 ** that appeared as part of an fts3 query expression. Neither quote character
124786 ** is included in the buffer. This function attempts to tokenize the entire
124787 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
124788 ** containing the results.
124789 **
124790 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
124791 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
124792 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
124793 ** to 0.
124794 */
124795 static int getNextString(
124796   ParseContext *pParse,                   /* fts3 query parse context */
124797   const char *zInput, int nInput,         /* Input string */
124798   Fts3Expr **ppExpr                       /* OUT: expression */
124799 ){
124800   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
124801   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
124802   int rc;
124803   Fts3Expr *p = 0;
124804   sqlite3_tokenizer_cursor *pCursor = 0;
124805   char *zTemp = 0;
124806   int nTemp = 0;
124807
124808   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
124809   int nToken = 0;
124810
124811   /* The final Fts3Expr data structure, including the Fts3Phrase,
124812   ** Fts3PhraseToken structures token buffers are all stored as a single
124813   ** allocation so that the expression can be freed with a single call to
124814   ** sqlite3_free(). Setting this up requires a two pass approach.
124815   **
124816   ** The first pass, in the block below, uses a tokenizer cursor to iterate
124817   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
124818   ** to assemble data in two dynamic buffers:
124819   **
124820   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
124821   **             structure, followed by the array of Fts3PhraseToken
124822   **             structures. This pass only populates the Fts3PhraseToken array.
124823   **
124824   **   Buffer zTemp: Contains copies of all tokens.
124825   **
124826   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
124827   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
124828   ** structures.
124829   */
124830   rc = sqlite3Fts3OpenTokenizer(
124831       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
124832   if( rc==SQLITE_OK ){
124833     int ii;
124834     for(ii=0; rc==SQLITE_OK; ii++){
124835       const char *zByte;
124836       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
124837       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
124838       if( rc==SQLITE_OK ){
124839         Fts3PhraseToken *pToken;
124840
124841         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
124842         if( !p ) goto no_mem;
124843
124844         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
124845         if( !zTemp ) goto no_mem;
124846
124847         assert( nToken==ii );
124848         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
124849         memset(pToken, 0, sizeof(Fts3PhraseToken));
124850
124851         memcpy(&zTemp[nTemp], zByte, nByte);
124852         nTemp += nByte;
124853
124854         pToken->n = nByte;
124855         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
124856         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
124857         nToken = ii+1;
124858       }
124859     }
124860
124861     pModule->xClose(pCursor);
124862     pCursor = 0;
124863   }
124864
124865   if( rc==SQLITE_DONE ){
124866     int jj;
124867     char *zBuf = 0;
124868
124869     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
124870     if( !p ) goto no_mem;
124871     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
124872     p->eType = FTSQUERY_PHRASE;
124873     p->pPhrase = (Fts3Phrase *)&p[1];
124874     p->pPhrase->iColumn = pParse->iDefaultCol;
124875     p->pPhrase->nToken = nToken;
124876
124877     zBuf = (char *)&p->pPhrase->aToken[nToken];
124878     if( zTemp ){
124879       memcpy(zBuf, zTemp, nTemp);
124880       sqlite3_free(zTemp);
124881     }else{
124882       assert( nTemp==0 );
124883     }
124884
124885     for(jj=0; jj<p->pPhrase->nToken; jj++){
124886       p->pPhrase->aToken[jj].z = zBuf;
124887       zBuf += p->pPhrase->aToken[jj].n;
124888     }
124889     rc = SQLITE_OK;
124890   }
124891
124892   *ppExpr = p;
124893   return rc;
124894 no_mem:
124895
124896   if( pCursor ){
124897     pModule->xClose(pCursor);
124898   }
124899   sqlite3_free(zTemp);
124900   sqlite3_free(p);
124901   *ppExpr = 0;
124902   return SQLITE_NOMEM;
124903 }
124904
124905 /*
124906 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
124907 ** call fts3ExprParse(). So this forward declaration is required.
124908 */
124909 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
124910
124911 /*
124912 ** The output variable *ppExpr is populated with an allocated Fts3Expr
124913 ** structure, or set to 0 if the end of the input buffer is reached.
124914 **
124915 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
124916 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
124917 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
124918 */
124919 static int getNextNode(
124920   ParseContext *pParse,                   /* fts3 query parse context */
124921   const char *z, int n,                   /* Input string */
124922   Fts3Expr **ppExpr,                      /* OUT: expression */
124923   int *pnConsumed                         /* OUT: Number of bytes consumed */
124924 ){
124925   static const struct Fts3Keyword {
124926     char *z;                              /* Keyword text */
124927     unsigned char n;                      /* Length of the keyword */
124928     unsigned char parenOnly;              /* Only valid in paren mode */
124929     unsigned char eType;                  /* Keyword code */
124930   } aKeyword[] = {
124931     { "OR" ,  2, 0, FTSQUERY_OR   },
124932     { "AND",  3, 1, FTSQUERY_AND  },
124933     { "NOT",  3, 1, FTSQUERY_NOT  },
124934     { "NEAR", 4, 0, FTSQUERY_NEAR }
124935   };
124936   int ii;
124937   int iCol;
124938   int iColLen;
124939   int rc;
124940   Fts3Expr *pRet = 0;
124941
124942   const char *zInput = z;
124943   int nInput = n;
124944
124945   pParse->isNot = 0;
124946
124947   /* Skip over any whitespace before checking for a keyword, an open or
124948   ** close bracket, or a quoted string.
124949   */
124950   while( nInput>0 && fts3isspace(*zInput) ){
124951     nInput--;
124952     zInput++;
124953   }
124954   if( nInput==0 ){
124955     return SQLITE_DONE;
124956   }
124957
124958   /* See if we are dealing with a keyword. */
124959   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
124960     const struct Fts3Keyword *pKey = &aKeyword[ii];
124961
124962     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
124963       continue;
124964     }
124965
124966     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
124967       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
124968       int nKey = pKey->n;
124969       char cNext;
124970
124971       /* If this is a "NEAR" keyword, check for an explicit nearness. */
124972       if( pKey->eType==FTSQUERY_NEAR ){
124973         assert( nKey==4 );
124974         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
124975           nNear = 0;
124976           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
124977             nNear = nNear * 10 + (zInput[nKey] - '0');
124978           }
124979         }
124980       }
124981
124982       /* At this point this is probably a keyword. But for that to be true,
124983       ** the next byte must contain either whitespace, an open or close
124984       ** parenthesis, a quote character, or EOF.
124985       */
124986       cNext = zInput[nKey];
124987       if( fts3isspace(cNext)
124988        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
124989       ){
124990         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
124991         if( !pRet ){
124992           return SQLITE_NOMEM;
124993         }
124994         pRet->eType = pKey->eType;
124995         pRet->nNear = nNear;
124996         *ppExpr = pRet;
124997         *pnConsumed = (int)((zInput - z) + nKey);
124998         return SQLITE_OK;
124999       }
125000
125001       /* Turns out that wasn't a keyword after all. This happens if the
125002       ** user has supplied a token such as "ORacle". Continue.
125003       */
125004     }
125005   }
125006
125007   /* Check for an open bracket. */
125008   if( sqlite3_fts3_enable_parentheses ){
125009     if( *zInput=='(' ){
125010       int nConsumed;
125011       pParse->nNest++;
125012       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
125013       if( rc==SQLITE_OK && !*ppExpr ){
125014         rc = SQLITE_DONE;
125015       }
125016       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
125017       return rc;
125018     }
125019
125020     /* Check for a close bracket. */
125021     if( *zInput==')' ){
125022       pParse->nNest--;
125023       *pnConsumed = (int)((zInput - z) + 1);
125024       return SQLITE_DONE;
125025     }
125026   }
125027
125028   /* See if we are dealing with a quoted phrase. If this is the case, then
125029   ** search for the closing quote and pass the whole string to getNextString()
125030   ** for processing. This is easy to do, as fts3 has no syntax for escaping
125031   ** a quote character embedded in a string.
125032   */
125033   if( *zInput=='"' ){
125034     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
125035     *pnConsumed = (int)((zInput - z) + ii + 1);
125036     if( ii==nInput ){
125037       return SQLITE_ERROR;
125038     }
125039     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
125040   }
125041
125042
125043   /* If control flows to this point, this must be a regular token, or
125044   ** the end of the input. Read a regular token using the sqlite3_tokenizer
125045   ** interface. Before doing so, figure out if there is an explicit
125046   ** column specifier for the token.
125047   **
125048   ** TODO: Strangely, it is not possible to associate a column specifier
125049   ** with a quoted phrase, only with a single token. Not sure if this was
125050   ** an implementation artifact or an intentional decision when fts3 was
125051   ** first implemented. Whichever it was, this module duplicates the
125052   ** limitation.
125053   */
125054   iCol = pParse->iDefaultCol;
125055   iColLen = 0;
125056   for(ii=0; ii<pParse->nCol; ii++){
125057     const char *zStr = pParse->azCol[ii];
125058     int nStr = (int)strlen(zStr);
125059     if( nInput>nStr && zInput[nStr]==':'
125060      && sqlite3_strnicmp(zStr, zInput, nStr)==0
125061     ){
125062       iCol = ii;
125063       iColLen = (int)((zInput - z) + nStr + 1);
125064       break;
125065     }
125066   }
125067   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
125068   *pnConsumed += iColLen;
125069   return rc;
125070 }
125071
125072 /*
125073 ** The argument is an Fts3Expr structure for a binary operator (any type
125074 ** except an FTSQUERY_PHRASE). Return an integer value representing the
125075 ** precedence of the operator. Lower values have a higher precedence (i.e.
125076 ** group more tightly). For example, in the C language, the == operator
125077 ** groups more tightly than ||, and would therefore have a higher precedence.
125078 **
125079 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
125080 ** is defined), the order of the operators in precedence from highest to
125081 ** lowest is:
125082 **
125083 **   NEAR
125084 **   NOT
125085 **   AND (including implicit ANDs)
125086 **   OR
125087 **
125088 ** Note that when using the old query syntax, the OR operator has a higher
125089 ** precedence than the AND operator.
125090 */
125091 static int opPrecedence(Fts3Expr *p){
125092   assert( p->eType!=FTSQUERY_PHRASE );
125093   if( sqlite3_fts3_enable_parentheses ){
125094     return p->eType;
125095   }else if( p->eType==FTSQUERY_NEAR ){
125096     return 1;
125097   }else if( p->eType==FTSQUERY_OR ){
125098     return 2;
125099   }
125100   assert( p->eType==FTSQUERY_AND );
125101   return 3;
125102 }
125103
125104 /*
125105 ** Argument ppHead contains a pointer to the current head of a query
125106 ** expression tree being parsed. pPrev is the expression node most recently
125107 ** inserted into the tree. This function adds pNew, which is always a binary
125108 ** operator node, into the expression tree based on the relative precedence
125109 ** of pNew and the existing nodes of the tree. This may result in the head
125110 ** of the tree changing, in which case *ppHead is set to the new root node.
125111 */
125112 static void insertBinaryOperator(
125113   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
125114   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
125115   Fts3Expr *pNew           /* New binary node to insert into expression tree */
125116 ){
125117   Fts3Expr *pSplit = pPrev;
125118   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
125119     pSplit = pSplit->pParent;
125120   }
125121
125122   if( pSplit->pParent ){
125123     assert( pSplit->pParent->pRight==pSplit );
125124     pSplit->pParent->pRight = pNew;
125125     pNew->pParent = pSplit->pParent;
125126   }else{
125127     *ppHead = pNew;
125128   }
125129   pNew->pLeft = pSplit;
125130   pSplit->pParent = pNew;
125131 }
125132
125133 /*
125134 ** Parse the fts3 query expression found in buffer z, length n. This function
125135 ** returns either when the end of the buffer is reached or an unmatched
125136 ** closing bracket - ')' - is encountered.
125137 **
125138 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
125139 ** parsed form of the expression and *pnConsumed is set to the number of
125140 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
125141 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
125142 */
125143 static int fts3ExprParse(
125144   ParseContext *pParse,                   /* fts3 query parse context */
125145   const char *z, int n,                   /* Text of MATCH query */
125146   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
125147   int *pnConsumed                         /* OUT: Number of bytes consumed */
125148 ){
125149   Fts3Expr *pRet = 0;
125150   Fts3Expr *pPrev = 0;
125151   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
125152   int nIn = n;
125153   const char *zIn = z;
125154   int rc = SQLITE_OK;
125155   int isRequirePhrase = 1;
125156
125157   while( rc==SQLITE_OK ){
125158     Fts3Expr *p = 0;
125159     int nByte = 0;
125160     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
125161     if( rc==SQLITE_OK ){
125162       int isPhrase;
125163
125164       if( !sqlite3_fts3_enable_parentheses
125165        && p->eType==FTSQUERY_PHRASE && pParse->isNot
125166       ){
125167         /* Create an implicit NOT operator. */
125168         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
125169         if( !pNot ){
125170           sqlite3Fts3ExprFree(p);
125171           rc = SQLITE_NOMEM;
125172           goto exprparse_out;
125173         }
125174         pNot->eType = FTSQUERY_NOT;
125175         pNot->pRight = p;
125176         if( pNotBranch ){
125177           pNot->pLeft = pNotBranch;
125178         }
125179         pNotBranch = pNot;
125180         p = pPrev;
125181       }else{
125182         int eType = p->eType;
125183         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
125184
125185         /* The isRequirePhrase variable is set to true if a phrase or
125186         ** an expression contained in parenthesis is required. If a
125187         ** binary operator (AND, OR, NOT or NEAR) is encounted when
125188         ** isRequirePhrase is set, this is a syntax error.
125189         */
125190         if( !isPhrase && isRequirePhrase ){
125191           sqlite3Fts3ExprFree(p);
125192           rc = SQLITE_ERROR;
125193           goto exprparse_out;
125194         }
125195
125196         if( isPhrase && !isRequirePhrase ){
125197           /* Insert an implicit AND operator. */
125198           Fts3Expr *pAnd;
125199           assert( pRet && pPrev );
125200           pAnd = fts3MallocZero(sizeof(Fts3Expr));
125201           if( !pAnd ){
125202             sqlite3Fts3ExprFree(p);
125203             rc = SQLITE_NOMEM;
125204             goto exprparse_out;
125205           }
125206           pAnd->eType = FTSQUERY_AND;
125207           insertBinaryOperator(&pRet, pPrev, pAnd);
125208           pPrev = pAnd;
125209         }
125210
125211         /* This test catches attempts to make either operand of a NEAR
125212         ** operator something other than a phrase. For example, either of
125213         ** the following:
125214         **
125215         **    (bracketed expression) NEAR phrase
125216         **    phrase NEAR (bracketed expression)
125217         **
125218         ** Return an error in either case.
125219         */
125220         if( pPrev && (
125221             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
125222          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
125223         )){
125224           sqlite3Fts3ExprFree(p);
125225           rc = SQLITE_ERROR;
125226           goto exprparse_out;
125227         }
125228
125229         if( isPhrase ){
125230           if( pRet ){
125231             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
125232             pPrev->pRight = p;
125233             p->pParent = pPrev;
125234           }else{
125235             pRet = p;
125236           }
125237         }else{
125238           insertBinaryOperator(&pRet, pPrev, p);
125239         }
125240         isRequirePhrase = !isPhrase;
125241       }
125242       assert( nByte>0 );
125243     }
125244     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
125245     nIn -= nByte;
125246     zIn += nByte;
125247     pPrev = p;
125248   }
125249
125250   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
125251     rc = SQLITE_ERROR;
125252   }
125253
125254   if( rc==SQLITE_DONE ){
125255     rc = SQLITE_OK;
125256     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
125257       if( !pRet ){
125258         rc = SQLITE_ERROR;
125259       }else{
125260         Fts3Expr *pIter = pNotBranch;
125261         while( pIter->pLeft ){
125262           pIter = pIter->pLeft;
125263         }
125264         pIter->pLeft = pRet;
125265         pRet = pNotBranch;
125266       }
125267     }
125268   }
125269   *pnConsumed = n - nIn;
125270
125271 exprparse_out:
125272   if( rc!=SQLITE_OK ){
125273     sqlite3Fts3ExprFree(pRet);
125274     sqlite3Fts3ExprFree(pNotBranch);
125275     pRet = 0;
125276   }
125277   *ppExpr = pRet;
125278   return rc;
125279 }
125280
125281 /*
125282 ** Parameters z and n contain a pointer to and length of a buffer containing
125283 ** an fts3 query expression, respectively. This function attempts to parse the
125284 ** query expression and create a tree of Fts3Expr structures representing the
125285 ** parsed expression. If successful, *ppExpr is set to point to the head
125286 ** of the parsed expression tree and SQLITE_OK is returned. If an error
125287 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
125288 ** error) is returned and *ppExpr is set to 0.
125289 **
125290 ** If parameter n is a negative number, then z is assumed to point to a
125291 ** nul-terminated string and the length is determined using strlen().
125292 **
125293 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
125294 ** use to normalize query tokens while parsing the expression. The azCol[]
125295 ** array, which is assumed to contain nCol entries, should contain the names
125296 ** of each column in the target fts3 table, in order from left to right.
125297 ** Column names must be nul-terminated strings.
125298 **
125299 ** The iDefaultCol parameter should be passed the index of the table column
125300 ** that appears on the left-hand-side of the MATCH operator (the default
125301 ** column to match against for tokens for which a column name is not explicitly
125302 ** specified as part of the query string), or -1 if tokens may by default
125303 ** match any table column.
125304 */
125305 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
125306   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
125307   int iLangid,                        /* Language id for tokenizer */
125308   char **azCol,                       /* Array of column names for fts3 table */
125309   int bFts4,                          /* True to allow FTS4-only syntax */
125310   int nCol,                           /* Number of entries in azCol[] */
125311   int iDefaultCol,                    /* Default column to query */
125312   const char *z, int n,               /* Text of MATCH query */
125313   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
125314 ){
125315   int nParsed;
125316   int rc;
125317   ParseContext sParse;
125318
125319   memset(&sParse, 0, sizeof(ParseContext));
125320   sParse.pTokenizer = pTokenizer;
125321   sParse.iLangid = iLangid;
125322   sParse.azCol = (const char **)azCol;
125323   sParse.nCol = nCol;
125324   sParse.iDefaultCol = iDefaultCol;
125325   sParse.bFts4 = bFts4;
125326   if( z==0 ){
125327     *ppExpr = 0;
125328     return SQLITE_OK;
125329   }
125330   if( n<0 ){
125331     n = (int)strlen(z);
125332   }
125333   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
125334
125335   /* Check for mismatched parenthesis */
125336   if( rc==SQLITE_OK && sParse.nNest ){
125337     rc = SQLITE_ERROR;
125338     sqlite3Fts3ExprFree(*ppExpr);
125339     *ppExpr = 0;
125340   }
125341
125342   return rc;
125343 }
125344
125345 /*
125346 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
125347 */
125348 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
125349   if( p ){
125350     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
125351     sqlite3Fts3ExprFree(p->pLeft);
125352     sqlite3Fts3ExprFree(p->pRight);
125353     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
125354     sqlite3_free(p->aMI);
125355     sqlite3_free(p);
125356   }
125357 }
125358
125359 /****************************************************************************
125360 *****************************************************************************
125361 ** Everything after this point is just test code.
125362 */
125363
125364 #ifdef SQLITE_TEST
125365
125366 /* #include <stdio.h> */
125367
125368 /*
125369 ** Function to query the hash-table of tokenizers (see README.tokenizers).
125370 */
125371 static int queryTestTokenizer(
125372   sqlite3 *db,
125373   const char *zName,
125374   const sqlite3_tokenizer_module **pp
125375 ){
125376   int rc;
125377   sqlite3_stmt *pStmt;
125378   const char zSql[] = "SELECT fts3_tokenizer(?)";
125379
125380   *pp = 0;
125381   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125382   if( rc!=SQLITE_OK ){
125383     return rc;
125384   }
125385
125386   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
125387   if( SQLITE_ROW==sqlite3_step(pStmt) ){
125388     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
125389       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
125390     }
125391   }
125392
125393   return sqlite3_finalize(pStmt);
125394 }
125395
125396 /*
125397 ** Return a pointer to a buffer containing a text representation of the
125398 ** expression passed as the first argument. The buffer is obtained from
125399 ** sqlite3_malloc(). It is the responsibility of the caller to use
125400 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
125401 ** NULL is returned.
125402 **
125403 ** If the second argument is not NULL, then its contents are prepended to
125404 ** the returned expression text and then freed using sqlite3_free().
125405 */
125406 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
125407   switch( pExpr->eType ){
125408     case FTSQUERY_PHRASE: {
125409       Fts3Phrase *pPhrase = pExpr->pPhrase;
125410       int i;
125411       zBuf = sqlite3_mprintf(
125412           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
125413       for(i=0; zBuf && i<pPhrase->nToken; i++){
125414         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
125415             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
125416             (pPhrase->aToken[i].isPrefix?"+":"")
125417         );
125418       }
125419       return zBuf;
125420     }
125421
125422     case FTSQUERY_NEAR:
125423       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
125424       break;
125425     case FTSQUERY_NOT:
125426       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
125427       break;
125428     case FTSQUERY_AND:
125429       zBuf = sqlite3_mprintf("%zAND ", zBuf);
125430       break;
125431     case FTSQUERY_OR:
125432       zBuf = sqlite3_mprintf("%zOR ", zBuf);
125433       break;
125434   }
125435
125436   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
125437   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
125438   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
125439
125440   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
125441   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
125442
125443   return zBuf;
125444 }
125445
125446 /*
125447 ** This is the implementation of a scalar SQL function used to test the
125448 ** expression parser. It should be called as follows:
125449 **
125450 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
125451 **
125452 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
125453 ** to parse the query expression (see README.tokenizers). The second argument
125454 ** is the query expression to parse. Each subsequent argument is the name
125455 ** of a column of the fts3 table that the query expression may refer to.
125456 ** For example:
125457 **
125458 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
125459 */
125460 static void fts3ExprTest(
125461   sqlite3_context *context,
125462   int argc,
125463   sqlite3_value **argv
125464 ){
125465   sqlite3_tokenizer_module const *pModule = 0;
125466   sqlite3_tokenizer *pTokenizer = 0;
125467   int rc;
125468   char **azCol = 0;
125469   const char *zExpr;
125470   int nExpr;
125471   int nCol;
125472   int ii;
125473   Fts3Expr *pExpr;
125474   char *zBuf = 0;
125475   sqlite3 *db = sqlite3_context_db_handle(context);
125476
125477   if( argc<3 ){
125478     sqlite3_result_error(context,
125479         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
125480     );
125481     return;
125482   }
125483
125484   rc = queryTestTokenizer(db,
125485                           (const char *)sqlite3_value_text(argv[0]), &pModule);
125486   if( rc==SQLITE_NOMEM ){
125487     sqlite3_result_error_nomem(context);
125488     goto exprtest_out;
125489   }else if( !pModule ){
125490     sqlite3_result_error(context, "No such tokenizer module", -1);
125491     goto exprtest_out;
125492   }
125493
125494   rc = pModule->xCreate(0, 0, &pTokenizer);
125495   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
125496   if( rc==SQLITE_NOMEM ){
125497     sqlite3_result_error_nomem(context);
125498     goto exprtest_out;
125499   }
125500   pTokenizer->pModule = pModule;
125501
125502   zExpr = (const char *)sqlite3_value_text(argv[1]);
125503   nExpr = sqlite3_value_bytes(argv[1]);
125504   nCol = argc-2;
125505   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
125506   if( !azCol ){
125507     sqlite3_result_error_nomem(context);
125508     goto exprtest_out;
125509   }
125510   for(ii=0; ii<nCol; ii++){
125511     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
125512   }
125513
125514   rc = sqlite3Fts3ExprParse(
125515       pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
125516   );
125517   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
125518     sqlite3_result_error(context, "Error parsing expression", -1);
125519   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
125520     sqlite3_result_error_nomem(context);
125521   }else{
125522     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
125523     sqlite3_free(zBuf);
125524   }
125525
125526   sqlite3Fts3ExprFree(pExpr);
125527
125528 exprtest_out:
125529   if( pModule && pTokenizer ){
125530     rc = pModule->xDestroy(pTokenizer);
125531   }
125532   sqlite3_free(azCol);
125533 }
125534
125535 /*
125536 ** Register the query expression parser test function fts3_exprtest()
125537 ** with database connection db.
125538 */
125539 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
125540   return sqlite3_create_function(
125541       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
125542   );
125543 }
125544
125545 #endif
125546 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125547
125548 /************** End of fts3_expr.c *******************************************/
125549 /************** Begin file fts3_hash.c ***************************************/
125550 /*
125551 ** 2001 September 22
125552 **
125553 ** The author disclaims copyright to this source code.  In place of
125554 ** a legal notice, here is a blessing:
125555 **
125556 **    May you do good and not evil.
125557 **    May you find forgiveness for yourself and forgive others.
125558 **    May you share freely, never taking more than you give.
125559 **
125560 *************************************************************************
125561 ** This is the implementation of generic hash-tables used in SQLite.
125562 ** We've modified it slightly to serve as a standalone hash table
125563 ** implementation for the full-text indexing module.
125564 */
125565
125566 /*
125567 ** The code in this file is only compiled if:
125568 **
125569 **     * The FTS3 module is being built as an extension
125570 **       (in which case SQLITE_CORE is not defined), or
125571 **
125572 **     * The FTS3 module is being built into the core of
125573 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
125574 */
125575 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125576
125577 /* #include <assert.h> */
125578 /* #include <stdlib.h> */
125579 /* #include <string.h> */
125580
125581
125582 /*
125583 ** Malloc and Free functions
125584 */
125585 static void *fts3HashMalloc(int n){
125586   void *p = sqlite3_malloc(n);
125587   if( p ){
125588     memset(p, 0, n);
125589   }
125590   return p;
125591 }
125592 static void fts3HashFree(void *p){
125593   sqlite3_free(p);
125594 }
125595
125596 /* Turn bulk memory into a hash table object by initializing the
125597 ** fields of the Hash structure.
125598 **
125599 ** "pNew" is a pointer to the hash table that is to be initialized.
125600 ** keyClass is one of the constants
125601 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
125602 ** determines what kind of key the hash table will use.  "copyKey" is
125603 ** true if the hash table should make its own private copy of keys and
125604 ** false if it should just use the supplied pointer.
125605 */
125606 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
125607   assert( pNew!=0 );
125608   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
125609   pNew->keyClass = keyClass;
125610   pNew->copyKey = copyKey;
125611   pNew->first = 0;
125612   pNew->count = 0;
125613   pNew->htsize = 0;
125614   pNew->ht = 0;
125615 }
125616
125617 /* Remove all entries from a hash table.  Reclaim all memory.
125618 ** Call this routine to delete a hash table or to reset a hash table
125619 ** to the empty state.
125620 */
125621 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
125622   Fts3HashElem *elem;         /* For looping over all elements of the table */
125623
125624   assert( pH!=0 );
125625   elem = pH->first;
125626   pH->first = 0;
125627   fts3HashFree(pH->ht);
125628   pH->ht = 0;
125629   pH->htsize = 0;
125630   while( elem ){
125631     Fts3HashElem *next_elem = elem->next;
125632     if( pH->copyKey && elem->pKey ){
125633       fts3HashFree(elem->pKey);
125634     }
125635     fts3HashFree(elem);
125636     elem = next_elem;
125637   }
125638   pH->count = 0;
125639 }
125640
125641 /*
125642 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
125643 */
125644 static int fts3StrHash(const void *pKey, int nKey){
125645   const char *z = (const char *)pKey;
125646   int h = 0;
125647   if( nKey<=0 ) nKey = (int) strlen(z);
125648   while( nKey > 0  ){
125649     h = (h<<3) ^ h ^ *z++;
125650     nKey--;
125651   }
125652   return h & 0x7fffffff;
125653 }
125654 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
125655   if( n1!=n2 ) return 1;
125656   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
125657 }
125658
125659 /*
125660 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
125661 */
125662 static int fts3BinHash(const void *pKey, int nKey){
125663   int h = 0;
125664   const char *z = (const char *)pKey;
125665   while( nKey-- > 0 ){
125666     h = (h<<3) ^ h ^ *(z++);
125667   }
125668   return h & 0x7fffffff;
125669 }
125670 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
125671   if( n1!=n2 ) return 1;
125672   return memcmp(pKey1,pKey2,n1);
125673 }
125674
125675 /*
125676 ** Return a pointer to the appropriate hash function given the key class.
125677 **
125678 ** The C syntax in this function definition may be unfamilar to some
125679 ** programmers, so we provide the following additional explanation:
125680 **
125681 ** The name of the function is "ftsHashFunction".  The function takes a
125682 ** single parameter "keyClass".  The return value of ftsHashFunction()
125683 ** is a pointer to another function.  Specifically, the return value
125684 ** of ftsHashFunction() is a pointer to a function that takes two parameters
125685 ** with types "const void*" and "int" and returns an "int".
125686 */
125687 static int (*ftsHashFunction(int keyClass))(const void*,int){
125688   if( keyClass==FTS3_HASH_STRING ){
125689     return &fts3StrHash;
125690   }else{
125691     assert( keyClass==FTS3_HASH_BINARY );
125692     return &fts3BinHash;
125693   }
125694 }
125695
125696 /*
125697 ** Return a pointer to the appropriate hash function given the key class.
125698 **
125699 ** For help in interpreted the obscure C code in the function definition,
125700 ** see the header comment on the previous function.
125701 */
125702 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
125703   if( keyClass==FTS3_HASH_STRING ){
125704     return &fts3StrCompare;
125705   }else{
125706     assert( keyClass==FTS3_HASH_BINARY );
125707     return &fts3BinCompare;
125708   }
125709 }
125710
125711 /* Link an element into the hash table
125712 */
125713 static void fts3HashInsertElement(
125714   Fts3Hash *pH,            /* The complete hash table */
125715   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
125716   Fts3HashElem *pNew       /* The element to be inserted */
125717 ){
125718   Fts3HashElem *pHead;     /* First element already in pEntry */
125719   pHead = pEntry->chain;
125720   if( pHead ){
125721     pNew->next = pHead;
125722     pNew->prev = pHead->prev;
125723     if( pHead->prev ){ pHead->prev->next = pNew; }
125724     else             { pH->first = pNew; }
125725     pHead->prev = pNew;
125726   }else{
125727     pNew->next = pH->first;
125728     if( pH->first ){ pH->first->prev = pNew; }
125729     pNew->prev = 0;
125730     pH->first = pNew;
125731   }
125732   pEntry->count++;
125733   pEntry->chain = pNew;
125734 }
125735
125736
125737 /* Resize the hash table so that it cantains "new_size" buckets.
125738 ** "new_size" must be a power of 2.  The hash table might fail
125739 ** to resize if sqliteMalloc() fails.
125740 **
125741 ** Return non-zero if a memory allocation error occurs.
125742 */
125743 static int fts3Rehash(Fts3Hash *pH, int new_size){
125744   struct _fts3ht *new_ht;          /* The new hash table */
125745   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
125746   int (*xHash)(const void*,int);   /* The hash function */
125747
125748   assert( (new_size & (new_size-1))==0 );
125749   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
125750   if( new_ht==0 ) return 1;
125751   fts3HashFree(pH->ht);
125752   pH->ht = new_ht;
125753   pH->htsize = new_size;
125754   xHash = ftsHashFunction(pH->keyClass);
125755   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
125756     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
125757     next_elem = elem->next;
125758     fts3HashInsertElement(pH, &new_ht[h], elem);
125759   }
125760   return 0;
125761 }
125762
125763 /* This function (for internal use only) locates an element in an
125764 ** hash table that matches the given key.  The hash for this key has
125765 ** already been computed and is passed as the 4th parameter.
125766 */
125767 static Fts3HashElem *fts3FindElementByHash(
125768   const Fts3Hash *pH, /* The pH to be searched */
125769   const void *pKey,   /* The key we are searching for */
125770   int nKey,
125771   int h               /* The hash for this key. */
125772 ){
125773   Fts3HashElem *elem;            /* Used to loop thru the element list */
125774   int count;                     /* Number of elements left to test */
125775   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
125776
125777   if( pH->ht ){
125778     struct _fts3ht *pEntry = &pH->ht[h];
125779     elem = pEntry->chain;
125780     count = pEntry->count;
125781     xCompare = ftsCompareFunction(pH->keyClass);
125782     while( count-- && elem ){
125783       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
125784         return elem;
125785       }
125786       elem = elem->next;
125787     }
125788   }
125789   return 0;
125790 }
125791
125792 /* Remove a single entry from the hash table given a pointer to that
125793 ** element and a hash on the element's key.
125794 */
125795 static void fts3RemoveElementByHash(
125796   Fts3Hash *pH,         /* The pH containing "elem" */
125797   Fts3HashElem* elem,   /* The element to be removed from the pH */
125798   int h                 /* Hash value for the element */
125799 ){
125800   struct _fts3ht *pEntry;
125801   if( elem->prev ){
125802     elem->prev->next = elem->next;
125803   }else{
125804     pH->first = elem->next;
125805   }
125806   if( elem->next ){
125807     elem->next->prev = elem->prev;
125808   }
125809   pEntry = &pH->ht[h];
125810   if( pEntry->chain==elem ){
125811     pEntry->chain = elem->next;
125812   }
125813   pEntry->count--;
125814   if( pEntry->count<=0 ){
125815     pEntry->chain = 0;
125816   }
125817   if( pH->copyKey && elem->pKey ){
125818     fts3HashFree(elem->pKey);
125819   }
125820   fts3HashFree( elem );
125821   pH->count--;
125822   if( pH->count<=0 ){
125823     assert( pH->first==0 );
125824     assert( pH->count==0 );
125825     fts3HashClear(pH);
125826   }
125827 }
125828
125829 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
125830   const Fts3Hash *pH,
125831   const void *pKey,
125832   int nKey
125833 ){
125834   int h;                          /* A hash on key */
125835   int (*xHash)(const void*,int);  /* The hash function */
125836
125837   if( pH==0 || pH->ht==0 ) return 0;
125838   xHash = ftsHashFunction(pH->keyClass);
125839   assert( xHash!=0 );
125840   h = (*xHash)(pKey,nKey);
125841   assert( (pH->htsize & (pH->htsize-1))==0 );
125842   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
125843 }
125844
125845 /*
125846 ** Attempt to locate an element of the hash table pH with a key
125847 ** that matches pKey,nKey.  Return the data for this element if it is
125848 ** found, or NULL if there is no match.
125849 */
125850 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
125851   Fts3HashElem *pElem;            /* The element that matches key (if any) */
125852
125853   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
125854   return pElem ? pElem->data : 0;
125855 }
125856
125857 /* Insert an element into the hash table pH.  The key is pKey,nKey
125858 ** and the data is "data".
125859 **
125860 ** If no element exists with a matching key, then a new
125861 ** element is created.  A copy of the key is made if the copyKey
125862 ** flag is set.  NULL is returned.
125863 **
125864 ** If another element already exists with the same key, then the
125865 ** new data replaces the old data and the old data is returned.
125866 ** The key is not copied in this instance.  If a malloc fails, then
125867 ** the new data is returned and the hash table is unchanged.
125868 **
125869 ** If the "data" parameter to this function is NULL, then the
125870 ** element corresponding to "key" is removed from the hash table.
125871 */
125872 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
125873   Fts3Hash *pH,        /* The hash table to insert into */
125874   const void *pKey,    /* The key */
125875   int nKey,            /* Number of bytes in the key */
125876   void *data           /* The data */
125877 ){
125878   int hraw;                 /* Raw hash value of the key */
125879   int h;                    /* the hash of the key modulo hash table size */
125880   Fts3HashElem *elem;       /* Used to loop thru the element list */
125881   Fts3HashElem *new_elem;   /* New element added to the pH */
125882   int (*xHash)(const void*,int);  /* The hash function */
125883
125884   assert( pH!=0 );
125885   xHash = ftsHashFunction(pH->keyClass);
125886   assert( xHash!=0 );
125887   hraw = (*xHash)(pKey, nKey);
125888   assert( (pH->htsize & (pH->htsize-1))==0 );
125889   h = hraw & (pH->htsize-1);
125890   elem = fts3FindElementByHash(pH,pKey,nKey,h);
125891   if( elem ){
125892     void *old_data = elem->data;
125893     if( data==0 ){
125894       fts3RemoveElementByHash(pH,elem,h);
125895     }else{
125896       elem->data = data;
125897     }
125898     return old_data;
125899   }
125900   if( data==0 ) return 0;
125901   if( (pH->htsize==0 && fts3Rehash(pH,8))
125902    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
125903   ){
125904     pH->count = 0;
125905     return data;
125906   }
125907   assert( pH->htsize>0 );
125908   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
125909   if( new_elem==0 ) return data;
125910   if( pH->copyKey && pKey!=0 ){
125911     new_elem->pKey = fts3HashMalloc( nKey );
125912     if( new_elem->pKey==0 ){
125913       fts3HashFree(new_elem);
125914       return data;
125915     }
125916     memcpy((void*)new_elem->pKey, pKey, nKey);
125917   }else{
125918     new_elem->pKey = (void*)pKey;
125919   }
125920   new_elem->nKey = nKey;
125921   pH->count++;
125922   assert( pH->htsize>0 );
125923   assert( (pH->htsize & (pH->htsize-1))==0 );
125924   h = hraw & (pH->htsize-1);
125925   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
125926   new_elem->data = data;
125927   return 0;
125928 }
125929
125930 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125931
125932 /************** End of fts3_hash.c *******************************************/
125933 /************** Begin file fts3_porter.c *************************************/
125934 /*
125935 ** 2006 September 30
125936 **
125937 ** The author disclaims copyright to this source code.  In place of
125938 ** a legal notice, here is a blessing:
125939 **
125940 **    May you do good and not evil.
125941 **    May you find forgiveness for yourself and forgive others.
125942 **    May you share freely, never taking more than you give.
125943 **
125944 *************************************************************************
125945 ** Implementation of the full-text-search tokenizer that implements
125946 ** a Porter stemmer.
125947 */
125948
125949 /*
125950 ** The code in this file is only compiled if:
125951 **
125952 **     * The FTS3 module is being built as an extension
125953 **       (in which case SQLITE_CORE is not defined), or
125954 **
125955 **     * The FTS3 module is being built into the core of
125956 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
125957 */
125958 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125959
125960 /* #include <assert.h> */
125961 /* #include <stdlib.h> */
125962 /* #include <stdio.h> */
125963 /* #include <string.h> */
125964
125965
125966 /*
125967 ** Class derived from sqlite3_tokenizer
125968 */
125969 typedef struct porter_tokenizer {
125970   sqlite3_tokenizer base;      /* Base class */
125971 } porter_tokenizer;
125972
125973 /*
125974 ** Class derived from sqlite3_tokenizer_cursor
125975 */
125976 typedef struct porter_tokenizer_cursor {
125977   sqlite3_tokenizer_cursor base;
125978   const char *zInput;          /* input we are tokenizing */
125979   int nInput;                  /* size of the input */
125980   int iOffset;                 /* current position in zInput */
125981   int iToken;                  /* index of next token to be returned */
125982   char *zToken;                /* storage for current token */
125983   int nAllocated;              /* space allocated to zToken buffer */
125984 } porter_tokenizer_cursor;
125985
125986
125987 /*
125988 ** Create a new tokenizer instance.
125989 */
125990 static int porterCreate(
125991   int argc, const char * const *argv,
125992   sqlite3_tokenizer **ppTokenizer
125993 ){
125994   porter_tokenizer *t;
125995
125996   UNUSED_PARAMETER(argc);
125997   UNUSED_PARAMETER(argv);
125998
125999   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
126000   if( t==NULL ) return SQLITE_NOMEM;
126001   memset(t, 0, sizeof(*t));
126002   *ppTokenizer = &t->base;
126003   return SQLITE_OK;
126004 }
126005
126006 /*
126007 ** Destroy a tokenizer
126008 */
126009 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
126010   sqlite3_free(pTokenizer);
126011   return SQLITE_OK;
126012 }
126013
126014 /*
126015 ** Prepare to begin tokenizing a particular string.  The input
126016 ** string to be tokenized is zInput[0..nInput-1].  A cursor
126017 ** used to incrementally tokenize this string is returned in
126018 ** *ppCursor.
126019 */
126020 static int porterOpen(
126021   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
126022   const char *zInput, int nInput,        /* String to be tokenized */
126023   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
126024 ){
126025   porter_tokenizer_cursor *c;
126026
126027   UNUSED_PARAMETER(pTokenizer);
126028
126029   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
126030   if( c==NULL ) return SQLITE_NOMEM;
126031
126032   c->zInput = zInput;
126033   if( zInput==0 ){
126034     c->nInput = 0;
126035   }else if( nInput<0 ){
126036     c->nInput = (int)strlen(zInput);
126037   }else{
126038     c->nInput = nInput;
126039   }
126040   c->iOffset = 0;                 /* start tokenizing at the beginning */
126041   c->iToken = 0;
126042   c->zToken = NULL;               /* no space allocated, yet. */
126043   c->nAllocated = 0;
126044
126045   *ppCursor = &c->base;
126046   return SQLITE_OK;
126047 }
126048
126049 /*
126050 ** Close a tokenization cursor previously opened by a call to
126051 ** porterOpen() above.
126052 */
126053 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
126054   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
126055   sqlite3_free(c->zToken);
126056   sqlite3_free(c);
126057   return SQLITE_OK;
126058 }
126059 /*
126060 ** Vowel or consonant
126061 */
126062 static const char cType[] = {
126063    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
126064    1, 1, 1, 2, 1
126065 };
126066
126067 /*
126068 ** isConsonant() and isVowel() determine if their first character in
126069 ** the string they point to is a consonant or a vowel, according
126070 ** to Porter ruls.
126071 **
126072 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
126073 ** 'Y' is a consonant unless it follows another consonant,
126074 ** in which case it is a vowel.
126075 **
126076 ** In these routine, the letters are in reverse order.  So the 'y' rule
126077 ** is that 'y' is a consonant unless it is followed by another
126078 ** consonent.
126079 */
126080 static int isVowel(const char*);
126081 static int isConsonant(const char *z){
126082   int j;
126083   char x = *z;
126084   if( x==0 ) return 0;
126085   assert( x>='a' && x<='z' );
126086   j = cType[x-'a'];
126087   if( j<2 ) return j;
126088   return z[1]==0 || isVowel(z + 1);
126089 }
126090 static int isVowel(const char *z){
126091   int j;
126092   char x = *z;
126093   if( x==0 ) return 0;
126094   assert( x>='a' && x<='z' );
126095   j = cType[x-'a'];
126096   if( j<2 ) return 1-j;
126097   return isConsonant(z + 1);
126098 }
126099
126100 /*
126101 ** Let any sequence of one or more vowels be represented by V and let
126102 ** C be sequence of one or more consonants.  Then every word can be
126103 ** represented as:
126104 **
126105 **           [C] (VC){m} [V]
126106 **
126107 ** In prose:  A word is an optional consonant followed by zero or
126108 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
126109 ** number of vowel consonant pairs.  This routine computes the value
126110 ** of m for the first i bytes of a word.
126111 **
126112 ** Return true if the m-value for z is 1 or more.  In other words,
126113 ** return true if z contains at least one vowel that is followed
126114 ** by a consonant.
126115 **
126116 ** In this routine z[] is in reverse order.  So we are really looking
126117 ** for an instance of of a consonant followed by a vowel.
126118 */
126119 static int m_gt_0(const char *z){
126120   while( isVowel(z) ){ z++; }
126121   if( *z==0 ) return 0;
126122   while( isConsonant(z) ){ z++; }
126123   return *z!=0;
126124 }
126125
126126 /* Like mgt0 above except we are looking for a value of m which is
126127 ** exactly 1
126128 */
126129 static int m_eq_1(const char *z){
126130   while( isVowel(z) ){ z++; }
126131   if( *z==0 ) return 0;
126132   while( isConsonant(z) ){ z++; }
126133   if( *z==0 ) return 0;
126134   while( isVowel(z) ){ z++; }
126135   if( *z==0 ) return 1;
126136   while( isConsonant(z) ){ z++; }
126137   return *z==0;
126138 }
126139
126140 /* Like mgt0 above except we are looking for a value of m>1 instead
126141 ** or m>0
126142 */
126143 static int m_gt_1(const char *z){
126144   while( isVowel(z) ){ z++; }
126145   if( *z==0 ) return 0;
126146   while( isConsonant(z) ){ z++; }
126147   if( *z==0 ) return 0;
126148   while( isVowel(z) ){ z++; }
126149   if( *z==0 ) return 0;
126150   while( isConsonant(z) ){ z++; }
126151   return *z!=0;
126152 }
126153
126154 /*
126155 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
126156 */
126157 static int hasVowel(const char *z){
126158   while( isConsonant(z) ){ z++; }
126159   return *z!=0;
126160 }
126161
126162 /*
126163 ** Return TRUE if the word ends in a double consonant.
126164 **
126165 ** The text is reversed here. So we are really looking at
126166 ** the first two characters of z[].
126167 */
126168 static int doubleConsonant(const char *z){
126169   return isConsonant(z) && z[0]==z[1];
126170 }
126171
126172 /*
126173 ** Return TRUE if the word ends with three letters which
126174 ** are consonant-vowel-consonent and where the final consonant
126175 ** is not 'w', 'x', or 'y'.
126176 **
126177 ** The word is reversed here.  So we are really checking the
126178 ** first three letters and the first one cannot be in [wxy].
126179 */
126180 static int star_oh(const char *z){
126181   return
126182     isConsonant(z) &&
126183     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
126184     isVowel(z+1) &&
126185     isConsonant(z+2);
126186 }
126187
126188 /*
126189 ** If the word ends with zFrom and xCond() is true for the stem
126190 ** of the word that preceeds the zFrom ending, then change the
126191 ** ending to zTo.
126192 **
126193 ** The input word *pz and zFrom are both in reverse order.  zTo
126194 ** is in normal order.
126195 **
126196 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
126197 ** match.  Not that TRUE is returned even if xCond() fails and
126198 ** no substitution occurs.
126199 */
126200 static int stem(
126201   char **pz,             /* The word being stemmed (Reversed) */
126202   const char *zFrom,     /* If the ending matches this... (Reversed) */
126203   const char *zTo,       /* ... change the ending to this (not reversed) */
126204   int (*xCond)(const char*)   /* Condition that must be true */
126205 ){
126206   char *z = *pz;
126207   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
126208   if( *zFrom!=0 ) return 0;
126209   if( xCond && !xCond(z) ) return 1;
126210   while( *zTo ){
126211     *(--z) = *(zTo++);
126212   }
126213   *pz = z;
126214   return 1;
126215 }
126216
126217 /*
126218 ** This is the fallback stemmer used when the porter stemmer is
126219 ** inappropriate.  The input word is copied into the output with
126220 ** US-ASCII case folding.  If the input word is too long (more
126221 ** than 20 bytes if it contains no digits or more than 6 bytes if
126222 ** it contains digits) then word is truncated to 20 or 6 bytes
126223 ** by taking 10 or 3 bytes from the beginning and end.
126224 */
126225 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
126226   int i, mx, j;
126227   int hasDigit = 0;
126228   for(i=0; i<nIn; i++){
126229     char c = zIn[i];
126230     if( c>='A' && c<='Z' ){
126231       zOut[i] = c - 'A' + 'a';
126232     }else{
126233       if( c>='0' && c<='9' ) hasDigit = 1;
126234       zOut[i] = c;
126235     }
126236   }
126237   mx = hasDigit ? 3 : 10;
126238   if( nIn>mx*2 ){
126239     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
126240       zOut[j] = zOut[i];
126241     }
126242     i = j;
126243   }
126244   zOut[i] = 0;
126245   *pnOut = i;
126246 }
126247
126248
126249 /*
126250 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
126251 ** zOut is at least big enough to hold nIn bytes.  Write the actual
126252 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
126253 **
126254 ** Any upper-case characters in the US-ASCII character set ([A-Z])
126255 ** are converted to lower case.  Upper-case UTF characters are
126256 ** unchanged.
126257 **
126258 ** Words that are longer than about 20 bytes are stemmed by retaining
126259 ** a few bytes from the beginning and the end of the word.  If the
126260 ** word contains digits, 3 bytes are taken from the beginning and
126261 ** 3 bytes from the end.  For long words without digits, 10 bytes
126262 ** are taken from each end.  US-ASCII case folding still applies.
126263 **
126264 ** If the input word contains not digits but does characters not
126265 ** in [a-zA-Z] then no stemming is attempted and this routine just
126266 ** copies the input into the input into the output with US-ASCII
126267 ** case folding.
126268 **
126269 ** Stemming never increases the length of the word.  So there is
126270 ** no chance of overflowing the zOut buffer.
126271 */
126272 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
126273   int i, j;
126274   char zReverse[28];
126275   char *z, *z2;
126276   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
126277     /* The word is too big or too small for the porter stemmer.
126278     ** Fallback to the copy stemmer */
126279     copy_stemmer(zIn, nIn, zOut, pnOut);
126280     return;
126281   }
126282   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
126283     char c = zIn[i];
126284     if( c>='A' && c<='Z' ){
126285       zReverse[j] = c + 'a' - 'A';
126286     }else if( c>='a' && c<='z' ){
126287       zReverse[j] = c;
126288     }else{
126289       /* The use of a character not in [a-zA-Z] means that we fallback
126290       ** to the copy stemmer */
126291       copy_stemmer(zIn, nIn, zOut, pnOut);
126292       return;
126293     }
126294   }
126295   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
126296   z = &zReverse[j+1];
126297
126298
126299   /* Step 1a */
126300   if( z[0]=='s' ){
126301     if(
126302      !stem(&z, "sess", "ss", 0) &&
126303      !stem(&z, "sei", "i", 0)  &&
126304      !stem(&z, "ss", "ss", 0)
126305     ){
126306       z++;
126307     }
126308   }
126309
126310   /* Step 1b */
126311   z2 = z;
126312   if( stem(&z, "dee", "ee", m_gt_0) ){
126313     /* Do nothing.  The work was all in the test */
126314   }else if(
126315      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
126316       && z!=z2
126317   ){
126318      if( stem(&z, "ta", "ate", 0) ||
126319          stem(&z, "lb", "ble", 0) ||
126320          stem(&z, "zi", "ize", 0) ){
126321        /* Do nothing.  The work was all in the test */
126322      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
126323        z++;
126324      }else if( m_eq_1(z) && star_oh(z) ){
126325        *(--z) = 'e';
126326      }
126327   }
126328
126329   /* Step 1c */
126330   if( z[0]=='y' && hasVowel(z+1) ){
126331     z[0] = 'i';
126332   }
126333
126334   /* Step 2 */
126335   switch( z[1] ){
126336    case 'a':
126337      stem(&z, "lanoita", "ate", m_gt_0) ||
126338      stem(&z, "lanoit", "tion", m_gt_0);
126339      break;
126340    case 'c':
126341      stem(&z, "icne", "ence", m_gt_0) ||
126342      stem(&z, "icna", "ance", m_gt_0);
126343      break;
126344    case 'e':
126345      stem(&z, "rezi", "ize", m_gt_0);
126346      break;
126347    case 'g':
126348      stem(&z, "igol", "log", m_gt_0);
126349      break;
126350    case 'l':
126351      stem(&z, "ilb", "ble", m_gt_0) ||
126352      stem(&z, "illa", "al", m_gt_0) ||
126353      stem(&z, "iltne", "ent", m_gt_0) ||
126354      stem(&z, "ile", "e", m_gt_0) ||
126355      stem(&z, "ilsuo", "ous", m_gt_0);
126356      break;
126357    case 'o':
126358      stem(&z, "noitazi", "ize", m_gt_0) ||
126359      stem(&z, "noita", "ate", m_gt_0) ||
126360      stem(&z, "rota", "ate", m_gt_0);
126361      break;
126362    case 's':
126363      stem(&z, "msila", "al", m_gt_0) ||
126364      stem(&z, "ssenevi", "ive", m_gt_0) ||
126365      stem(&z, "ssenluf", "ful", m_gt_0) ||
126366      stem(&z, "ssensuo", "ous", m_gt_0);
126367      break;
126368    case 't':
126369      stem(&z, "itila", "al", m_gt_0) ||
126370      stem(&z, "itivi", "ive", m_gt_0) ||
126371      stem(&z, "itilib", "ble", m_gt_0);
126372      break;
126373   }
126374
126375   /* Step 3 */
126376   switch( z[0] ){
126377    case 'e':
126378      stem(&z, "etaci", "ic", m_gt_0) ||
126379      stem(&z, "evita", "", m_gt_0)   ||
126380      stem(&z, "ezila", "al", m_gt_0);
126381      break;
126382    case 'i':
126383      stem(&z, "itici", "ic", m_gt_0);
126384      break;
126385    case 'l':
126386      stem(&z, "laci", "ic", m_gt_0) ||
126387      stem(&z, "luf", "", m_gt_0);
126388      break;
126389    case 's':
126390      stem(&z, "ssen", "", m_gt_0);
126391      break;
126392   }
126393
126394   /* Step 4 */
126395   switch( z[1] ){
126396    case 'a':
126397      if( z[0]=='l' && m_gt_1(z+2) ){
126398        z += 2;
126399      }
126400      break;
126401    case 'c':
126402      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
126403        z += 4;
126404      }
126405      break;
126406    case 'e':
126407      if( z[0]=='r' && m_gt_1(z+2) ){
126408        z += 2;
126409      }
126410      break;
126411    case 'i':
126412      if( z[0]=='c' && m_gt_1(z+2) ){
126413        z += 2;
126414      }
126415      break;
126416    case 'l':
126417      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
126418        z += 4;
126419      }
126420      break;
126421    case 'n':
126422      if( z[0]=='t' ){
126423        if( z[2]=='a' ){
126424          if( m_gt_1(z+3) ){
126425            z += 3;
126426          }
126427        }else if( z[2]=='e' ){
126428          stem(&z, "tneme", "", m_gt_1) ||
126429          stem(&z, "tnem", "", m_gt_1) ||
126430          stem(&z, "tne", "", m_gt_1);
126431        }
126432      }
126433      break;
126434    case 'o':
126435      if( z[0]=='u' ){
126436        if( m_gt_1(z+2) ){
126437          z += 2;
126438        }
126439      }else if( z[3]=='s' || z[3]=='t' ){
126440        stem(&z, "noi", "", m_gt_1);
126441      }
126442      break;
126443    case 's':
126444      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
126445        z += 3;
126446      }
126447      break;
126448    case 't':
126449      stem(&z, "eta", "", m_gt_1) ||
126450      stem(&z, "iti", "", m_gt_1);
126451      break;
126452    case 'u':
126453      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
126454        z += 3;
126455      }
126456      break;
126457    case 'v':
126458    case 'z':
126459      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
126460        z += 3;
126461      }
126462      break;
126463   }
126464
126465   /* Step 5a */
126466   if( z[0]=='e' ){
126467     if( m_gt_1(z+1) ){
126468       z++;
126469     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
126470       z++;
126471     }
126472   }
126473
126474   /* Step 5b */
126475   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
126476     z++;
126477   }
126478
126479   /* z[] is now the stemmed word in reverse order.  Flip it back
126480   ** around into forward order and return.
126481   */
126482   *pnOut = i = (int)strlen(z);
126483   zOut[i] = 0;
126484   while( *z ){
126485     zOut[--i] = *(z++);
126486   }
126487 }
126488
126489 /*
126490 ** Characters that can be part of a token.  We assume any character
126491 ** whose value is greater than 0x80 (any UTF character) can be
126492 ** part of a token.  In other words, delimiters all must have
126493 ** values of 0x7f or lower.
126494 */
126495 static const char porterIdChar[] = {
126496 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
126497     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
126498     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
126499     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
126500     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
126501     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
126502 };
126503 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
126504
126505 /*
126506 ** Extract the next token from a tokenization cursor.  The cursor must
126507 ** have been opened by a prior call to porterOpen().
126508 */
126509 static int porterNext(
126510   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
126511   const char **pzToken,               /* OUT: *pzToken is the token text */
126512   int *pnBytes,                       /* OUT: Number of bytes in token */
126513   int *piStartOffset,                 /* OUT: Starting offset of token */
126514   int *piEndOffset,                   /* OUT: Ending offset of token */
126515   int *piPosition                     /* OUT: Position integer of token */
126516 ){
126517   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
126518   const char *z = c->zInput;
126519
126520   while( c->iOffset<c->nInput ){
126521     int iStartOffset, ch;
126522
126523     /* Scan past delimiter characters */
126524     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
126525       c->iOffset++;
126526     }
126527
126528     /* Count non-delimiter characters. */
126529     iStartOffset = c->iOffset;
126530     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
126531       c->iOffset++;
126532     }
126533
126534     if( c->iOffset>iStartOffset ){
126535       int n = c->iOffset-iStartOffset;
126536       if( n>c->nAllocated ){
126537         char *pNew;
126538         c->nAllocated = n+20;
126539         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
126540         if( !pNew ) return SQLITE_NOMEM;
126541         c->zToken = pNew;
126542       }
126543       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
126544       *pzToken = c->zToken;
126545       *piStartOffset = iStartOffset;
126546       *piEndOffset = c->iOffset;
126547       *piPosition = c->iToken++;
126548       return SQLITE_OK;
126549     }
126550   }
126551   return SQLITE_DONE;
126552 }
126553
126554 /*
126555 ** The set of routines that implement the porter-stemmer tokenizer
126556 */
126557 static const sqlite3_tokenizer_module porterTokenizerModule = {
126558   0,
126559   porterCreate,
126560   porterDestroy,
126561   porterOpen,
126562   porterClose,
126563   porterNext,
126564   0
126565 };
126566
126567 /*
126568 ** Allocate a new porter tokenizer.  Return a pointer to the new
126569 ** tokenizer in *ppModule
126570 */
126571 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
126572   sqlite3_tokenizer_module const**ppModule
126573 ){
126574   *ppModule = &porterTokenizerModule;
126575 }
126576
126577 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126578
126579 /************** End of fts3_porter.c *****************************************/
126580 /************** Begin file fts3_tokenizer.c **********************************/
126581 /*
126582 ** 2007 June 22
126583 **
126584 ** The author disclaims copyright to this source code.  In place of
126585 ** a legal notice, here is a blessing:
126586 **
126587 **    May you do good and not evil.
126588 **    May you find forgiveness for yourself and forgive others.
126589 **    May you share freely, never taking more than you give.
126590 **
126591 ******************************************************************************
126592 **
126593 ** This is part of an SQLite module implementing full-text search.
126594 ** This particular file implements the generic tokenizer interface.
126595 */
126596
126597 /*
126598 ** The code in this file is only compiled if:
126599 **
126600 **     * The FTS3 module is being built as an extension
126601 **       (in which case SQLITE_CORE is not defined), or
126602 **
126603 **     * The FTS3 module is being built into the core of
126604 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126605 */
126606 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126607
126608 /* #include <assert.h> */
126609 /* #include <string.h> */
126610
126611 /*
126612 ** Implementation of the SQL scalar function for accessing the underlying
126613 ** hash table. This function may be called as follows:
126614 **
126615 **   SELECT <function-name>(<key-name>);
126616 **   SELECT <function-name>(<key-name>, <pointer>);
126617 **
126618 ** where <function-name> is the name passed as the second argument
126619 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
126620 **
126621 ** If the <pointer> argument is specified, it must be a blob value
126622 ** containing a pointer to be stored as the hash data corresponding
126623 ** to the string <key-name>. If <pointer> is not specified, then
126624 ** the string <key-name> must already exist in the has table. Otherwise,
126625 ** an error is returned.
126626 **
126627 ** Whether or not the <pointer> argument is specified, the value returned
126628 ** is a blob containing the pointer stored as the hash data corresponding
126629 ** to string <key-name> (after the hash-table is updated, if applicable).
126630 */
126631 static void scalarFunc(
126632   sqlite3_context *context,
126633   int argc,
126634   sqlite3_value **argv
126635 ){
126636   Fts3Hash *pHash;
126637   void *pPtr = 0;
126638   const unsigned char *zName;
126639   int nName;
126640
126641   assert( argc==1 || argc==2 );
126642
126643   pHash = (Fts3Hash *)sqlite3_user_data(context);
126644
126645   zName = sqlite3_value_text(argv[0]);
126646   nName = sqlite3_value_bytes(argv[0])+1;
126647
126648   if( argc==2 ){
126649     void *pOld;
126650     int n = sqlite3_value_bytes(argv[1]);
126651     if( n!=sizeof(pPtr) ){
126652       sqlite3_result_error(context, "argument type mismatch", -1);
126653       return;
126654     }
126655     pPtr = *(void **)sqlite3_value_blob(argv[1]);
126656     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
126657     if( pOld==pPtr ){
126658       sqlite3_result_error(context, "out of memory", -1);
126659       return;
126660     }
126661   }else{
126662     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
126663     if( !pPtr ){
126664       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
126665       sqlite3_result_error(context, zErr, -1);
126666       sqlite3_free(zErr);
126667       return;
126668     }
126669   }
126670
126671   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
126672 }
126673
126674 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
126675   static const char isFtsIdChar[] = {
126676       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
126677       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
126678       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
126679       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
126680       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
126681       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
126682       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
126683       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
126684   };
126685   return (c&0x80 || isFtsIdChar[(int)(c)]);
126686 }
126687
126688 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
126689   const char *z1;
126690   const char *z2 = 0;
126691
126692   /* Find the start of the next token. */
126693   z1 = zStr;
126694   while( z2==0 ){
126695     char c = *z1;
126696     switch( c ){
126697       case '\0': return 0;        /* No more tokens here */
126698       case '\'':
126699       case '"':
126700       case '`': {
126701         z2 = z1;
126702         while( *++z2 && (*z2!=c || *++z2==c) );
126703         break;
126704       }
126705       case '[':
126706         z2 = &z1[1];
126707         while( *z2 && z2[0]!=']' ) z2++;
126708         if( *z2 ) z2++;
126709         break;
126710
126711       default:
126712         if( sqlite3Fts3IsIdChar(*z1) ){
126713           z2 = &z1[1];
126714           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
126715         }else{
126716           z1++;
126717         }
126718     }
126719   }
126720
126721   *pn = (int)(z2-z1);
126722   return z1;
126723 }
126724
126725 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
126726   Fts3Hash *pHash,                /* Tokenizer hash table */
126727   const char *zArg,               /* Tokenizer name */
126728   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
126729   char **pzErr                    /* OUT: Set to malloced error message */
126730 ){
126731   int rc;
126732   char *z = (char *)zArg;
126733   int n = 0;
126734   char *zCopy;
126735   char *zEnd;                     /* Pointer to nul-term of zCopy */
126736   sqlite3_tokenizer_module *m;
126737
126738   zCopy = sqlite3_mprintf("%s", zArg);
126739   if( !zCopy ) return SQLITE_NOMEM;
126740   zEnd = &zCopy[strlen(zCopy)];
126741
126742   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
126743   z[n] = '\0';
126744   sqlite3Fts3Dequote(z);
126745
126746   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
126747   if( !m ){
126748     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
126749     rc = SQLITE_ERROR;
126750   }else{
126751     char const **aArg = 0;
126752     int iArg = 0;
126753     z = &z[n+1];
126754     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
126755       int nNew = sizeof(char *)*(iArg+1);
126756       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
126757       if( !aNew ){
126758         sqlite3_free(zCopy);
126759         sqlite3_free((void *)aArg);
126760         return SQLITE_NOMEM;
126761       }
126762       aArg = aNew;
126763       aArg[iArg++] = z;
126764       z[n] = '\0';
126765       sqlite3Fts3Dequote(z);
126766       z = &z[n+1];
126767     }
126768     rc = m->xCreate(iArg, aArg, ppTok);
126769     assert( rc!=SQLITE_OK || *ppTok );
126770     if( rc!=SQLITE_OK ){
126771       *pzErr = sqlite3_mprintf("unknown tokenizer");
126772     }else{
126773       (*ppTok)->pModule = m;
126774     }
126775     sqlite3_free((void *)aArg);
126776   }
126777
126778   sqlite3_free(zCopy);
126779   return rc;
126780 }
126781
126782
126783 #ifdef SQLITE_TEST
126784
126785 /* #include <tcl.h> */
126786 /* #include <string.h> */
126787
126788 /*
126789 ** Implementation of a special SQL scalar function for testing tokenizers
126790 ** designed to be used in concert with the Tcl testing framework. This
126791 ** function must be called with two or more arguments:
126792 **
126793 **   SELECT <function-name>(<key-name>, ..., <input-string>);
126794 **
126795 ** where <function-name> is the name passed as the second argument
126796 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
126797 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
126798 **
126799 ** The return value is a string that may be interpreted as a Tcl
126800 ** list. For each token in the <input-string>, three elements are
126801 ** added to the returned list. The first is the token position, the
126802 ** second is the token text (folded, stemmed, etc.) and the third is the
126803 ** substring of <input-string> associated with the token. For example,
126804 ** using the built-in "simple" tokenizer:
126805 **
126806 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
126807 **
126808 ** will return the string:
126809 **
126810 **   "{0 i I 1 dont don't 2 see see 3 how how}"
126811 **
126812 */
126813 static void testFunc(
126814   sqlite3_context *context,
126815   int argc,
126816   sqlite3_value **argv
126817 ){
126818   Fts3Hash *pHash;
126819   sqlite3_tokenizer_module *p;
126820   sqlite3_tokenizer *pTokenizer = 0;
126821   sqlite3_tokenizer_cursor *pCsr = 0;
126822
126823   const char *zErr = 0;
126824
126825   const char *zName;
126826   int nName;
126827   const char *zInput;
126828   int nInput;
126829
126830   const char *azArg[64];
126831
126832   const char *zToken;
126833   int nToken = 0;
126834   int iStart = 0;
126835   int iEnd = 0;
126836   int iPos = 0;
126837   int i;
126838
126839   Tcl_Obj *pRet;
126840
126841   if( argc<2 ){
126842     sqlite3_result_error(context, "insufficient arguments", -1);
126843     return;
126844   }
126845
126846   nName = sqlite3_value_bytes(argv[0]);
126847   zName = (const char *)sqlite3_value_text(argv[0]);
126848   nInput = sqlite3_value_bytes(argv[argc-1]);
126849   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
126850
126851   pHash = (Fts3Hash *)sqlite3_user_data(context);
126852   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
126853
126854   if( !p ){
126855     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
126856     sqlite3_result_error(context, zErr, -1);
126857     sqlite3_free(zErr);
126858     return;
126859   }
126860
126861   pRet = Tcl_NewObj();
126862   Tcl_IncrRefCount(pRet);
126863
126864   for(i=1; i<argc-1; i++){
126865     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
126866   }
126867
126868   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
126869     zErr = "error in xCreate()";
126870     goto finish;
126871   }
126872   pTokenizer->pModule = p;
126873   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
126874     zErr = "error in xOpen()";
126875     goto finish;
126876   }
126877
126878   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
126879     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
126880     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
126881     zToken = &zInput[iStart];
126882     nToken = iEnd-iStart;
126883     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
126884   }
126885
126886   if( SQLITE_OK!=p->xClose(pCsr) ){
126887     zErr = "error in xClose()";
126888     goto finish;
126889   }
126890   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
126891     zErr = "error in xDestroy()";
126892     goto finish;
126893   }
126894
126895 finish:
126896   if( zErr ){
126897     sqlite3_result_error(context, zErr, -1);
126898   }else{
126899     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
126900   }
126901   Tcl_DecrRefCount(pRet);
126902 }
126903
126904 static
126905 int registerTokenizer(
126906   sqlite3 *db,
126907   char *zName,
126908   const sqlite3_tokenizer_module *p
126909 ){
126910   int rc;
126911   sqlite3_stmt *pStmt;
126912   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
126913
126914   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
126915   if( rc!=SQLITE_OK ){
126916     return rc;
126917   }
126918
126919   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
126920   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
126921   sqlite3_step(pStmt);
126922
126923   return sqlite3_finalize(pStmt);
126924 }
126925
126926 static
126927 int queryTokenizer(
126928   sqlite3 *db,
126929   char *zName,
126930   const sqlite3_tokenizer_module **pp
126931 ){
126932   int rc;
126933   sqlite3_stmt *pStmt;
126934   const char zSql[] = "SELECT fts3_tokenizer(?)";
126935
126936   *pp = 0;
126937   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
126938   if( rc!=SQLITE_OK ){
126939     return rc;
126940   }
126941
126942   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
126943   if( SQLITE_ROW==sqlite3_step(pStmt) ){
126944     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
126945       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
126946     }
126947   }
126948
126949   return sqlite3_finalize(pStmt);
126950 }
126951
126952 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
126953
126954 /*
126955 ** Implementation of the scalar function fts3_tokenizer_internal_test().
126956 ** This function is used for testing only, it is not included in the
126957 ** build unless SQLITE_TEST is defined.
126958 **
126959 ** The purpose of this is to test that the fts3_tokenizer() function
126960 ** can be used as designed by the C-code in the queryTokenizer and
126961 ** registerTokenizer() functions above. These two functions are repeated
126962 ** in the README.tokenizer file as an example, so it is important to
126963 ** test them.
126964 **
126965 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
126966 ** function with no arguments. An assert() will fail if a problem is
126967 ** detected. i.e.:
126968 **
126969 **     SELECT fts3_tokenizer_internal_test();
126970 **
126971 */
126972 static void intTestFunc(
126973   sqlite3_context *context,
126974   int argc,
126975   sqlite3_value **argv
126976 ){
126977   int rc;
126978   const sqlite3_tokenizer_module *p1;
126979   const sqlite3_tokenizer_module *p2;
126980   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
126981
126982   UNUSED_PARAMETER(argc);
126983   UNUSED_PARAMETER(argv);
126984
126985   /* Test the query function */
126986   sqlite3Fts3SimpleTokenizerModule(&p1);
126987   rc = queryTokenizer(db, "simple", &p2);
126988   assert( rc==SQLITE_OK );
126989   assert( p1==p2 );
126990   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
126991   assert( rc==SQLITE_ERROR );
126992   assert( p2==0 );
126993   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
126994
126995   /* Test the storage function */
126996   rc = registerTokenizer(db, "nosuchtokenizer", p1);
126997   assert( rc==SQLITE_OK );
126998   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
126999   assert( rc==SQLITE_OK );
127000   assert( p2==p1 );
127001
127002   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
127003 }
127004
127005 #endif
127006
127007 /*
127008 ** Set up SQL objects in database db used to access the contents of
127009 ** the hash table pointed to by argument pHash. The hash table must
127010 ** been initialised to use string keys, and to take a private copy
127011 ** of the key when a value is inserted. i.e. by a call similar to:
127012 **
127013 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
127014 **
127015 ** This function adds a scalar function (see header comment above
127016 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
127017 ** defined at compilation time, a temporary virtual table (see header
127018 ** comment above struct HashTableVtab) to the database schema. Both
127019 ** provide read/write access to the contents of *pHash.
127020 **
127021 ** The third argument to this function, zName, is used as the name
127022 ** of both the scalar and, if created, the virtual table.
127023 */
127024 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
127025   sqlite3 *db,
127026   Fts3Hash *pHash,
127027   const char *zName
127028 ){
127029   int rc = SQLITE_OK;
127030   void *p = (void *)pHash;
127031   const int any = SQLITE_ANY;
127032
127033 #ifdef SQLITE_TEST
127034   char *zTest = 0;
127035   char *zTest2 = 0;
127036   void *pdb = (void *)db;
127037   zTest = sqlite3_mprintf("%s_test", zName);
127038   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
127039   if( !zTest || !zTest2 ){
127040     rc = SQLITE_NOMEM;
127041   }
127042 #endif
127043
127044   if( SQLITE_OK==rc ){
127045     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
127046   }
127047   if( SQLITE_OK==rc ){
127048     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
127049   }
127050 #ifdef SQLITE_TEST
127051   if( SQLITE_OK==rc ){
127052     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
127053   }
127054   if( SQLITE_OK==rc ){
127055     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
127056   }
127057 #endif
127058
127059 #ifdef SQLITE_TEST
127060   sqlite3_free(zTest);
127061   sqlite3_free(zTest2);
127062 #endif
127063
127064   return rc;
127065 }
127066
127067 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127068
127069 /************** End of fts3_tokenizer.c **************************************/
127070 /************** Begin file fts3_tokenizer1.c *********************************/
127071 /*
127072 ** 2006 Oct 10
127073 **
127074 ** The author disclaims copyright to this source code.  In place of
127075 ** a legal notice, here is a blessing:
127076 **
127077 **    May you do good and not evil.
127078 **    May you find forgiveness for yourself and forgive others.
127079 **    May you share freely, never taking more than you give.
127080 **
127081 ******************************************************************************
127082 **
127083 ** Implementation of the "simple" full-text-search tokenizer.
127084 */
127085
127086 /*
127087 ** The code in this file is only compiled if:
127088 **
127089 **     * The FTS3 module is being built as an extension
127090 **       (in which case SQLITE_CORE is not defined), or
127091 **
127092 **     * The FTS3 module is being built into the core of
127093 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
127094 */
127095 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127096
127097 /* #include <assert.h> */
127098 /* #include <stdlib.h> */
127099 /* #include <stdio.h> */
127100 /* #include <string.h> */
127101
127102
127103 typedef struct simple_tokenizer {
127104   sqlite3_tokenizer base;
127105   char delim[128];             /* flag ASCII delimiters */
127106 } simple_tokenizer;
127107
127108 typedef struct simple_tokenizer_cursor {
127109   sqlite3_tokenizer_cursor base;
127110   const char *pInput;          /* input we are tokenizing */
127111   int nBytes;                  /* size of the input */
127112   int iOffset;                 /* current position in pInput */
127113   int iToken;                  /* index of next token to be returned */
127114   char *pToken;                /* storage for current token */
127115   int nTokenAllocated;         /* space allocated to zToken buffer */
127116 } simple_tokenizer_cursor;
127117
127118
127119 static int simpleDelim(simple_tokenizer *t, unsigned char c){
127120   return c<0x80 && t->delim[c];
127121 }
127122 static int fts3_isalnum(int x){
127123   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
127124 }
127125
127126 /*
127127 ** Create a new tokenizer instance.
127128 */
127129 static int simpleCreate(
127130   int argc, const char * const *argv,
127131   sqlite3_tokenizer **ppTokenizer
127132 ){
127133   simple_tokenizer *t;
127134
127135   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
127136   if( t==NULL ) return SQLITE_NOMEM;
127137   memset(t, 0, sizeof(*t));
127138
127139   /* TODO(shess) Delimiters need to remain the same from run to run,
127140   ** else we need to reindex.  One solution would be a meta-table to
127141   ** track such information in the database, then we'd only want this
127142   ** information on the initial create.
127143   */
127144   if( argc>1 ){
127145     int i, n = (int)strlen(argv[1]);
127146     for(i=0; i<n; i++){
127147       unsigned char ch = argv[1][i];
127148       /* We explicitly don't support UTF-8 delimiters for now. */
127149       if( ch>=0x80 ){
127150         sqlite3_free(t);
127151         return SQLITE_ERROR;
127152       }
127153       t->delim[ch] = 1;
127154     }
127155   } else {
127156     /* Mark non-alphanumeric ASCII characters as delimiters */
127157     int i;
127158     for(i=1; i<0x80; i++){
127159       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
127160     }
127161   }
127162
127163   *ppTokenizer = &t->base;
127164   return SQLITE_OK;
127165 }
127166
127167 /*
127168 ** Destroy a tokenizer
127169 */
127170 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
127171   sqlite3_free(pTokenizer);
127172   return SQLITE_OK;
127173 }
127174
127175 /*
127176 ** Prepare to begin tokenizing a particular string.  The input
127177 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
127178 ** used to incrementally tokenize this string is returned in
127179 ** *ppCursor.
127180 */
127181 static int simpleOpen(
127182   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
127183   const char *pInput, int nBytes,        /* String to be tokenized */
127184   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
127185 ){
127186   simple_tokenizer_cursor *c;
127187
127188   UNUSED_PARAMETER(pTokenizer);
127189
127190   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
127191   if( c==NULL ) return SQLITE_NOMEM;
127192
127193   c->pInput = pInput;
127194   if( pInput==0 ){
127195     c->nBytes = 0;
127196   }else if( nBytes<0 ){
127197     c->nBytes = (int)strlen(pInput);
127198   }else{
127199     c->nBytes = nBytes;
127200   }
127201   c->iOffset = 0;                 /* start tokenizing at the beginning */
127202   c->iToken = 0;
127203   c->pToken = NULL;               /* no space allocated, yet. */
127204   c->nTokenAllocated = 0;
127205
127206   *ppCursor = &c->base;
127207   return SQLITE_OK;
127208 }
127209
127210 /*
127211 ** Close a tokenization cursor previously opened by a call to
127212 ** simpleOpen() above.
127213 */
127214 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
127215   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
127216   sqlite3_free(c->pToken);
127217   sqlite3_free(c);
127218   return SQLITE_OK;
127219 }
127220
127221 /*
127222 ** Extract the next token from a tokenization cursor.  The cursor must
127223 ** have been opened by a prior call to simpleOpen().
127224 */
127225 static int simpleNext(
127226   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
127227   const char **ppToken,               /* OUT: *ppToken is the token text */
127228   int *pnBytes,                       /* OUT: Number of bytes in token */
127229   int *piStartOffset,                 /* OUT: Starting offset of token */
127230   int *piEndOffset,                   /* OUT: Ending offset of token */
127231   int *piPosition                     /* OUT: Position integer of token */
127232 ){
127233   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
127234   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
127235   unsigned char *p = (unsigned char *)c->pInput;
127236
127237   while( c->iOffset<c->nBytes ){
127238     int iStartOffset;
127239
127240     /* Scan past delimiter characters */
127241     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
127242       c->iOffset++;
127243     }
127244
127245     /* Count non-delimiter characters. */
127246     iStartOffset = c->iOffset;
127247     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
127248       c->iOffset++;
127249     }
127250
127251     if( c->iOffset>iStartOffset ){
127252       int i, n = c->iOffset-iStartOffset;
127253       if( n>c->nTokenAllocated ){
127254         char *pNew;
127255         c->nTokenAllocated = n+20;
127256         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
127257         if( !pNew ) return SQLITE_NOMEM;
127258         c->pToken = pNew;
127259       }
127260       for(i=0; i<n; i++){
127261         /* TODO(shess) This needs expansion to handle UTF-8
127262         ** case-insensitivity.
127263         */
127264         unsigned char ch = p[iStartOffset+i];
127265         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
127266       }
127267       *ppToken = c->pToken;
127268       *pnBytes = n;
127269       *piStartOffset = iStartOffset;
127270       *piEndOffset = c->iOffset;
127271       *piPosition = c->iToken++;
127272
127273       return SQLITE_OK;
127274     }
127275   }
127276   return SQLITE_DONE;
127277 }
127278
127279 /*
127280 ** The set of routines that implement the simple tokenizer
127281 */
127282 static const sqlite3_tokenizer_module simpleTokenizerModule = {
127283   0,
127284   simpleCreate,
127285   simpleDestroy,
127286   simpleOpen,
127287   simpleClose,
127288   simpleNext,
127289   0,
127290 };
127291
127292 /*
127293 ** Allocate a new simple tokenizer.  Return a pointer to the new
127294 ** tokenizer in *ppModule
127295 */
127296 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
127297   sqlite3_tokenizer_module const**ppModule
127298 ){
127299   *ppModule = &simpleTokenizerModule;
127300 }
127301
127302 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127303
127304 /************** End of fts3_tokenizer1.c *************************************/
127305 /************** Begin file fts3_write.c **************************************/
127306 /*
127307 ** 2009 Oct 23
127308 **
127309 ** The author disclaims copyright to this source code.  In place of
127310 ** a legal notice, here is a blessing:
127311 **
127312 **    May you do good and not evil.
127313 **    May you find forgiveness for yourself and forgive others.
127314 **    May you share freely, never taking more than you give.
127315 **
127316 ******************************************************************************
127317 **
127318 ** This file is part of the SQLite FTS3 extension module. Specifically,
127319 ** this file contains code to insert, update and delete rows from FTS3
127320 ** tables. It also contains code to merge FTS3 b-tree segments. Some
127321 ** of the sub-routines used to merge segments are also used by the query
127322 ** code in fts3.c.
127323 */
127324
127325 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127326
127327 /* #include <string.h> */
127328 /* #include <assert.h> */
127329 /* #include <stdlib.h> */
127330
127331
127332 #define FTS_MAX_APPENDABLE_HEIGHT 16
127333
127334 /*
127335 ** When full-text index nodes are loaded from disk, the buffer that they
127336 ** are loaded into has the following number of bytes of padding at the end
127337 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
127338 ** of 920 bytes is allocated for it.
127339 **
127340 ** This means that if we have a pointer into a buffer containing node data,
127341 ** it is always safe to read up to two varints from it without risking an
127342 ** overread, even if the node data is corrupted.
127343 */
127344 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
127345
127346 /*
127347 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
127348 ** memory incrementally instead of all at once. This can be a big performance
127349 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
127350 ** method before retrieving all query results (as may happen, for example,
127351 ** if a query has a LIMIT clause).
127352 **
127353 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
127354 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
127355 ** The code is written so that the hard lower-limit for each of these values
127356 ** is 1. Clearly such small values would be inefficient, but can be useful
127357 ** for testing purposes.
127358 **
127359 ** If this module is built with SQLITE_TEST defined, these constants may
127360 ** be overridden at runtime for testing purposes. File fts3_test.c contains
127361 ** a Tcl interface to read and write the values.
127362 */
127363 #ifdef SQLITE_TEST
127364 int test_fts3_node_chunksize = (4*1024);
127365 int test_fts3_node_chunk_threshold = (4*1024)*4;
127366 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
127367 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
127368 #else
127369 # define FTS3_NODE_CHUNKSIZE (4*1024)
127370 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
127371 #endif
127372
127373 /*
127374 ** The two values that may be meaningfully bound to the :1 parameter in
127375 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
127376 */
127377 #define FTS_STAT_DOCTOTAL      0
127378 #define FTS_STAT_INCRMERGEHINT 1
127379 #define FTS_STAT_AUTOINCRMERGE 2
127380
127381 /*
127382 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
127383 ** and incremental merge operation that takes place. This is used for
127384 ** debugging FTS only, it should not usually be turned on in production
127385 ** systems.
127386 */
127387 #ifdef FTS3_LOG_MERGES
127388 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
127389   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
127390 }
127391 #else
127392 #define fts3LogMerge(x, y)
127393 #endif
127394
127395
127396 typedef struct PendingList PendingList;
127397 typedef struct SegmentNode SegmentNode;
127398 typedef struct SegmentWriter SegmentWriter;
127399
127400 /*
127401 ** An instance of the following data structure is used to build doclists
127402 ** incrementally. See function fts3PendingListAppend() for details.
127403 */
127404 struct PendingList {
127405   int nData;
127406   char *aData;
127407   int nSpace;
127408   sqlite3_int64 iLastDocid;
127409   sqlite3_int64 iLastCol;
127410   sqlite3_int64 iLastPos;
127411 };
127412
127413
127414 /*
127415 ** Each cursor has a (possibly empty) linked list of the following objects.
127416 */
127417 struct Fts3DeferredToken {
127418   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
127419   int iCol;                       /* Column token must occur in */
127420   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
127421   PendingList *pList;             /* Doclist is assembled here */
127422 };
127423
127424 /*
127425 ** An instance of this structure is used to iterate through the terms on
127426 ** a contiguous set of segment b-tree leaf nodes. Although the details of
127427 ** this structure are only manipulated by code in this file, opaque handles
127428 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
127429 ** terms when querying the full-text index. See functions:
127430 **
127431 **   sqlite3Fts3SegReaderNew()
127432 **   sqlite3Fts3SegReaderFree()
127433 **   sqlite3Fts3SegReaderIterate()
127434 **
127435 ** Methods used to manipulate Fts3SegReader structures:
127436 **
127437 **   fts3SegReaderNext()
127438 **   fts3SegReaderFirstDocid()
127439 **   fts3SegReaderNextDocid()
127440 */
127441 struct Fts3SegReader {
127442   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
127443   u8 bLookup;                     /* True for a lookup only */
127444   u8 rootOnly;                    /* True for a root-only reader */
127445
127446   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
127447   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
127448   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
127449   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
127450
127451   char *aNode;                    /* Pointer to node data (or NULL) */
127452   int nNode;                      /* Size of buffer at aNode (or 0) */
127453   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
127454   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
127455
127456   Fts3HashElem **ppNextElem;
127457
127458   /* Variables set by fts3SegReaderNext(). These may be read directly
127459   ** by the caller. They are valid from the time SegmentReaderNew() returns
127460   ** until SegmentReaderNext() returns something other than SQLITE_OK
127461   ** (i.e. SQLITE_DONE).
127462   */
127463   int nTerm;                      /* Number of bytes in current term */
127464   char *zTerm;                    /* Pointer to current term */
127465   int nTermAlloc;                 /* Allocated size of zTerm buffer */
127466   char *aDoclist;                 /* Pointer to doclist of current entry */
127467   int nDoclist;                   /* Size of doclist in current entry */
127468
127469   /* The following variables are used by fts3SegReaderNextDocid() to iterate
127470   ** through the current doclist (aDoclist/nDoclist).
127471   */
127472   char *pOffsetList;
127473   int nOffsetList;                /* For descending pending seg-readers only */
127474   sqlite3_int64 iDocid;
127475 };
127476
127477 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
127478 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
127479
127480 /*
127481 ** An instance of this structure is used to create a segment b-tree in the
127482 ** database. The internal details of this type are only accessed by the
127483 ** following functions:
127484 **
127485 **   fts3SegWriterAdd()
127486 **   fts3SegWriterFlush()
127487 **   fts3SegWriterFree()
127488 */
127489 struct SegmentWriter {
127490   SegmentNode *pTree;             /* Pointer to interior tree structure */
127491   sqlite3_int64 iFirst;           /* First slot in %_segments written */
127492   sqlite3_int64 iFree;            /* Next free slot in %_segments */
127493   char *zTerm;                    /* Pointer to previous term buffer */
127494   int nTerm;                      /* Number of bytes in zTerm */
127495   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
127496   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
127497   int nSize;                      /* Size of allocation at aData */
127498   int nData;                      /* Bytes of data in aData */
127499   char *aData;                    /* Pointer to block from malloc() */
127500 };
127501
127502 /*
127503 ** Type SegmentNode is used by the following three functions to create
127504 ** the interior part of the segment b+-tree structures (everything except
127505 ** the leaf nodes). These functions and type are only ever used by code
127506 ** within the fts3SegWriterXXX() family of functions described above.
127507 **
127508 **   fts3NodeAddTerm()
127509 **   fts3NodeWrite()
127510 **   fts3NodeFree()
127511 **
127512 ** When a b+tree is written to the database (either as a result of a merge
127513 ** or the pending-terms table being flushed), leaves are written into the
127514 ** database file as soon as they are completely populated. The interior of
127515 ** the tree is assembled in memory and written out only once all leaves have
127516 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
127517 ** very large, meaning that the interior of the tree consumes relatively
127518 ** little memory.
127519 */
127520 struct SegmentNode {
127521   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
127522   SegmentNode *pRight;            /* Pointer to right-sibling */
127523   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
127524   int nEntry;                     /* Number of terms written to node so far */
127525   char *zTerm;                    /* Pointer to previous term buffer */
127526   int nTerm;                      /* Number of bytes in zTerm */
127527   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
127528   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
127529   int nData;                      /* Bytes of valid data so far */
127530   char *aData;                    /* Node data */
127531 };
127532
127533 /*
127534 ** Valid values for the second argument to fts3SqlStmt().
127535 */
127536 #define SQL_DELETE_CONTENT             0
127537 #define SQL_IS_EMPTY                   1
127538 #define SQL_DELETE_ALL_CONTENT         2
127539 #define SQL_DELETE_ALL_SEGMENTS        3
127540 #define SQL_DELETE_ALL_SEGDIR          4
127541 #define SQL_DELETE_ALL_DOCSIZE         5
127542 #define SQL_DELETE_ALL_STAT            6
127543 #define SQL_SELECT_CONTENT_BY_ROWID    7
127544 #define SQL_NEXT_SEGMENT_INDEX         8
127545 #define SQL_INSERT_SEGMENTS            9
127546 #define SQL_NEXT_SEGMENTS_ID          10
127547 #define SQL_INSERT_SEGDIR             11
127548 #define SQL_SELECT_LEVEL              12
127549 #define SQL_SELECT_LEVEL_RANGE        13
127550 #define SQL_SELECT_LEVEL_COUNT        14
127551 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
127552 #define SQL_DELETE_SEGDIR_LEVEL       16
127553 #define SQL_DELETE_SEGMENTS_RANGE     17
127554 #define SQL_CONTENT_INSERT            18
127555 #define SQL_DELETE_DOCSIZE            19
127556 #define SQL_REPLACE_DOCSIZE           20
127557 #define SQL_SELECT_DOCSIZE            21
127558 #define SQL_SELECT_STAT               22
127559 #define SQL_REPLACE_STAT              23
127560
127561 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
127562 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
127563 #define SQL_DELETE_SEGDIR_RANGE       26
127564 #define SQL_SELECT_ALL_LANGID         27
127565 #define SQL_FIND_MERGE_LEVEL          28
127566 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
127567 #define SQL_DELETE_SEGDIR_ENTRY       30
127568 #define SQL_SHIFT_SEGDIR_ENTRY        31
127569 #define SQL_SELECT_SEGDIR             32
127570 #define SQL_CHOMP_SEGDIR              33
127571 #define SQL_SEGMENT_IS_APPENDABLE     34
127572 #define SQL_SELECT_INDEXES            35
127573 #define SQL_SELECT_MXLEVEL            36
127574
127575 /*
127576 ** This function is used to obtain an SQLite prepared statement handle
127577 ** for the statement identified by the second argument. If successful,
127578 ** *pp is set to the requested statement handle and SQLITE_OK returned.
127579 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
127580 **
127581 ** If argument apVal is not NULL, then it must point to an array with
127582 ** at least as many entries as the requested statement has bound
127583 ** parameters. The values are bound to the statements parameters before
127584 ** returning.
127585 */
127586 static int fts3SqlStmt(
127587   Fts3Table *p,                   /* Virtual table handle */
127588   int eStmt,                      /* One of the SQL_XXX constants above */
127589   sqlite3_stmt **pp,              /* OUT: Statement handle */
127590   sqlite3_value **apVal           /* Values to bind to statement */
127591 ){
127592   const char *azSql[] = {
127593 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
127594 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
127595 /* 2  */  "DELETE FROM %Q.'%q_content'",
127596 /* 3  */  "DELETE FROM %Q.'%q_segments'",
127597 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
127598 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
127599 /* 6  */  "DELETE FROM %Q.'%q_stat'",
127600 /* 7  */  "SELECT %s WHERE rowid=?",
127601 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
127602 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
127603 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
127604 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
127605
127606           /* Return segments in order from oldest to newest.*/
127607 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
127608             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
127609 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
127610             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
127611             "ORDER BY level DESC, idx ASC",
127612
127613 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
127614 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
127615
127616 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
127617 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
127618 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
127619 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
127620 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
127621 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
127622 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
127623 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
127624 /* 24 */  "",
127625 /* 25 */  "",
127626
127627 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
127628 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
127629
127630 /* This statement is used to determine which level to read the input from
127631 ** when performing an incremental merge. It returns the absolute level number
127632 ** of the oldest level in the db that contains at least ? segments. Or,
127633 ** if no level in the FTS index contains more than ? segments, the statement
127634 ** returns zero rows.  */
127635 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
127636          "  ORDER BY (level %% 1024) ASC LIMIT 1",
127637
127638 /* Estimate the upper limit on the number of leaf nodes in a new segment
127639 ** created by merging the oldest :2 segments from absolute level :1. See
127640 ** function sqlite3Fts3Incrmerge() for details.  */
127641 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
127642          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
127643
127644 /* SQL_DELETE_SEGDIR_ENTRY
127645 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
127646 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
127647
127648 /* SQL_SHIFT_SEGDIR_ENTRY
127649 **   Modify the idx value for the segment with idx=:3 on absolute level :2
127650 **   to :1.  */
127651 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
127652
127653 /* SQL_SELECT_SEGDIR
127654 **   Read a single entry from the %_segdir table. The entry from absolute
127655 **   level :1 with index value :2.  */
127656 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
127657             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
127658
127659 /* SQL_CHOMP_SEGDIR
127660 **   Update the start_block (:1) and root (:2) fields of the %_segdir
127661 **   entry located on absolute level :3 with index :4.  */
127662 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
127663             "WHERE level = ? AND idx = ?",
127664
127665 /* SQL_SEGMENT_IS_APPENDABLE
127666 **   Return a single row if the segment with end_block=? is appendable. Or
127667 **   no rows otherwise.  */
127668 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
127669
127670 /* SQL_SELECT_INDEXES
127671 **   Return the list of valid segment indexes for absolute level ?  */
127672 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
127673
127674 /* SQL_SELECT_MXLEVEL
127675 **   Return the largest relative level in the FTS index or indexes.  */
127676 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
127677   };
127678   int rc = SQLITE_OK;
127679   sqlite3_stmt *pStmt;
127680
127681   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
127682   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
127683
127684   pStmt = p->aStmt[eStmt];
127685   if( !pStmt ){
127686     char *zSql;
127687     if( eStmt==SQL_CONTENT_INSERT ){
127688       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
127689     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
127690       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
127691     }else{
127692       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
127693     }
127694     if( !zSql ){
127695       rc = SQLITE_NOMEM;
127696     }else{
127697       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
127698       sqlite3_free(zSql);
127699       assert( rc==SQLITE_OK || pStmt==0 );
127700       p->aStmt[eStmt] = pStmt;
127701     }
127702   }
127703   if( apVal ){
127704     int i;
127705     int nParam = sqlite3_bind_parameter_count(pStmt);
127706     for(i=0; rc==SQLITE_OK && i<nParam; i++){
127707       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
127708     }
127709   }
127710   *pp = pStmt;
127711   return rc;
127712 }
127713
127714
127715 static int fts3SelectDocsize(
127716   Fts3Table *pTab,                /* FTS3 table handle */
127717   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
127718   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
127719 ){
127720   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
127721   int rc;                         /* Return code */
127722
127723   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
127724   if( rc==SQLITE_OK ){
127725     sqlite3_bind_int64(pStmt, 1, iDocid);
127726     rc = sqlite3_step(pStmt);
127727     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
127728       rc = sqlite3_reset(pStmt);
127729       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
127730       pStmt = 0;
127731     }else{
127732       rc = SQLITE_OK;
127733     }
127734   }
127735
127736   *ppStmt = pStmt;
127737   return rc;
127738 }
127739
127740 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
127741   Fts3Table *pTab,                /* Fts3 table handle */
127742   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
127743 ){
127744   sqlite3_stmt *pStmt = 0;
127745   int rc;
127746   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
127747   if( rc==SQLITE_OK ){
127748     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
127749     if( sqlite3_step(pStmt)!=SQLITE_ROW
127750      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
127751     ){
127752       rc = sqlite3_reset(pStmt);
127753       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
127754       pStmt = 0;
127755     }
127756   }
127757   *ppStmt = pStmt;
127758   return rc;
127759 }
127760
127761 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
127762   Fts3Table *pTab,                /* Fts3 table handle */
127763   sqlite3_int64 iDocid,           /* Docid to read size data for */
127764   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
127765 ){
127766   return fts3SelectDocsize(pTab, iDocid, ppStmt);
127767 }
127768
127769 /*
127770 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
127771 ** array apVal[] to the SQL statement identified by eStmt, the statement
127772 ** is executed.
127773 **
127774 ** Returns SQLITE_OK if the statement is successfully executed, or an
127775 ** SQLite error code otherwise.
127776 */
127777 static void fts3SqlExec(
127778   int *pRC,                /* Result code */
127779   Fts3Table *p,            /* The FTS3 table */
127780   int eStmt,               /* Index of statement to evaluate */
127781   sqlite3_value **apVal    /* Parameters to bind */
127782 ){
127783   sqlite3_stmt *pStmt;
127784   int rc;
127785   if( *pRC ) return;
127786   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
127787   if( rc==SQLITE_OK ){
127788     sqlite3_step(pStmt);
127789     rc = sqlite3_reset(pStmt);
127790   }
127791   *pRC = rc;
127792 }
127793
127794
127795 /*
127796 ** This function ensures that the caller has obtained a shared-cache
127797 ** table-lock on the %_content table. This is required before reading
127798 ** data from the fts3 table. If this lock is not acquired first, then
127799 ** the caller may end up holding read-locks on the %_segments and %_segdir
127800 ** tables, but no read-lock on the %_content table. If this happens
127801 ** a second connection will be able to write to the fts3 table, but
127802 ** attempting to commit those writes might return SQLITE_LOCKED or
127803 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
127804 ** write-locks on the %_segments and %_segdir ** tables).
127805 **
127806 ** We try to avoid this because if FTS3 returns any error when committing
127807 ** a transaction, the whole transaction will be rolled back. And this is
127808 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
127809 ** still happen if the user reads data directly from the %_segments or
127810 ** %_segdir tables instead of going through FTS3 though.
127811 **
127812 ** This reasoning does not apply to a content=xxx table.
127813 */
127814 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
127815   int rc;                         /* Return code */
127816   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
127817
127818   if( p->zContentTbl==0 ){
127819     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
127820     if( rc==SQLITE_OK ){
127821       sqlite3_bind_null(pStmt, 1);
127822       sqlite3_step(pStmt);
127823       rc = sqlite3_reset(pStmt);
127824     }
127825   }else{
127826     rc = SQLITE_OK;
127827   }
127828
127829   return rc;
127830 }
127831
127832 /*
127833 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
127834 ** Within each language id, a separate index is maintained to store the
127835 ** document terms, and each configured prefix size (configured the FTS
127836 ** "prefix=" option). And each index consists of multiple levels ("relative
127837 ** levels").
127838 **
127839 ** All three of these values (the language id, the specific index and the
127840 ** level within the index) are encoded in 64-bit integer values stored
127841 ** in the %_segdir table on disk. This function is used to convert three
127842 ** separate component values into the single 64-bit integer value that
127843 ** can be used to query the %_segdir table.
127844 **
127845 ** Specifically, each language-id/index combination is allocated 1024
127846 ** 64-bit integer level values ("absolute levels"). The main terms index
127847 ** for language-id 0 is allocate values 0-1023. The first prefix index
127848 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
127849 ** Language 1 indexes are allocated immediately following language 0.
127850 **
127851 ** So, for a system with nPrefix prefix indexes configured, the block of
127852 ** absolute levels that corresponds to language-id iLangid and index
127853 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
127854 */
127855 static sqlite3_int64 getAbsoluteLevel(
127856   Fts3Table *p,                   /* FTS3 table handle */
127857   int iLangid,                    /* Language id */
127858   int iIndex,                     /* Index in p->aIndex[] */
127859   int iLevel                      /* Level of segments */
127860 ){
127861   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
127862   assert( iLangid>=0 );
127863   assert( p->nIndex>0 );
127864   assert( iIndex>=0 && iIndex<p->nIndex );
127865
127866   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
127867   return iBase + iLevel;
127868 }
127869
127870 /*
127871 ** Set *ppStmt to a statement handle that may be used to iterate through
127872 ** all rows in the %_segdir table, from oldest to newest. If successful,
127873 ** return SQLITE_OK. If an error occurs while preparing the statement,
127874 ** return an SQLite error code.
127875 **
127876 ** There is only ever one instance of this SQL statement compiled for
127877 ** each FTS3 table.
127878 **
127879 ** The statement returns the following columns from the %_segdir table:
127880 **
127881 **   0: idx
127882 **   1: start_block
127883 **   2: leaves_end_block
127884 **   3: end_block
127885 **   4: root
127886 */
127887 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
127888   Fts3Table *p,                   /* FTS3 table */
127889   int iLangid,                    /* Language being queried */
127890   int iIndex,                     /* Index for p->aIndex[] */
127891   int iLevel,                     /* Level to select (relative level) */
127892   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
127893 ){
127894   int rc;
127895   sqlite3_stmt *pStmt = 0;
127896
127897   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
127898   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
127899   assert( iIndex>=0 && iIndex<p->nIndex );
127900
127901   if( iLevel<0 ){
127902     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
127903     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
127904     if( rc==SQLITE_OK ){
127905       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
127906       sqlite3_bind_int64(pStmt, 2,
127907           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
127908       );
127909     }
127910   }else{
127911     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
127912     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
127913     if( rc==SQLITE_OK ){
127914       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
127915     }
127916   }
127917   *ppStmt = pStmt;
127918   return rc;
127919 }
127920
127921
127922 /*
127923 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
127924 ** if successful, or an SQLite error code otherwise.
127925 **
127926 ** This function also serves to allocate the PendingList structure itself.
127927 ** For example, to create a new PendingList structure containing two
127928 ** varints:
127929 **
127930 **   PendingList *p = 0;
127931 **   fts3PendingListAppendVarint(&p, 1);
127932 **   fts3PendingListAppendVarint(&p, 2);
127933 */
127934 static int fts3PendingListAppendVarint(
127935   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
127936   sqlite3_int64 i                 /* Value to append to data */
127937 ){
127938   PendingList *p = *pp;
127939
127940   /* Allocate or grow the PendingList as required. */
127941   if( !p ){
127942     p = sqlite3_malloc(sizeof(*p) + 100);
127943     if( !p ){
127944       return SQLITE_NOMEM;
127945     }
127946     p->nSpace = 100;
127947     p->aData = (char *)&p[1];
127948     p->nData = 0;
127949   }
127950   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
127951     int nNew = p->nSpace * 2;
127952     p = sqlite3_realloc(p, sizeof(*p) + nNew);
127953     if( !p ){
127954       sqlite3_free(*pp);
127955       *pp = 0;
127956       return SQLITE_NOMEM;
127957     }
127958     p->nSpace = nNew;
127959     p->aData = (char *)&p[1];
127960   }
127961
127962   /* Append the new serialized varint to the end of the list. */
127963   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
127964   p->aData[p->nData] = '\0';
127965   *pp = p;
127966   return SQLITE_OK;
127967 }
127968
127969 /*
127970 ** Add a docid/column/position entry to a PendingList structure. Non-zero
127971 ** is returned if the structure is sqlite3_realloced as part of adding
127972 ** the entry. Otherwise, zero.
127973 **
127974 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
127975 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
127976 ** it is set to SQLITE_OK.
127977 */
127978 static int fts3PendingListAppend(
127979   PendingList **pp,               /* IN/OUT: PendingList structure */
127980   sqlite3_int64 iDocid,           /* Docid for entry to add */
127981   sqlite3_int64 iCol,             /* Column for entry to add */
127982   sqlite3_int64 iPos,             /* Position of term for entry to add */
127983   int *pRc                        /* OUT: Return code */
127984 ){
127985   PendingList *p = *pp;
127986   int rc = SQLITE_OK;
127987
127988   assert( !p || p->iLastDocid<=iDocid );
127989
127990   if( !p || p->iLastDocid!=iDocid ){
127991     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
127992     if( p ){
127993       assert( p->nData<p->nSpace );
127994       assert( p->aData[p->nData]==0 );
127995       p->nData++;
127996     }
127997     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
127998       goto pendinglistappend_out;
127999     }
128000     p->iLastCol = -1;
128001     p->iLastPos = 0;
128002     p->iLastDocid = iDocid;
128003   }
128004   if( iCol>0 && p->iLastCol!=iCol ){
128005     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
128006      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
128007     ){
128008       goto pendinglistappend_out;
128009     }
128010     p->iLastCol = iCol;
128011     p->iLastPos = 0;
128012   }
128013   if( iCol>=0 ){
128014     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
128015     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
128016     if( rc==SQLITE_OK ){
128017       p->iLastPos = iPos;
128018     }
128019   }
128020
128021  pendinglistappend_out:
128022   *pRc = rc;
128023   if( p!=*pp ){
128024     *pp = p;
128025     return 1;
128026   }
128027   return 0;
128028 }
128029
128030 /*
128031 ** Free a PendingList object allocated by fts3PendingListAppend().
128032 */
128033 static void fts3PendingListDelete(PendingList *pList){
128034   sqlite3_free(pList);
128035 }
128036
128037 /*
128038 ** Add an entry to one of the pending-terms hash tables.
128039 */
128040 static int fts3PendingTermsAddOne(
128041   Fts3Table *p,
128042   int iCol,
128043   int iPos,
128044   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
128045   const char *zToken,
128046   int nToken
128047 ){
128048   PendingList *pList;
128049   int rc = SQLITE_OK;
128050
128051   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
128052   if( pList ){
128053     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
128054   }
128055   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
128056     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
128057       /* Malloc failed while inserting the new entry. This can only
128058       ** happen if there was no previous entry for this token.
128059       */
128060       assert( 0==fts3HashFind(pHash, zToken, nToken) );
128061       sqlite3_free(pList);
128062       rc = SQLITE_NOMEM;
128063     }
128064   }
128065   if( rc==SQLITE_OK ){
128066     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
128067   }
128068   return rc;
128069 }
128070
128071 /*
128072 ** Tokenize the nul-terminated string zText and add all tokens to the
128073 ** pending-terms hash-table. The docid used is that currently stored in
128074 ** p->iPrevDocid, and the column is specified by argument iCol.
128075 **
128076 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
128077 */
128078 static int fts3PendingTermsAdd(
128079   Fts3Table *p,                   /* Table into which text will be inserted */
128080   int iLangid,                    /* Language id to use */
128081   const char *zText,              /* Text of document to be inserted */
128082   int iCol,                       /* Column into which text is being inserted */
128083   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
128084 ){
128085   int rc;
128086   int iStart = 0;
128087   int iEnd = 0;
128088   int iPos = 0;
128089   int nWord = 0;
128090
128091   char const *zToken;
128092   int nToken = 0;
128093
128094   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
128095   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
128096   sqlite3_tokenizer_cursor *pCsr;
128097   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
128098       const char**,int*,int*,int*,int*);
128099
128100   assert( pTokenizer && pModule );
128101
128102   /* If the user has inserted a NULL value, this function may be called with
128103   ** zText==0. In this case, add zero token entries to the hash table and
128104   ** return early. */
128105   if( zText==0 ){
128106     *pnWord = 0;
128107     return SQLITE_OK;
128108   }
128109
128110   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
128111   if( rc!=SQLITE_OK ){
128112     return rc;
128113   }
128114
128115   xNext = pModule->xNext;
128116   while( SQLITE_OK==rc
128117       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
128118   ){
128119     int i;
128120     if( iPos>=nWord ) nWord = iPos+1;
128121
128122     /* Positions cannot be negative; we use -1 as a terminator internally.
128123     ** Tokens must have a non-zero length.
128124     */
128125     if( iPos<0 || !zToken || nToken<=0 ){
128126       rc = SQLITE_ERROR;
128127       break;
128128     }
128129
128130     /* Add the term to the terms index */
128131     rc = fts3PendingTermsAddOne(
128132         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
128133     );
128134
128135     /* Add the term to each of the prefix indexes that it is not too
128136     ** short for. */
128137     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
128138       struct Fts3Index *pIndex = &p->aIndex[i];
128139       if( nToken<pIndex->nPrefix ) continue;
128140       rc = fts3PendingTermsAddOne(
128141           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
128142       );
128143     }
128144   }
128145
128146   pModule->xClose(pCsr);
128147   *pnWord += nWord;
128148   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
128149 }
128150
128151 /*
128152 ** Calling this function indicates that subsequent calls to
128153 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
128154 ** contents of the document with docid iDocid.
128155 */
128156 static int fts3PendingTermsDocid(
128157   Fts3Table *p,                   /* Full-text table handle */
128158   int iLangid,                    /* Language id of row being written */
128159   sqlite_int64 iDocid             /* Docid of row being written */
128160 ){
128161   assert( iLangid>=0 );
128162
128163   /* TODO(shess) Explore whether partially flushing the buffer on
128164   ** forced-flush would provide better performance.  I suspect that if
128165   ** we ordered the doclists by size and flushed the largest until the
128166   ** buffer was half empty, that would let the less frequent terms
128167   ** generate longer doclists.
128168   */
128169   if( iDocid<=p->iPrevDocid
128170    || p->iPrevLangid!=iLangid
128171    || p->nPendingData>p->nMaxPendingData
128172   ){
128173     int rc = sqlite3Fts3PendingTermsFlush(p);
128174     if( rc!=SQLITE_OK ) return rc;
128175   }
128176   p->iPrevDocid = iDocid;
128177   p->iPrevLangid = iLangid;
128178   return SQLITE_OK;
128179 }
128180
128181 /*
128182 ** Discard the contents of the pending-terms hash tables.
128183 */
128184 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
128185   int i;
128186   for(i=0; i<p->nIndex; i++){
128187     Fts3HashElem *pElem;
128188     Fts3Hash *pHash = &p->aIndex[i].hPending;
128189     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
128190       PendingList *pList = (PendingList *)fts3HashData(pElem);
128191       fts3PendingListDelete(pList);
128192     }
128193     fts3HashClear(pHash);
128194   }
128195   p->nPendingData = 0;
128196 }
128197
128198 /*
128199 ** This function is called by the xUpdate() method as part of an INSERT
128200 ** operation. It adds entries for each term in the new record to the
128201 ** pendingTerms hash table.
128202 **
128203 ** Argument apVal is the same as the similarly named argument passed to
128204 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
128205 */
128206 static int fts3InsertTerms(
128207   Fts3Table *p,
128208   int iLangid,
128209   sqlite3_value **apVal,
128210   u32 *aSz
128211 ){
128212   int i;                          /* Iterator variable */
128213   for(i=2; i<p->nColumn+2; i++){
128214     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
128215     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
128216     if( rc!=SQLITE_OK ){
128217       return rc;
128218     }
128219     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
128220   }
128221   return SQLITE_OK;
128222 }
128223
128224 /*
128225 ** This function is called by the xUpdate() method for an INSERT operation.
128226 ** The apVal parameter is passed a copy of the apVal argument passed by
128227 ** SQLite to the xUpdate() method. i.e:
128228 **
128229 **   apVal[0]                Not used for INSERT.
128230 **   apVal[1]                rowid
128231 **   apVal[2]                Left-most user-defined column
128232 **   ...
128233 **   apVal[p->nColumn+1]     Right-most user-defined column
128234 **   apVal[p->nColumn+2]     Hidden column with same name as table
128235 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
128236 **   apVal[p->nColumn+4]     Hidden languageid column
128237 */
128238 static int fts3InsertData(
128239   Fts3Table *p,                   /* Full-text table */
128240   sqlite3_value **apVal,          /* Array of values to insert */
128241   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
128242 ){
128243   int rc;                         /* Return code */
128244   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
128245
128246   if( p->zContentTbl ){
128247     sqlite3_value *pRowid = apVal[p->nColumn+3];
128248     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
128249       pRowid = apVal[1];
128250     }
128251     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
128252       return SQLITE_CONSTRAINT;
128253     }
128254     *piDocid = sqlite3_value_int64(pRowid);
128255     return SQLITE_OK;
128256   }
128257
128258   /* Locate the statement handle used to insert data into the %_content
128259   ** table. The SQL for this statement is:
128260   **
128261   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
128262   **
128263   ** The statement features N '?' variables, where N is the number of user
128264   ** defined columns in the FTS3 table, plus one for the docid field.
128265   */
128266   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
128267   if( rc==SQLITE_OK && p->zLanguageid ){
128268     rc = sqlite3_bind_int(
128269         pContentInsert, p->nColumn+2,
128270         sqlite3_value_int(apVal[p->nColumn+4])
128271     );
128272   }
128273   if( rc!=SQLITE_OK ) return rc;
128274
128275   /* There is a quirk here. The users INSERT statement may have specified
128276   ** a value for the "rowid" field, for the "docid" field, or for both.
128277   ** Which is a problem, since "rowid" and "docid" are aliases for the
128278   ** same value. For example:
128279   **
128280   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
128281   **
128282   ** In FTS3, this is an error. It is an error to specify non-NULL values
128283   ** for both docid and some other rowid alias.
128284   */
128285   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
128286     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
128287      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
128288     ){
128289       /* A rowid/docid conflict. */
128290       return SQLITE_ERROR;
128291     }
128292     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
128293     if( rc!=SQLITE_OK ) return rc;
128294   }
128295
128296   /* Execute the statement to insert the record. Set *piDocid to the
128297   ** new docid value.
128298   */
128299   sqlite3_step(pContentInsert);
128300   rc = sqlite3_reset(pContentInsert);
128301
128302   *piDocid = sqlite3_last_insert_rowid(p->db);
128303   return rc;
128304 }
128305
128306
128307
128308 /*
128309 ** Remove all data from the FTS3 table. Clear the hash table containing
128310 ** pending terms.
128311 */
128312 static int fts3DeleteAll(Fts3Table *p, int bContent){
128313   int rc = SQLITE_OK;             /* Return code */
128314
128315   /* Discard the contents of the pending-terms hash table. */
128316   sqlite3Fts3PendingTermsClear(p);
128317
128318   /* Delete everything from the shadow tables. Except, leave %_content as
128319   ** is if bContent is false.  */
128320   assert( p->zContentTbl==0 || bContent==0 );
128321   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
128322   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
128323   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
128324   if( p->bHasDocsize ){
128325     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
128326   }
128327   if( p->bHasStat ){
128328     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
128329   }
128330   return rc;
128331 }
128332
128333 /*
128334 **
128335 */
128336 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
128337   int iLangid = 0;
128338   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
128339   return iLangid;
128340 }
128341
128342 /*
128343 ** The first element in the apVal[] array is assumed to contain the docid
128344 ** (an integer) of a row about to be deleted. Remove all terms from the
128345 ** full-text index.
128346 */
128347 static void fts3DeleteTerms(
128348   int *pRC,               /* Result code */
128349   Fts3Table *p,           /* The FTS table to delete from */
128350   sqlite3_value *pRowid,  /* The docid to be deleted */
128351   u32 *aSz,               /* Sizes of deleted document written here */
128352   int *pbFound            /* OUT: Set to true if row really does exist */
128353 ){
128354   int rc;
128355   sqlite3_stmt *pSelect;
128356
128357   assert( *pbFound==0 );
128358   if( *pRC ) return;
128359   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
128360   if( rc==SQLITE_OK ){
128361     if( SQLITE_ROW==sqlite3_step(pSelect) ){
128362       int i;
128363       int iLangid = langidFromSelect(p, pSelect);
128364       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
128365       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
128366         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
128367         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
128368         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
128369       }
128370       if( rc!=SQLITE_OK ){
128371         sqlite3_reset(pSelect);
128372         *pRC = rc;
128373         return;
128374       }
128375       *pbFound = 1;
128376     }
128377     rc = sqlite3_reset(pSelect);
128378   }else{
128379     sqlite3_reset(pSelect);
128380   }
128381   *pRC = rc;
128382 }
128383
128384 /*
128385 ** Forward declaration to account for the circular dependency between
128386 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
128387 */
128388 static int fts3SegmentMerge(Fts3Table *, int, int, int);
128389
128390 /*
128391 ** This function allocates a new level iLevel index in the segdir table.
128392 ** Usually, indexes are allocated within a level sequentially starting
128393 ** with 0, so the allocated index is one greater than the value returned
128394 ** by:
128395 **
128396 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
128397 **
128398 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
128399 ** level, they are merged into a single level (iLevel+1) segment and the
128400 ** allocated index is 0.
128401 **
128402 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
128403 ** returned. Otherwise, an SQLite error code is returned.
128404 */
128405 static int fts3AllocateSegdirIdx(
128406   Fts3Table *p,
128407   int iLangid,                    /* Language id */
128408   int iIndex,                     /* Index for p->aIndex */
128409   int iLevel,
128410   int *piIdx
128411 ){
128412   int rc;                         /* Return Code */
128413   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
128414   int iNext = 0;                  /* Result of query pNextIdx */
128415
128416   assert( iLangid>=0 );
128417   assert( p->nIndex>=1 );
128418
128419   /* Set variable iNext to the next available segdir index at level iLevel. */
128420   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
128421   if( rc==SQLITE_OK ){
128422     sqlite3_bind_int64(
128423         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
128424     );
128425     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
128426       iNext = sqlite3_column_int(pNextIdx, 0);
128427     }
128428     rc = sqlite3_reset(pNextIdx);
128429   }
128430
128431   if( rc==SQLITE_OK ){
128432     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
128433     ** full, merge all segments in level iLevel into a single iLevel+1
128434     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
128435     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
128436     */
128437     if( iNext>=FTS3_MERGE_COUNT ){
128438       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
128439       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
128440       *piIdx = 0;
128441     }else{
128442       *piIdx = iNext;
128443     }
128444   }
128445
128446   return rc;
128447 }
128448
128449 /*
128450 ** The %_segments table is declared as follows:
128451 **
128452 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
128453 **
128454 ** This function reads data from a single row of the %_segments table. The
128455 ** specific row is identified by the iBlockid parameter. If paBlob is not
128456 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
128457 ** with the contents of the blob stored in the "block" column of the
128458 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
128459 ** to the size of the blob in bytes before returning.
128460 **
128461 ** If an error occurs, or the table does not contain the specified row,
128462 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
128463 ** paBlob is non-NULL, then it is the responsibility of the caller to
128464 ** eventually free the returned buffer.
128465 **
128466 ** This function may leave an open sqlite3_blob* handle in the
128467 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
128468 ** to this function. The handle may be closed by calling the
128469 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
128470 ** performance improvement, but the blob handle should always be closed
128471 ** before control is returned to the user (to prevent a lock being held
128472 ** on the database file for longer than necessary). Thus, any virtual table
128473 ** method (xFilter etc.) that may directly or indirectly call this function
128474 ** must call sqlite3Fts3SegmentsClose() before returning.
128475 */
128476 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
128477   Fts3Table *p,                   /* FTS3 table handle */
128478   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
128479   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
128480   int *pnBlob,                    /* OUT: Size of blob data */
128481   int *pnLoad                     /* OUT: Bytes actually loaded */
128482 ){
128483   int rc;                         /* Return code */
128484
128485   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
128486   assert( pnBlob );
128487
128488   if( p->pSegments ){
128489     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
128490   }else{
128491     if( 0==p->zSegmentsTbl ){
128492       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
128493       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
128494     }
128495     rc = sqlite3_blob_open(
128496        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
128497     );
128498   }
128499
128500   if( rc==SQLITE_OK ){
128501     int nByte = sqlite3_blob_bytes(p->pSegments);
128502     *pnBlob = nByte;
128503     if( paBlob ){
128504       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
128505       if( !aByte ){
128506         rc = SQLITE_NOMEM;
128507       }else{
128508         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
128509           nByte = FTS3_NODE_CHUNKSIZE;
128510           *pnLoad = nByte;
128511         }
128512         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
128513         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
128514         if( rc!=SQLITE_OK ){
128515           sqlite3_free(aByte);
128516           aByte = 0;
128517         }
128518       }
128519       *paBlob = aByte;
128520     }
128521   }
128522
128523   return rc;
128524 }
128525
128526 /*
128527 ** Close the blob handle at p->pSegments, if it is open. See comments above
128528 ** the sqlite3Fts3ReadBlock() function for details.
128529 */
128530 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
128531   sqlite3_blob_close(p->pSegments);
128532   p->pSegments = 0;
128533 }
128534
128535 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
128536   int nRead;                      /* Number of bytes to read */
128537   int rc;                         /* Return code */
128538
128539   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
128540   rc = sqlite3_blob_read(
128541       pReader->pBlob,
128542       &pReader->aNode[pReader->nPopulate],
128543       nRead,
128544       pReader->nPopulate
128545   );
128546
128547   if( rc==SQLITE_OK ){
128548     pReader->nPopulate += nRead;
128549     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
128550     if( pReader->nPopulate==pReader->nNode ){
128551       sqlite3_blob_close(pReader->pBlob);
128552       pReader->pBlob = 0;
128553       pReader->nPopulate = 0;
128554     }
128555   }
128556   return rc;
128557 }
128558
128559 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
128560   int rc = SQLITE_OK;
128561   assert( !pReader->pBlob
128562        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
128563   );
128564   while( pReader->pBlob && rc==SQLITE_OK
128565      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
128566   ){
128567     rc = fts3SegReaderIncrRead(pReader);
128568   }
128569   return rc;
128570 }
128571
128572 /*
128573 ** Set an Fts3SegReader cursor to point at EOF.
128574 */
128575 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
128576   if( !fts3SegReaderIsRootOnly(pSeg) ){
128577     sqlite3_free(pSeg->aNode);
128578     sqlite3_blob_close(pSeg->pBlob);
128579     pSeg->pBlob = 0;
128580   }
128581   pSeg->aNode = 0;
128582 }
128583
128584 /*
128585 ** Move the iterator passed as the first argument to the next term in the
128586 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
128587 ** SQLITE_DONE. Otherwise, an SQLite error code.
128588 */
128589 static int fts3SegReaderNext(
128590   Fts3Table *p,
128591   Fts3SegReader *pReader,
128592   int bIncr
128593 ){
128594   int rc;                         /* Return code of various sub-routines */
128595   char *pNext;                    /* Cursor variable */
128596   int nPrefix;                    /* Number of bytes in term prefix */
128597   int nSuffix;                    /* Number of bytes in term suffix */
128598
128599   if( !pReader->aDoclist ){
128600     pNext = pReader->aNode;
128601   }else{
128602     pNext = &pReader->aDoclist[pReader->nDoclist];
128603   }
128604
128605   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
128606
128607     if( fts3SegReaderIsPending(pReader) ){
128608       Fts3HashElem *pElem = *(pReader->ppNextElem);
128609       if( pElem==0 ){
128610         pReader->aNode = 0;
128611       }else{
128612         PendingList *pList = (PendingList *)fts3HashData(pElem);
128613         pReader->zTerm = (char *)fts3HashKey(pElem);
128614         pReader->nTerm = fts3HashKeysize(pElem);
128615         pReader->nNode = pReader->nDoclist = pList->nData + 1;
128616         pReader->aNode = pReader->aDoclist = pList->aData;
128617         pReader->ppNextElem++;
128618         assert( pReader->aNode );
128619       }
128620       return SQLITE_OK;
128621     }
128622
128623     fts3SegReaderSetEof(pReader);
128624
128625     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
128626     ** blocks have already been traversed.  */
128627     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
128628     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
128629       return SQLITE_OK;
128630     }
128631
128632     rc = sqlite3Fts3ReadBlock(
128633         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
128634         (bIncr ? &pReader->nPopulate : 0)
128635     );
128636     if( rc!=SQLITE_OK ) return rc;
128637     assert( pReader->pBlob==0 );
128638     if( bIncr && pReader->nPopulate<pReader->nNode ){
128639       pReader->pBlob = p->pSegments;
128640       p->pSegments = 0;
128641     }
128642     pNext = pReader->aNode;
128643   }
128644
128645   assert( !fts3SegReaderIsPending(pReader) );
128646
128647   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
128648   if( rc!=SQLITE_OK ) return rc;
128649
128650   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
128651   ** safe (no risk of overread) even if the node data is corrupted. */
128652   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
128653   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
128654   if( nPrefix<0 || nSuffix<=0
128655    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
128656   ){
128657     return FTS_CORRUPT_VTAB;
128658   }
128659
128660   if( nPrefix+nSuffix>pReader->nTermAlloc ){
128661     int nNew = (nPrefix+nSuffix)*2;
128662     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
128663     if( !zNew ){
128664       return SQLITE_NOMEM;
128665     }
128666     pReader->zTerm = zNew;
128667     pReader->nTermAlloc = nNew;
128668   }
128669
128670   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
128671   if( rc!=SQLITE_OK ) return rc;
128672
128673   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
128674   pReader->nTerm = nPrefix+nSuffix;
128675   pNext += nSuffix;
128676   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
128677   pReader->aDoclist = pNext;
128678   pReader->pOffsetList = 0;
128679
128680   /* Check that the doclist does not appear to extend past the end of the
128681   ** b-tree node. And that the final byte of the doclist is 0x00. If either
128682   ** of these statements is untrue, then the data structure is corrupt.
128683   */
128684   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
128685    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
128686   ){
128687     return FTS_CORRUPT_VTAB;
128688   }
128689   return SQLITE_OK;
128690 }
128691
128692 /*
128693 ** Set the SegReader to point to the first docid in the doclist associated
128694 ** with the current term.
128695 */
128696 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
128697   int rc = SQLITE_OK;
128698   assert( pReader->aDoclist );
128699   assert( !pReader->pOffsetList );
128700   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
128701     u8 bEof = 0;
128702     pReader->iDocid = 0;
128703     pReader->nOffsetList = 0;
128704     sqlite3Fts3DoclistPrev(0,
128705         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
128706         &pReader->iDocid, &pReader->nOffsetList, &bEof
128707     );
128708   }else{
128709     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
128710     if( rc==SQLITE_OK ){
128711       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
128712       pReader->pOffsetList = &pReader->aDoclist[n];
128713     }
128714   }
128715   return rc;
128716 }
128717
128718 /*
128719 ** Advance the SegReader to point to the next docid in the doclist
128720 ** associated with the current term.
128721 **
128722 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
128723 ** *ppOffsetList is set to point to the first column-offset list
128724 ** in the doclist entry (i.e. immediately past the docid varint).
128725 ** *pnOffsetList is set to the length of the set of column-offset
128726 ** lists, not including the nul-terminator byte. For example:
128727 */
128728 static int fts3SegReaderNextDocid(
128729   Fts3Table *pTab,
128730   Fts3SegReader *pReader,         /* Reader to advance to next docid */
128731   char **ppOffsetList,            /* OUT: Pointer to current position-list */
128732   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
128733 ){
128734   int rc = SQLITE_OK;
128735   char *p = pReader->pOffsetList;
128736   char c = 0;
128737
128738   assert( p );
128739
128740   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
128741     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
128742     ** Pending-terms doclists are always built up in ascending order, so
128743     ** we have to iterate through them backwards here. */
128744     u8 bEof = 0;
128745     if( ppOffsetList ){
128746       *ppOffsetList = pReader->pOffsetList;
128747       *pnOffsetList = pReader->nOffsetList - 1;
128748     }
128749     sqlite3Fts3DoclistPrev(0,
128750         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
128751         &pReader->nOffsetList, &bEof
128752     );
128753     if( bEof ){
128754       pReader->pOffsetList = 0;
128755     }else{
128756       pReader->pOffsetList = p;
128757     }
128758   }else{
128759     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
128760
128761     /* Pointer p currently points at the first byte of an offset list. The
128762     ** following block advances it to point one byte past the end of
128763     ** the same offset list. */
128764     while( 1 ){
128765
128766       /* The following line of code (and the "p++" below the while() loop) is
128767       ** normally all that is required to move pointer p to the desired
128768       ** position. The exception is if this node is being loaded from disk
128769       ** incrementally and pointer "p" now points to the first byte passed
128770       ** the populated part of pReader->aNode[].
128771       */
128772       while( *p | c ) c = *p++ & 0x80;
128773       assert( *p==0 );
128774
128775       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
128776       rc = fts3SegReaderIncrRead(pReader);
128777       if( rc!=SQLITE_OK ) return rc;
128778     }
128779     p++;
128780
128781     /* If required, populate the output variables with a pointer to and the
128782     ** size of the previous offset-list.
128783     */
128784     if( ppOffsetList ){
128785       *ppOffsetList = pReader->pOffsetList;
128786       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
128787     }
128788
128789     while( p<pEnd && *p==0 ) p++;
128790
128791     /* If there are no more entries in the doclist, set pOffsetList to
128792     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
128793     ** Fts3SegReader.pOffsetList to point to the next offset list before
128794     ** returning.
128795     */
128796     if( p>=pEnd ){
128797       pReader->pOffsetList = 0;
128798     }else{
128799       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
128800       if( rc==SQLITE_OK ){
128801         sqlite3_int64 iDelta;
128802         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
128803         if( pTab->bDescIdx ){
128804           pReader->iDocid -= iDelta;
128805         }else{
128806           pReader->iDocid += iDelta;
128807         }
128808       }
128809     }
128810   }
128811
128812   return SQLITE_OK;
128813 }
128814
128815
128816 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
128817   Fts3Cursor *pCsr,
128818   Fts3MultiSegReader *pMsr,
128819   int *pnOvfl
128820 ){
128821   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
128822   int nOvfl = 0;
128823   int ii;
128824   int rc = SQLITE_OK;
128825   int pgsz = p->nPgsz;
128826
128827   assert( p->bFts4 );
128828   assert( pgsz>0 );
128829
128830   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
128831     Fts3SegReader *pReader = pMsr->apSegment[ii];
128832     if( !fts3SegReaderIsPending(pReader)
128833      && !fts3SegReaderIsRootOnly(pReader)
128834     ){
128835       sqlite3_int64 jj;
128836       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
128837         int nBlob;
128838         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
128839         if( rc!=SQLITE_OK ) break;
128840         if( (nBlob+35)>pgsz ){
128841           nOvfl += (nBlob + 34)/pgsz;
128842         }
128843       }
128844     }
128845   }
128846   *pnOvfl = nOvfl;
128847   return rc;
128848 }
128849
128850 /*
128851 ** Free all allocations associated with the iterator passed as the
128852 ** second argument.
128853 */
128854 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
128855   if( pReader && !fts3SegReaderIsPending(pReader) ){
128856     sqlite3_free(pReader->zTerm);
128857     if( !fts3SegReaderIsRootOnly(pReader) ){
128858       sqlite3_free(pReader->aNode);
128859       sqlite3_blob_close(pReader->pBlob);
128860     }
128861   }
128862   sqlite3_free(pReader);
128863 }
128864
128865 /*
128866 ** Allocate a new SegReader object.
128867 */
128868 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
128869   int iAge,                       /* Segment "age". */
128870   int bLookup,                    /* True for a lookup only */
128871   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
128872   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
128873   sqlite3_int64 iEndBlock,        /* Final block of segment */
128874   const char *zRoot,              /* Buffer containing root node */
128875   int nRoot,                      /* Size of buffer containing root node */
128876   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
128877 ){
128878   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
128879   int nExtra = 0;                 /* Bytes to allocate segment root node */
128880
128881   assert( iStartLeaf<=iEndLeaf );
128882   if( iStartLeaf==0 ){
128883     nExtra = nRoot + FTS3_NODE_PADDING;
128884   }
128885
128886   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
128887   if( !pReader ){
128888     return SQLITE_NOMEM;
128889   }
128890   memset(pReader, 0, sizeof(Fts3SegReader));
128891   pReader->iIdx = iAge;
128892   pReader->bLookup = bLookup!=0;
128893   pReader->iStartBlock = iStartLeaf;
128894   pReader->iLeafEndBlock = iEndLeaf;
128895   pReader->iEndBlock = iEndBlock;
128896
128897   if( nExtra ){
128898     /* The entire segment is stored in the root node. */
128899     pReader->aNode = (char *)&pReader[1];
128900     pReader->rootOnly = 1;
128901     pReader->nNode = nRoot;
128902     memcpy(pReader->aNode, zRoot, nRoot);
128903     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
128904   }else{
128905     pReader->iCurrentBlock = iStartLeaf-1;
128906   }
128907   *ppReader = pReader;
128908   return SQLITE_OK;
128909 }
128910
128911 /*
128912 ** This is a comparison function used as a qsort() callback when sorting
128913 ** an array of pending terms by term. This occurs as part of flushing
128914 ** the contents of the pending-terms hash table to the database.
128915 */
128916 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
128917   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
128918   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
128919   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
128920   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
128921
128922   int n = (n1<n2 ? n1 : n2);
128923   int c = memcmp(z1, z2, n);
128924   if( c==0 ){
128925     c = n1 - n2;
128926   }
128927   return c;
128928 }
128929
128930 /*
128931 ** This function is used to allocate an Fts3SegReader that iterates through
128932 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
128933 **
128934 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
128935 ** through each term in the pending-terms table. Or, if isPrefixIter is
128936 ** non-zero, it iterates through each term and its prefixes. For example, if
128937 ** the pending terms hash table contains the terms "sqlite", "mysql" and
128938 ** "firebird", then the iterator visits the following 'terms' (in the order
128939 ** shown):
128940 **
128941 **   f fi fir fire fireb firebi firebir firebird
128942 **   m my mys mysq mysql
128943 **   s sq sql sqli sqlit sqlite
128944 **
128945 ** Whereas if isPrefixIter is zero, the terms visited are:
128946 **
128947 **   firebird mysql sqlite
128948 */
128949 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
128950   Fts3Table *p,                   /* Virtual table handle */
128951   int iIndex,                     /* Index for p->aIndex */
128952   const char *zTerm,              /* Term to search for */
128953   int nTerm,                      /* Size of buffer zTerm */
128954   int bPrefix,                    /* True for a prefix iterator */
128955   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
128956 ){
128957   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
128958   Fts3HashElem *pE;               /* Iterator variable */
128959   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
128960   int nElem = 0;                  /* Size of array at aElem */
128961   int rc = SQLITE_OK;             /* Return Code */
128962   Fts3Hash *pHash;
128963
128964   pHash = &p->aIndex[iIndex].hPending;
128965   if( bPrefix ){
128966     int nAlloc = 0;               /* Size of allocated array at aElem */
128967
128968     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
128969       char *zKey = (char *)fts3HashKey(pE);
128970       int nKey = fts3HashKeysize(pE);
128971       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
128972         if( nElem==nAlloc ){
128973           Fts3HashElem **aElem2;
128974           nAlloc += 16;
128975           aElem2 = (Fts3HashElem **)sqlite3_realloc(
128976               aElem, nAlloc*sizeof(Fts3HashElem *)
128977           );
128978           if( !aElem2 ){
128979             rc = SQLITE_NOMEM;
128980             nElem = 0;
128981             break;
128982           }
128983           aElem = aElem2;
128984         }
128985
128986         aElem[nElem++] = pE;
128987       }
128988     }
128989
128990     /* If more than one term matches the prefix, sort the Fts3HashElem
128991     ** objects in term order using qsort(). This uses the same comparison
128992     ** callback as is used when flushing terms to disk.
128993     */
128994     if( nElem>1 ){
128995       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
128996     }
128997
128998   }else{
128999     /* The query is a simple term lookup that matches at most one term in
129000     ** the index. All that is required is a straight hash-lookup.
129001     **
129002     ** Because the stack address of pE may be accessed via the aElem pointer
129003     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
129004     ** within this entire function, not just this "else{...}" block.
129005     */
129006     pE = fts3HashFindElem(pHash, zTerm, nTerm);
129007     if( pE ){
129008       aElem = &pE;
129009       nElem = 1;
129010     }
129011   }
129012
129013   if( nElem>0 ){
129014     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
129015     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
129016     if( !pReader ){
129017       rc = SQLITE_NOMEM;
129018     }else{
129019       memset(pReader, 0, nByte);
129020       pReader->iIdx = 0x7FFFFFFF;
129021       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
129022       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
129023     }
129024   }
129025
129026   if( bPrefix ){
129027     sqlite3_free(aElem);
129028   }
129029   *ppReader = pReader;
129030   return rc;
129031 }
129032
129033 /*
129034 ** Compare the entries pointed to by two Fts3SegReader structures.
129035 ** Comparison is as follows:
129036 **
129037 **   1) EOF is greater than not EOF.
129038 **
129039 **   2) The current terms (if any) are compared using memcmp(). If one
129040 **      term is a prefix of another, the longer term is considered the
129041 **      larger.
129042 **
129043 **   3) By segment age. An older segment is considered larger.
129044 */
129045 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
129046   int rc;
129047   if( pLhs->aNode && pRhs->aNode ){
129048     int rc2 = pLhs->nTerm - pRhs->nTerm;
129049     if( rc2<0 ){
129050       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
129051     }else{
129052       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
129053     }
129054     if( rc==0 ){
129055       rc = rc2;
129056     }
129057   }else{
129058     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
129059   }
129060   if( rc==0 ){
129061     rc = pRhs->iIdx - pLhs->iIdx;
129062   }
129063   assert( rc!=0 );
129064   return rc;
129065 }
129066
129067 /*
129068 ** A different comparison function for SegReader structures. In this
129069 ** version, it is assumed that each SegReader points to an entry in
129070 ** a doclist for identical terms. Comparison is made as follows:
129071 **
129072 **   1) EOF (end of doclist in this case) is greater than not EOF.
129073 **
129074 **   2) By current docid.
129075 **
129076 **   3) By segment age. An older segment is considered larger.
129077 */
129078 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
129079   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
129080   if( rc==0 ){
129081     if( pLhs->iDocid==pRhs->iDocid ){
129082       rc = pRhs->iIdx - pLhs->iIdx;
129083     }else{
129084       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
129085     }
129086   }
129087   assert( pLhs->aNode && pRhs->aNode );
129088   return rc;
129089 }
129090 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
129091   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
129092   if( rc==0 ){
129093     if( pLhs->iDocid==pRhs->iDocid ){
129094       rc = pRhs->iIdx - pLhs->iIdx;
129095     }else{
129096       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
129097     }
129098   }
129099   assert( pLhs->aNode && pRhs->aNode );
129100   return rc;
129101 }
129102
129103 /*
129104 ** Compare the term that the Fts3SegReader object passed as the first argument
129105 ** points to with the term specified by arguments zTerm and nTerm.
129106 **
129107 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
129108 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
129109 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
129110 */
129111 static int fts3SegReaderTermCmp(
129112   Fts3SegReader *pSeg,            /* Segment reader object */
129113   const char *zTerm,              /* Term to compare to */
129114   int nTerm                       /* Size of term zTerm in bytes */
129115 ){
129116   int res = 0;
129117   if( pSeg->aNode ){
129118     if( pSeg->nTerm>nTerm ){
129119       res = memcmp(pSeg->zTerm, zTerm, nTerm);
129120     }else{
129121       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
129122     }
129123     if( res==0 ){
129124       res = pSeg->nTerm-nTerm;
129125     }
129126   }
129127   return res;
129128 }
129129
129130 /*
129131 ** Argument apSegment is an array of nSegment elements. It is known that
129132 ** the final (nSegment-nSuspect) members are already in sorted order
129133 ** (according to the comparison function provided). This function shuffles
129134 ** the array around until all entries are in sorted order.
129135 */
129136 static void fts3SegReaderSort(
129137   Fts3SegReader **apSegment,                     /* Array to sort entries of */
129138   int nSegment,                                  /* Size of apSegment array */
129139   int nSuspect,                                  /* Unsorted entry count */
129140   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
129141 ){
129142   int i;                          /* Iterator variable */
129143
129144   assert( nSuspect<=nSegment );
129145
129146   if( nSuspect==nSegment ) nSuspect--;
129147   for(i=nSuspect-1; i>=0; i--){
129148     int j;
129149     for(j=i; j<(nSegment-1); j++){
129150       Fts3SegReader *pTmp;
129151       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
129152       pTmp = apSegment[j+1];
129153       apSegment[j+1] = apSegment[j];
129154       apSegment[j] = pTmp;
129155     }
129156   }
129157
129158 #ifndef NDEBUG
129159   /* Check that the list really is sorted now. */
129160   for(i=0; i<(nSuspect-1); i++){
129161     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
129162   }
129163 #endif
129164 }
129165
129166 /*
129167 ** Insert a record into the %_segments table.
129168 */
129169 static int fts3WriteSegment(
129170   Fts3Table *p,                   /* Virtual table handle */
129171   sqlite3_int64 iBlock,           /* Block id for new block */
129172   char *z,                        /* Pointer to buffer containing block data */
129173   int n                           /* Size of buffer z in bytes */
129174 ){
129175   sqlite3_stmt *pStmt;
129176   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
129177   if( rc==SQLITE_OK ){
129178     sqlite3_bind_int64(pStmt, 1, iBlock);
129179     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
129180     sqlite3_step(pStmt);
129181     rc = sqlite3_reset(pStmt);
129182   }
129183   return rc;
129184 }
129185
129186 /*
129187 ** Find the largest relative level number in the table. If successful, set
129188 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
129189 ** set *pnMax to zero and return an SQLite error code.
129190 */
129191 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
129192   int rc;
129193   int mxLevel = 0;
129194   sqlite3_stmt *pStmt = 0;
129195
129196   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
129197   if( rc==SQLITE_OK ){
129198     if( SQLITE_ROW==sqlite3_step(pStmt) ){
129199       mxLevel = sqlite3_column_int(pStmt, 0);
129200     }
129201     rc = sqlite3_reset(pStmt);
129202   }
129203   *pnMax = mxLevel;
129204   return rc;
129205 }
129206
129207 /*
129208 ** Insert a record into the %_segdir table.
129209 */
129210 static int fts3WriteSegdir(
129211   Fts3Table *p,                   /* Virtual table handle */
129212   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
129213   int iIdx,                       /* Value for "idx" field */
129214   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
129215   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
129216   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
129217   char *zRoot,                    /* Blob value for "root" field */
129218   int nRoot                       /* Number of bytes in buffer zRoot */
129219 ){
129220   sqlite3_stmt *pStmt;
129221   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
129222   if( rc==SQLITE_OK ){
129223     sqlite3_bind_int64(pStmt, 1, iLevel);
129224     sqlite3_bind_int(pStmt, 2, iIdx);
129225     sqlite3_bind_int64(pStmt, 3, iStartBlock);
129226     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
129227     sqlite3_bind_int64(pStmt, 5, iEndBlock);
129228     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
129229     sqlite3_step(pStmt);
129230     rc = sqlite3_reset(pStmt);
129231   }
129232   return rc;
129233 }
129234
129235 /*
129236 ** Return the size of the common prefix (if any) shared by zPrev and
129237 ** zNext, in bytes. For example,
129238 **
129239 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
129240 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
129241 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
129242 */
129243 static int fts3PrefixCompress(
129244   const char *zPrev,              /* Buffer containing previous term */
129245   int nPrev,                      /* Size of buffer zPrev in bytes */
129246   const char *zNext,              /* Buffer containing next term */
129247   int nNext                       /* Size of buffer zNext in bytes */
129248 ){
129249   int n;
129250   UNUSED_PARAMETER(nNext);
129251   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
129252   return n;
129253 }
129254
129255 /*
129256 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
129257 ** (according to memcmp) than the previous term.
129258 */
129259 static int fts3NodeAddTerm(
129260   Fts3Table *p,                   /* Virtual table handle */
129261   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
129262   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
129263   const char *zTerm,              /* Pointer to buffer containing term */
129264   int nTerm                       /* Size of term in bytes */
129265 ){
129266   SegmentNode *pTree = *ppTree;
129267   int rc;
129268   SegmentNode *pNew;
129269
129270   /* First try to append the term to the current node. Return early if
129271   ** this is possible.
129272   */
129273   if( pTree ){
129274     int nData = pTree->nData;     /* Current size of node in bytes */
129275     int nReq = nData;             /* Required space after adding zTerm */
129276     int nPrefix;                  /* Number of bytes of prefix compression */
129277     int nSuffix;                  /* Suffix length */
129278
129279     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
129280     nSuffix = nTerm-nPrefix;
129281
129282     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
129283     if( nReq<=p->nNodeSize || !pTree->zTerm ){
129284
129285       if( nReq>p->nNodeSize ){
129286         /* An unusual case: this is the first term to be added to the node
129287         ** and the static node buffer (p->nNodeSize bytes) is not large
129288         ** enough. Use a separately malloced buffer instead This wastes
129289         ** p->nNodeSize bytes, but since this scenario only comes about when
129290         ** the database contain two terms that share a prefix of almost 2KB,
129291         ** this is not expected to be a serious problem.
129292         */
129293         assert( pTree->aData==(char *)&pTree[1] );
129294         pTree->aData = (char *)sqlite3_malloc(nReq);
129295         if( !pTree->aData ){
129296           return SQLITE_NOMEM;
129297         }
129298       }
129299
129300       if( pTree->zTerm ){
129301         /* There is no prefix-length field for first term in a node */
129302         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
129303       }
129304
129305       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
129306       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
129307       pTree->nData = nData + nSuffix;
129308       pTree->nEntry++;
129309
129310       if( isCopyTerm ){
129311         if( pTree->nMalloc<nTerm ){
129312           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
129313           if( !zNew ){
129314             return SQLITE_NOMEM;
129315           }
129316           pTree->nMalloc = nTerm*2;
129317           pTree->zMalloc = zNew;
129318         }
129319         pTree->zTerm = pTree->zMalloc;
129320         memcpy(pTree->zTerm, zTerm, nTerm);
129321         pTree->nTerm = nTerm;
129322       }else{
129323         pTree->zTerm = (char *)zTerm;
129324         pTree->nTerm = nTerm;
129325       }
129326       return SQLITE_OK;
129327     }
129328   }
129329
129330   /* If control flows to here, it was not possible to append zTerm to the
129331   ** current node. Create a new node (a right-sibling of the current node).
129332   ** If this is the first node in the tree, the term is added to it.
129333   **
129334   ** Otherwise, the term is not added to the new node, it is left empty for
129335   ** now. Instead, the term is inserted into the parent of pTree. If pTree
129336   ** has no parent, one is created here.
129337   */
129338   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
129339   if( !pNew ){
129340     return SQLITE_NOMEM;
129341   }
129342   memset(pNew, 0, sizeof(SegmentNode));
129343   pNew->nData = 1 + FTS3_VARINT_MAX;
129344   pNew->aData = (char *)&pNew[1];
129345
129346   if( pTree ){
129347     SegmentNode *pParent = pTree->pParent;
129348     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
129349     if( pTree->pParent==0 ){
129350       pTree->pParent = pParent;
129351     }
129352     pTree->pRight = pNew;
129353     pNew->pLeftmost = pTree->pLeftmost;
129354     pNew->pParent = pParent;
129355     pNew->zMalloc = pTree->zMalloc;
129356     pNew->nMalloc = pTree->nMalloc;
129357     pTree->zMalloc = 0;
129358   }else{
129359     pNew->pLeftmost = pNew;
129360     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
129361   }
129362
129363   *ppTree = pNew;
129364   return rc;
129365 }
129366
129367 /*
129368 ** Helper function for fts3NodeWrite().
129369 */
129370 static int fts3TreeFinishNode(
129371   SegmentNode *pTree,
129372   int iHeight,
129373   sqlite3_int64 iLeftChild
129374 ){
129375   int nStart;
129376   assert( iHeight>=1 && iHeight<128 );
129377   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
129378   pTree->aData[nStart] = (char)iHeight;
129379   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
129380   return nStart;
129381 }
129382
129383 /*
129384 ** Write the buffer for the segment node pTree and all of its peers to the
129385 ** database. Then call this function recursively to write the parent of
129386 ** pTree and its peers to the database.
129387 **
129388 ** Except, if pTree is a root node, do not write it to the database. Instead,
129389 ** set output variables *paRoot and *pnRoot to contain the root node.
129390 **
129391 ** If successful, SQLITE_OK is returned and output variable *piLast is
129392 ** set to the largest blockid written to the database (or zero if no
129393 ** blocks were written to the db). Otherwise, an SQLite error code is
129394 ** returned.
129395 */
129396 static int fts3NodeWrite(
129397   Fts3Table *p,                   /* Virtual table handle */
129398   SegmentNode *pTree,             /* SegmentNode handle */
129399   int iHeight,                    /* Height of this node in tree */
129400   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
129401   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
129402   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
129403   char **paRoot,                  /* OUT: Data for root node */
129404   int *pnRoot                     /* OUT: Size of root node in bytes */
129405 ){
129406   int rc = SQLITE_OK;
129407
129408   if( !pTree->pParent ){
129409     /* Root node of the tree. */
129410     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
129411     *piLast = iFree-1;
129412     *pnRoot = pTree->nData - nStart;
129413     *paRoot = &pTree->aData[nStart];
129414   }else{
129415     SegmentNode *pIter;
129416     sqlite3_int64 iNextFree = iFree;
129417     sqlite3_int64 iNextLeaf = iLeaf;
129418     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
129419       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
129420       int nWrite = pIter->nData - nStart;
129421
129422       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
129423       iNextFree++;
129424       iNextLeaf += (pIter->nEntry+1);
129425     }
129426     if( rc==SQLITE_OK ){
129427       assert( iNextLeaf==iFree );
129428       rc = fts3NodeWrite(
129429           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
129430       );
129431     }
129432   }
129433
129434   return rc;
129435 }
129436
129437 /*
129438 ** Free all memory allocations associated with the tree pTree.
129439 */
129440 static void fts3NodeFree(SegmentNode *pTree){
129441   if( pTree ){
129442     SegmentNode *p = pTree->pLeftmost;
129443     fts3NodeFree(p->pParent);
129444     while( p ){
129445       SegmentNode *pRight = p->pRight;
129446       if( p->aData!=(char *)&p[1] ){
129447         sqlite3_free(p->aData);
129448       }
129449       assert( pRight==0 || p->zMalloc==0 );
129450       sqlite3_free(p->zMalloc);
129451       sqlite3_free(p);
129452       p = pRight;
129453     }
129454   }
129455 }
129456
129457 /*
129458 ** Add a term to the segment being constructed by the SegmentWriter object
129459 ** *ppWriter. When adding the first term to a segment, *ppWriter should
129460 ** be passed NULL. This function will allocate a new SegmentWriter object
129461 ** and return it via the input/output variable *ppWriter in this case.
129462 **
129463 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
129464 */
129465 static int fts3SegWriterAdd(
129466   Fts3Table *p,                   /* Virtual table handle */
129467   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
129468   int isCopyTerm,                 /* True if buffer zTerm must be copied */
129469   const char *zTerm,              /* Pointer to buffer containing term */
129470   int nTerm,                      /* Size of term in bytes */
129471   const char *aDoclist,           /* Pointer to buffer containing doclist */
129472   int nDoclist                    /* Size of doclist in bytes */
129473 ){
129474   int nPrefix;                    /* Size of term prefix in bytes */
129475   int nSuffix;                    /* Size of term suffix in bytes */
129476   int nReq;                       /* Number of bytes required on leaf page */
129477   int nData;
129478   SegmentWriter *pWriter = *ppWriter;
129479
129480   if( !pWriter ){
129481     int rc;
129482     sqlite3_stmt *pStmt;
129483
129484     /* Allocate the SegmentWriter structure */
129485     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
129486     if( !pWriter ) return SQLITE_NOMEM;
129487     memset(pWriter, 0, sizeof(SegmentWriter));
129488     *ppWriter = pWriter;
129489
129490     /* Allocate a buffer in which to accumulate data */
129491     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
129492     if( !pWriter->aData ) return SQLITE_NOMEM;
129493     pWriter->nSize = p->nNodeSize;
129494
129495     /* Find the next free blockid in the %_segments table */
129496     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
129497     if( rc!=SQLITE_OK ) return rc;
129498     if( SQLITE_ROW==sqlite3_step(pStmt) ){
129499       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
129500       pWriter->iFirst = pWriter->iFree;
129501     }
129502     rc = sqlite3_reset(pStmt);
129503     if( rc!=SQLITE_OK ) return rc;
129504   }
129505   nData = pWriter->nData;
129506
129507   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
129508   nSuffix = nTerm-nPrefix;
129509
129510   /* Figure out how many bytes are required by this new entry */
129511   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
129512     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
129513     nSuffix +                               /* Term suffix */
129514     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
129515     nDoclist;                               /* Doclist data */
129516
129517   if( nData>0 && nData+nReq>p->nNodeSize ){
129518     int rc;
129519
129520     /* The current leaf node is full. Write it out to the database. */
129521     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
129522     if( rc!=SQLITE_OK ) return rc;
129523     p->nLeafAdd++;
129524
129525     /* Add the current term to the interior node tree. The term added to
129526     ** the interior tree must:
129527     **
129528     **   a) be greater than the largest term on the leaf node just written
129529     **      to the database (still available in pWriter->zTerm), and
129530     **
129531     **   b) be less than or equal to the term about to be added to the new
129532     **      leaf node (zTerm/nTerm).
129533     **
129534     ** In other words, it must be the prefix of zTerm 1 byte longer than
129535     ** the common prefix (if any) of zTerm and pWriter->zTerm.
129536     */
129537     assert( nPrefix<nTerm );
129538     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
129539     if( rc!=SQLITE_OK ) return rc;
129540
129541     nData = 0;
129542     pWriter->nTerm = 0;
129543
129544     nPrefix = 0;
129545     nSuffix = nTerm;
129546     nReq = 1 +                              /* varint containing prefix size */
129547       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
129548       nTerm +                               /* Term suffix */
129549       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
129550       nDoclist;                             /* Doclist data */
129551   }
129552
129553   /* If the buffer currently allocated is too small for this entry, realloc
129554   ** the buffer to make it large enough.
129555   */
129556   if( nReq>pWriter->nSize ){
129557     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
129558     if( !aNew ) return SQLITE_NOMEM;
129559     pWriter->aData = aNew;
129560     pWriter->nSize = nReq;
129561   }
129562   assert( nData+nReq<=pWriter->nSize );
129563
129564   /* Append the prefix-compressed term and doclist to the buffer. */
129565   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
129566   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
129567   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
129568   nData += nSuffix;
129569   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
129570   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
129571   pWriter->nData = nData + nDoclist;
129572
129573   /* Save the current term so that it can be used to prefix-compress the next.
129574   ** If the isCopyTerm parameter is true, then the buffer pointed to by
129575   ** zTerm is transient, so take a copy of the term data. Otherwise, just
129576   ** store a copy of the pointer.
129577   */
129578   if( isCopyTerm ){
129579     if( nTerm>pWriter->nMalloc ){
129580       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
129581       if( !zNew ){
129582         return SQLITE_NOMEM;
129583       }
129584       pWriter->nMalloc = nTerm*2;
129585       pWriter->zMalloc = zNew;
129586       pWriter->zTerm = zNew;
129587     }
129588     assert( pWriter->zTerm==pWriter->zMalloc );
129589     memcpy(pWriter->zTerm, zTerm, nTerm);
129590   }else{
129591     pWriter->zTerm = (char *)zTerm;
129592   }
129593   pWriter->nTerm = nTerm;
129594
129595   return SQLITE_OK;
129596 }
129597
129598 /*
129599 ** Flush all data associated with the SegmentWriter object pWriter to the
129600 ** database. This function must be called after all terms have been added
129601 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
129602 ** returned. Otherwise, an SQLite error code.
129603 */
129604 static int fts3SegWriterFlush(
129605   Fts3Table *p,                   /* Virtual table handle */
129606   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
129607   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
129608   int iIdx                        /* Value for 'idx' column of %_segdir */
129609 ){
129610   int rc;                         /* Return code */
129611   if( pWriter->pTree ){
129612     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
129613     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
129614     char *zRoot = NULL;           /* Pointer to buffer containing root node */
129615     int nRoot = 0;                /* Size of buffer zRoot */
129616
129617     iLastLeaf = pWriter->iFree;
129618     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
129619     if( rc==SQLITE_OK ){
129620       rc = fts3NodeWrite(p, pWriter->pTree, 1,
129621           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
129622     }
129623     if( rc==SQLITE_OK ){
129624       rc = fts3WriteSegdir(
129625           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
129626     }
129627   }else{
129628     /* The entire tree fits on the root node. Write it to the segdir table. */
129629     rc = fts3WriteSegdir(
129630         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
129631   }
129632   p->nLeafAdd++;
129633   return rc;
129634 }
129635
129636 /*
129637 ** Release all memory held by the SegmentWriter object passed as the
129638 ** first argument.
129639 */
129640 static void fts3SegWriterFree(SegmentWriter *pWriter){
129641   if( pWriter ){
129642     sqlite3_free(pWriter->aData);
129643     sqlite3_free(pWriter->zMalloc);
129644     fts3NodeFree(pWriter->pTree);
129645     sqlite3_free(pWriter);
129646   }
129647 }
129648
129649 /*
129650 ** The first value in the apVal[] array is assumed to contain an integer.
129651 ** This function tests if there exist any documents with docid values that
129652 ** are different from that integer. i.e. if deleting the document with docid
129653 ** pRowid would mean the FTS3 table were empty.
129654 **
129655 ** If successful, *pisEmpty is set to true if the table is empty except for
129656 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
129657 ** error occurs, an SQLite error code is returned.
129658 */
129659 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
129660   sqlite3_stmt *pStmt;
129661   int rc;
129662   if( p->zContentTbl ){
129663     /* If using the content=xxx option, assume the table is never empty */
129664     *pisEmpty = 0;
129665     rc = SQLITE_OK;
129666   }else{
129667     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
129668     if( rc==SQLITE_OK ){
129669       if( SQLITE_ROW==sqlite3_step(pStmt) ){
129670         *pisEmpty = sqlite3_column_int(pStmt, 0);
129671       }
129672       rc = sqlite3_reset(pStmt);
129673     }
129674   }
129675   return rc;
129676 }
129677
129678 /*
129679 ** Set *pnMax to the largest segment level in the database for the index
129680 ** iIndex.
129681 **
129682 ** Segment levels are stored in the 'level' column of the %_segdir table.
129683 **
129684 ** Return SQLITE_OK if successful, or an SQLite error code if not.
129685 */
129686 static int fts3SegmentMaxLevel(
129687   Fts3Table *p,
129688   int iLangid,
129689   int iIndex,
129690   sqlite3_int64 *pnMax
129691 ){
129692   sqlite3_stmt *pStmt;
129693   int rc;
129694   assert( iIndex>=0 && iIndex<p->nIndex );
129695
129696   /* Set pStmt to the compiled version of:
129697   **
129698   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
129699   **
129700   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
129701   */
129702   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
129703   if( rc!=SQLITE_OK ) return rc;
129704   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
129705   sqlite3_bind_int64(pStmt, 2,
129706       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
129707   );
129708   if( SQLITE_ROW==sqlite3_step(pStmt) ){
129709     *pnMax = sqlite3_column_int64(pStmt, 0);
129710   }
129711   return sqlite3_reset(pStmt);
129712 }
129713
129714 /*
129715 ** Delete all entries in the %_segments table associated with the segment
129716 ** opened with seg-reader pSeg. This function does not affect the contents
129717 ** of the %_segdir table.
129718 */
129719 static int fts3DeleteSegment(
129720   Fts3Table *p,                   /* FTS table handle */
129721   Fts3SegReader *pSeg             /* Segment to delete */
129722 ){
129723   int rc = SQLITE_OK;             /* Return code */
129724   if( pSeg->iStartBlock ){
129725     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
129726     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
129727     if( rc==SQLITE_OK ){
129728       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
129729       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
129730       sqlite3_step(pDelete);
129731       rc = sqlite3_reset(pDelete);
129732     }
129733   }
129734   return rc;
129735 }
129736
129737 /*
129738 ** This function is used after merging multiple segments into a single large
129739 ** segment to delete the old, now redundant, segment b-trees. Specifically,
129740 ** it:
129741 **
129742 **   1) Deletes all %_segments entries for the segments associated with
129743 **      each of the SegReader objects in the array passed as the third
129744 **      argument, and
129745 **
129746 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
129747 **      entries regardless of level if (iLevel<0).
129748 **
129749 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
129750 */
129751 static int fts3DeleteSegdir(
129752   Fts3Table *p,                   /* Virtual table handle */
129753   int iLangid,                    /* Language id */
129754   int iIndex,                     /* Index for p->aIndex */
129755   int iLevel,                     /* Level of %_segdir entries to delete */
129756   Fts3SegReader **apSegment,      /* Array of SegReader objects */
129757   int nReader                     /* Size of array apSegment */
129758 ){
129759   int rc = SQLITE_OK;             /* Return Code */
129760   int i;                          /* Iterator variable */
129761   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
129762
129763   for(i=0; rc==SQLITE_OK && i<nReader; i++){
129764     rc = fts3DeleteSegment(p, apSegment[i]);
129765   }
129766   if( rc!=SQLITE_OK ){
129767     return rc;
129768   }
129769
129770   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
129771   if( iLevel==FTS3_SEGCURSOR_ALL ){
129772     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
129773     if( rc==SQLITE_OK ){
129774       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
129775       sqlite3_bind_int64(pDelete, 2,
129776           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
129777       );
129778     }
129779   }else{
129780     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
129781     if( rc==SQLITE_OK ){
129782       sqlite3_bind_int64(
129783           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
129784       );
129785     }
129786   }
129787
129788   if( rc==SQLITE_OK ){
129789     sqlite3_step(pDelete);
129790     rc = sqlite3_reset(pDelete);
129791   }
129792
129793   return rc;
129794 }
129795
129796 /*
129797 ** When this function is called, buffer *ppList (size *pnList bytes) contains
129798 ** a position list that may (or may not) feature multiple columns. This
129799 ** function adjusts the pointer *ppList and the length *pnList so that they
129800 ** identify the subset of the position list that corresponds to column iCol.
129801 **
129802 ** If there are no entries in the input position list for column iCol, then
129803 ** *pnList is set to zero before returning.
129804 */
129805 static void fts3ColumnFilter(
129806   int iCol,                       /* Column to filter on */
129807   char **ppList,                  /* IN/OUT: Pointer to position list */
129808   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
129809 ){
129810   char *pList = *ppList;
129811   int nList = *pnList;
129812   char *pEnd = &pList[nList];
129813   int iCurrent = 0;
129814   char *p = pList;
129815
129816   assert( iCol>=0 );
129817   while( 1 ){
129818     char c = 0;
129819     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
129820
129821     if( iCol==iCurrent ){
129822       nList = (int)(p - pList);
129823       break;
129824     }
129825
129826     nList -= (int)(p - pList);
129827     pList = p;
129828     if( nList==0 ){
129829       break;
129830     }
129831     p = &pList[1];
129832     p += sqlite3Fts3GetVarint32(p, &iCurrent);
129833   }
129834
129835   *ppList = pList;
129836   *pnList = nList;
129837 }
129838
129839 /*
129840 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
129841 ** existing data). Grow the buffer if required.
129842 **
129843 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
129844 ** trying to resize the buffer, return SQLITE_NOMEM.
129845 */
129846 static int fts3MsrBufferData(
129847   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
129848   char *pList,
129849   int nList
129850 ){
129851   if( nList>pMsr->nBuffer ){
129852     char *pNew;
129853     pMsr->nBuffer = nList*2;
129854     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
129855     if( !pNew ) return SQLITE_NOMEM;
129856     pMsr->aBuffer = pNew;
129857   }
129858
129859   memcpy(pMsr->aBuffer, pList, nList);
129860   return SQLITE_OK;
129861 }
129862
129863 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
129864   Fts3Table *p,                   /* Virtual table handle */
129865   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
129866   sqlite3_int64 *piDocid,         /* OUT: Docid value */
129867   char **paPoslist,               /* OUT: Pointer to position list */
129868   int *pnPoslist                  /* OUT: Size of position list in bytes */
129869 ){
129870   int nMerge = pMsr->nAdvance;
129871   Fts3SegReader **apSegment = pMsr->apSegment;
129872   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
129873     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
129874   );
129875
129876   if( nMerge==0 ){
129877     *paPoslist = 0;
129878     return SQLITE_OK;
129879   }
129880
129881   while( 1 ){
129882     Fts3SegReader *pSeg;
129883     pSeg = pMsr->apSegment[0];
129884
129885     if( pSeg->pOffsetList==0 ){
129886       *paPoslist = 0;
129887       break;
129888     }else{
129889       int rc;
129890       char *pList;
129891       int nList;
129892       int j;
129893       sqlite3_int64 iDocid = apSegment[0]->iDocid;
129894
129895       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
129896       j = 1;
129897       while( rc==SQLITE_OK
129898         && j<nMerge
129899         && apSegment[j]->pOffsetList
129900         && apSegment[j]->iDocid==iDocid
129901       ){
129902         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
129903         j++;
129904       }
129905       if( rc!=SQLITE_OK ) return rc;
129906       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
129907
129908       if( pMsr->iColFilter>=0 ){
129909         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
129910       }
129911
129912       if( nList>0 ){
129913         if( fts3SegReaderIsPending(apSegment[0]) ){
129914           rc = fts3MsrBufferData(pMsr, pList, nList+1);
129915           if( rc!=SQLITE_OK ) return rc;
129916           *paPoslist = pMsr->aBuffer;
129917           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
129918         }else{
129919           *paPoslist = pList;
129920         }
129921         *piDocid = iDocid;
129922         *pnPoslist = nList;
129923         break;
129924       }
129925     }
129926   }
129927
129928   return SQLITE_OK;
129929 }
129930
129931 static int fts3SegReaderStart(
129932   Fts3Table *p,                   /* Virtual table handle */
129933   Fts3MultiSegReader *pCsr,       /* Cursor object */
129934   const char *zTerm,              /* Term searched for (or NULL) */
129935   int nTerm                       /* Length of zTerm in bytes */
129936 ){
129937   int i;
129938   int nSeg = pCsr->nSegment;
129939
129940   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
129941   ** for, then advance each segment iterator until it points to a term of
129942   ** equal or greater value than the specified term. This prevents many
129943   ** unnecessary merge/sort operations for the case where single segment
129944   ** b-tree leaf nodes contain more than one term.
129945   */
129946   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
129947     int res = 0;
129948     Fts3SegReader *pSeg = pCsr->apSegment[i];
129949     do {
129950       int rc = fts3SegReaderNext(p, pSeg, 0);
129951       if( rc!=SQLITE_OK ) return rc;
129952     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
129953
129954     if( pSeg->bLookup && res!=0 ){
129955       fts3SegReaderSetEof(pSeg);
129956     }
129957   }
129958   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
129959
129960   return SQLITE_OK;
129961 }
129962
129963 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
129964   Fts3Table *p,                   /* Virtual table handle */
129965   Fts3MultiSegReader *pCsr,       /* Cursor object */
129966   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
129967 ){
129968   pCsr->pFilter = pFilter;
129969   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
129970 }
129971
129972 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
129973   Fts3Table *p,                   /* Virtual table handle */
129974   Fts3MultiSegReader *pCsr,       /* Cursor object */
129975   int iCol,                       /* Column to match on. */
129976   const char *zTerm,              /* Term to iterate through a doclist for */
129977   int nTerm                       /* Number of bytes in zTerm */
129978 ){
129979   int i;
129980   int rc;
129981   int nSegment = pCsr->nSegment;
129982   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
129983     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
129984   );
129985
129986   assert( pCsr->pFilter==0 );
129987   assert( zTerm && nTerm>0 );
129988
129989   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
129990   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
129991   if( rc!=SQLITE_OK ) return rc;
129992
129993   /* Determine how many of the segments actually point to zTerm/nTerm. */
129994   for(i=0; i<nSegment; i++){
129995     Fts3SegReader *pSeg = pCsr->apSegment[i];
129996     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
129997       break;
129998     }
129999   }
130000   pCsr->nAdvance = i;
130001
130002   /* Advance each of the segments to point to the first docid. */
130003   for(i=0; i<pCsr->nAdvance; i++){
130004     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
130005     if( rc!=SQLITE_OK ) return rc;
130006   }
130007   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
130008
130009   assert( iCol<0 || iCol<p->nColumn );
130010   pCsr->iColFilter = iCol;
130011
130012   return SQLITE_OK;
130013 }
130014
130015 /*
130016 ** This function is called on a MultiSegReader that has been started using
130017 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
130018 ** have been made. Calling this function puts the MultiSegReader in such
130019 ** a state that if the next two calls are:
130020 **
130021 **   sqlite3Fts3SegReaderStart()
130022 **   sqlite3Fts3SegReaderStep()
130023 **
130024 ** then the entire doclist for the term is available in
130025 ** MultiSegReader.aDoclist/nDoclist.
130026 */
130027 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
130028   int i;                          /* Used to iterate through segment-readers */
130029
130030   assert( pCsr->zTerm==0 );
130031   assert( pCsr->nTerm==0 );
130032   assert( pCsr->aDoclist==0 );
130033   assert( pCsr->nDoclist==0 );
130034
130035   pCsr->nAdvance = 0;
130036   pCsr->bRestart = 1;
130037   for(i=0; i<pCsr->nSegment; i++){
130038     pCsr->apSegment[i]->pOffsetList = 0;
130039     pCsr->apSegment[i]->nOffsetList = 0;
130040     pCsr->apSegment[i]->iDocid = 0;
130041   }
130042
130043   return SQLITE_OK;
130044 }
130045
130046
130047 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
130048   Fts3Table *p,                   /* Virtual table handle */
130049   Fts3MultiSegReader *pCsr        /* Cursor object */
130050 ){
130051   int rc = SQLITE_OK;
130052
130053   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
130054   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
130055   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
130056   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
130057   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
130058   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
130059
130060   Fts3SegReader **apSegment = pCsr->apSegment;
130061   int nSegment = pCsr->nSegment;
130062   Fts3SegFilter *pFilter = pCsr->pFilter;
130063   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
130064     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
130065   );
130066
130067   if( pCsr->nSegment==0 ) return SQLITE_OK;
130068
130069   do {
130070     int nMerge;
130071     int i;
130072
130073     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
130074     ** forward. Then sort the list in order of current term again.
130075     */
130076     for(i=0; i<pCsr->nAdvance; i++){
130077       Fts3SegReader *pSeg = apSegment[i];
130078       if( pSeg->bLookup ){
130079         fts3SegReaderSetEof(pSeg);
130080       }else{
130081         rc = fts3SegReaderNext(p, pSeg, 0);
130082       }
130083       if( rc!=SQLITE_OK ) return rc;
130084     }
130085     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
130086     pCsr->nAdvance = 0;
130087
130088     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
130089     assert( rc==SQLITE_OK );
130090     if( apSegment[0]->aNode==0 ) break;
130091
130092     pCsr->nTerm = apSegment[0]->nTerm;
130093     pCsr->zTerm = apSegment[0]->zTerm;
130094
130095     /* If this is a prefix-search, and if the term that apSegment[0] points
130096     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
130097     ** required callbacks have been made. In this case exit early.
130098     **
130099     ** Similarly, if this is a search for an exact match, and the first term
130100     ** of segment apSegment[0] is not a match, exit early.
130101     */
130102     if( pFilter->zTerm && !isScan ){
130103       if( pCsr->nTerm<pFilter->nTerm
130104        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
130105        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
130106       ){
130107         break;
130108       }
130109     }
130110
130111     nMerge = 1;
130112     while( nMerge<nSegment
130113         && apSegment[nMerge]->aNode
130114         && apSegment[nMerge]->nTerm==pCsr->nTerm
130115         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
130116     ){
130117       nMerge++;
130118     }
130119
130120     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
130121     if( nMerge==1
130122      && !isIgnoreEmpty
130123      && !isFirst
130124      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
130125     ){
130126       pCsr->nDoclist = apSegment[0]->nDoclist;
130127       if( fts3SegReaderIsPending(apSegment[0]) ){
130128         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
130129         pCsr->aDoclist = pCsr->aBuffer;
130130       }else{
130131         pCsr->aDoclist = apSegment[0]->aDoclist;
130132       }
130133       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
130134     }else{
130135       int nDoclist = 0;           /* Size of doclist */
130136       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
130137
130138       /* The current term of the first nMerge entries in the array
130139       ** of Fts3SegReader objects is the same. The doclists must be merged
130140       ** and a single term returned with the merged doclist.
130141       */
130142       for(i=0; i<nMerge; i++){
130143         fts3SegReaderFirstDocid(p, apSegment[i]);
130144       }
130145       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
130146       while( apSegment[0]->pOffsetList ){
130147         int j;                    /* Number of segments that share a docid */
130148         char *pList;
130149         int nList;
130150         int nByte;
130151         sqlite3_int64 iDocid = apSegment[0]->iDocid;
130152         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
130153         j = 1;
130154         while( j<nMerge
130155             && apSegment[j]->pOffsetList
130156             && apSegment[j]->iDocid==iDocid
130157         ){
130158           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
130159           j++;
130160         }
130161
130162         if( isColFilter ){
130163           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
130164         }
130165
130166         if( !isIgnoreEmpty || nList>0 ){
130167
130168           /* Calculate the 'docid' delta value to write into the merged
130169           ** doclist. */
130170           sqlite3_int64 iDelta;
130171           if( p->bDescIdx && nDoclist>0 ){
130172             iDelta = iPrev - iDocid;
130173           }else{
130174             iDelta = iDocid - iPrev;
130175           }
130176           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
130177           assert( nDoclist>0 || iDelta==iDocid );
130178
130179           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
130180           if( nDoclist+nByte>pCsr->nBuffer ){
130181             char *aNew;
130182             pCsr->nBuffer = (nDoclist+nByte)*2;
130183             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
130184             if( !aNew ){
130185               return SQLITE_NOMEM;
130186             }
130187             pCsr->aBuffer = aNew;
130188           }
130189
130190           if( isFirst ){
130191             char *a = &pCsr->aBuffer[nDoclist];
130192             int nWrite;
130193
130194             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
130195             if( nWrite ){
130196               iPrev = iDocid;
130197               nDoclist += nWrite;
130198             }
130199           }else{
130200             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
130201             iPrev = iDocid;
130202             if( isRequirePos ){
130203               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
130204               nDoclist += nList;
130205               pCsr->aBuffer[nDoclist++] = '\0';
130206             }
130207           }
130208         }
130209
130210         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
130211       }
130212       if( nDoclist>0 ){
130213         pCsr->aDoclist = pCsr->aBuffer;
130214         pCsr->nDoclist = nDoclist;
130215         rc = SQLITE_ROW;
130216       }
130217     }
130218     pCsr->nAdvance = nMerge;
130219   }while( rc==SQLITE_OK );
130220
130221   return rc;
130222 }
130223
130224
130225 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
130226   Fts3MultiSegReader *pCsr       /* Cursor object */
130227 ){
130228   if( pCsr ){
130229     int i;
130230     for(i=0; i<pCsr->nSegment; i++){
130231       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
130232     }
130233     sqlite3_free(pCsr->apSegment);
130234     sqlite3_free(pCsr->aBuffer);
130235
130236     pCsr->nSegment = 0;
130237     pCsr->apSegment = 0;
130238     pCsr->aBuffer = 0;
130239   }
130240 }
130241
130242 /*
130243 ** Merge all level iLevel segments in the database into a single
130244 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
130245 ** single segment with a level equal to the numerically largest level
130246 ** currently present in the database.
130247 **
130248 ** If this function is called with iLevel<0, but there is only one
130249 ** segment in the database, SQLITE_DONE is returned immediately.
130250 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
130251 ** an SQLite error code is returned.
130252 */
130253 static int fts3SegmentMerge(
130254   Fts3Table *p,
130255   int iLangid,                    /* Language id to merge */
130256   int iIndex,                     /* Index in p->aIndex[] to merge */
130257   int iLevel                      /* Level to merge */
130258 ){
130259   int rc;                         /* Return code */
130260   int iIdx = 0;                   /* Index of new segment */
130261   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
130262   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
130263   Fts3SegFilter filter;           /* Segment term filter condition */
130264   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
130265   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
130266
130267   assert( iLevel==FTS3_SEGCURSOR_ALL
130268        || iLevel==FTS3_SEGCURSOR_PENDING
130269        || iLevel>=0
130270   );
130271   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
130272   assert( iIndex>=0 && iIndex<p->nIndex );
130273
130274   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
130275   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
130276
130277   if( iLevel==FTS3_SEGCURSOR_ALL ){
130278     /* This call is to merge all segments in the database to a single
130279     ** segment. The level of the new segment is equal to the numerically
130280     ** greatest segment level currently present in the database for this
130281     ** index. The idx of the new segment is always 0.  */
130282     if( csr.nSegment==1 ){
130283       rc = SQLITE_DONE;
130284       goto finished;
130285     }
130286     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
130287     bIgnoreEmpty = 1;
130288
130289   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
130290     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
130291     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
130292   }else{
130293     /* This call is to merge all segments at level iLevel. find the next
130294     ** available segment index at level iLevel+1. The call to
130295     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
130296     ** a single iLevel+2 segment if necessary.  */
130297     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
130298     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
130299   }
130300   if( rc!=SQLITE_OK ) goto finished;
130301   assert( csr.nSegment>0 );
130302   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
130303   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
130304
130305   memset(&filter, 0, sizeof(Fts3SegFilter));
130306   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
130307   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
130308
130309   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
130310   while( SQLITE_OK==rc ){
130311     rc = sqlite3Fts3SegReaderStep(p, &csr);
130312     if( rc!=SQLITE_ROW ) break;
130313     rc = fts3SegWriterAdd(p, &pWriter, 1,
130314         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
130315   }
130316   if( rc!=SQLITE_OK ) goto finished;
130317   assert( pWriter );
130318
130319   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
130320     rc = fts3DeleteSegdir(
130321         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
130322     );
130323     if( rc!=SQLITE_OK ) goto finished;
130324   }
130325   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
130326
130327  finished:
130328   fts3SegWriterFree(pWriter);
130329   sqlite3Fts3SegReaderFinish(&csr);
130330   return rc;
130331 }
130332
130333
130334 /*
130335 ** Flush the contents of pendingTerms to level 0 segments.
130336 */
130337 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
130338   int rc = SQLITE_OK;
130339   int i;
130340
130341   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
130342     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
130343     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
130344   }
130345   sqlite3Fts3PendingTermsClear(p);
130346
130347   /* Determine the auto-incr-merge setting if unknown.  If enabled,
130348   ** estimate the number of leaf blocks of content to be written
130349   */
130350   if( rc==SQLITE_OK && p->bHasStat
130351    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
130352   ){
130353     sqlite3_stmt *pStmt = 0;
130354     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
130355     if( rc==SQLITE_OK ){
130356       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
130357       rc = sqlite3_step(pStmt);
130358       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
130359       rc = sqlite3_reset(pStmt);
130360     }
130361   }
130362   return rc;
130363 }
130364
130365 /*
130366 ** Encode N integers as varints into a blob.
130367 */
130368 static void fts3EncodeIntArray(
130369   int N,             /* The number of integers to encode */
130370   u32 *a,            /* The integer values */
130371   char *zBuf,        /* Write the BLOB here */
130372   int *pNBuf         /* Write number of bytes if zBuf[] used here */
130373 ){
130374   int i, j;
130375   for(i=j=0; i<N; i++){
130376     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
130377   }
130378   *pNBuf = j;
130379 }
130380
130381 /*
130382 ** Decode a blob of varints into N integers
130383 */
130384 static void fts3DecodeIntArray(
130385   int N,             /* The number of integers to decode */
130386   u32 *a,            /* Write the integer values */
130387   const char *zBuf,  /* The BLOB containing the varints */
130388   int nBuf           /* size of the BLOB */
130389 ){
130390   int i, j;
130391   UNUSED_PARAMETER(nBuf);
130392   for(i=j=0; i<N; i++){
130393     sqlite3_int64 x;
130394     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
130395     assert(j<=nBuf);
130396     a[i] = (u32)(x & 0xffffffff);
130397   }
130398 }
130399
130400 /*
130401 ** Insert the sizes (in tokens) for each column of the document
130402 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
130403 ** a blob of varints.
130404 */
130405 static void fts3InsertDocsize(
130406   int *pRC,                       /* Result code */
130407   Fts3Table *p,                   /* Table into which to insert */
130408   u32 *aSz                        /* Sizes of each column, in tokens */
130409 ){
130410   char *pBlob;             /* The BLOB encoding of the document size */
130411   int nBlob;               /* Number of bytes in the BLOB */
130412   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
130413   int rc;                  /* Result code from subfunctions */
130414
130415   if( *pRC ) return;
130416   pBlob = sqlite3_malloc( 10*p->nColumn );
130417   if( pBlob==0 ){
130418     *pRC = SQLITE_NOMEM;
130419     return;
130420   }
130421   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
130422   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
130423   if( rc ){
130424     sqlite3_free(pBlob);
130425     *pRC = rc;
130426     return;
130427   }
130428   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
130429   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
130430   sqlite3_step(pStmt);
130431   *pRC = sqlite3_reset(pStmt);
130432 }
130433
130434 /*
130435 ** Record 0 of the %_stat table contains a blob consisting of N varints,
130436 ** where N is the number of user defined columns in the fts3 table plus
130437 ** two. If nCol is the number of user defined columns, then values of the
130438 ** varints are set as follows:
130439 **
130440 **   Varint 0:       Total number of rows in the table.
130441 **
130442 **   Varint 1..nCol: For each column, the total number of tokens stored in
130443 **                   the column for all rows of the table.
130444 **
130445 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
130446 **                   columns of all rows of the table.
130447 **
130448 */
130449 static void fts3UpdateDocTotals(
130450   int *pRC,                       /* The result code */
130451   Fts3Table *p,                   /* Table being updated */
130452   u32 *aSzIns,                    /* Size increases */
130453   u32 *aSzDel,                    /* Size decreases */
130454   int nChng                       /* Change in the number of documents */
130455 ){
130456   char *pBlob;             /* Storage for BLOB written into %_stat */
130457   int nBlob;               /* Size of BLOB written into %_stat */
130458   u32 *a;                  /* Array of integers that becomes the BLOB */
130459   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
130460   int i;                   /* Loop counter */
130461   int rc;                  /* Result code from subfunctions */
130462
130463   const int nStat = p->nColumn+2;
130464
130465   if( *pRC ) return;
130466   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
130467   if( a==0 ){
130468     *pRC = SQLITE_NOMEM;
130469     return;
130470   }
130471   pBlob = (char*)&a[nStat];
130472   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
130473   if( rc ){
130474     sqlite3_free(a);
130475     *pRC = rc;
130476     return;
130477   }
130478   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
130479   if( sqlite3_step(pStmt)==SQLITE_ROW ){
130480     fts3DecodeIntArray(nStat, a,
130481          sqlite3_column_blob(pStmt, 0),
130482          sqlite3_column_bytes(pStmt, 0));
130483   }else{
130484     memset(a, 0, sizeof(u32)*(nStat) );
130485   }
130486   rc = sqlite3_reset(pStmt);
130487   if( rc!=SQLITE_OK ){
130488     sqlite3_free(a);
130489     *pRC = rc;
130490     return;
130491   }
130492   if( nChng<0 && a[0]<(u32)(-nChng) ){
130493     a[0] = 0;
130494   }else{
130495     a[0] += nChng;
130496   }
130497   for(i=0; i<p->nColumn+1; i++){
130498     u32 x = a[i+1];
130499     if( x+aSzIns[i] < aSzDel[i] ){
130500       x = 0;
130501     }else{
130502       x = x + aSzIns[i] - aSzDel[i];
130503     }
130504     a[i+1] = x;
130505   }
130506   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
130507   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
130508   if( rc ){
130509     sqlite3_free(a);
130510     *pRC = rc;
130511     return;
130512   }
130513   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
130514   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
130515   sqlite3_step(pStmt);
130516   *pRC = sqlite3_reset(pStmt);
130517   sqlite3_free(a);
130518 }
130519
130520 /*
130521 ** Merge the entire database so that there is one segment for each
130522 ** iIndex/iLangid combination.
130523 */
130524 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
130525   int bSeenDone = 0;
130526   int rc;
130527   sqlite3_stmt *pAllLangid = 0;
130528
130529   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
130530   if( rc==SQLITE_OK ){
130531     int rc2;
130532     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
130533     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
130534       int i;
130535       int iLangid = sqlite3_column_int(pAllLangid, 0);
130536       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
130537         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
130538         if( rc==SQLITE_DONE ){
130539           bSeenDone = 1;
130540           rc = SQLITE_OK;
130541         }
130542       }
130543     }
130544     rc2 = sqlite3_reset(pAllLangid);
130545     if( rc==SQLITE_OK ) rc = rc2;
130546   }
130547
130548   sqlite3Fts3SegmentsClose(p);
130549   sqlite3Fts3PendingTermsClear(p);
130550
130551   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
130552 }
130553
130554 /*
130555 ** This function is called when the user executes the following statement:
130556 **
130557 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
130558 **
130559 ** The entire FTS index is discarded and rebuilt. If the table is one
130560 ** created using the content=xxx option, then the new index is based on
130561 ** the current contents of the xxx table. Otherwise, it is rebuilt based
130562 ** on the contents of the %_content table.
130563 */
130564 static int fts3DoRebuild(Fts3Table *p){
130565   int rc;                         /* Return Code */
130566
130567   rc = fts3DeleteAll(p, 0);
130568   if( rc==SQLITE_OK ){
130569     u32 *aSz = 0;
130570     u32 *aSzIns = 0;
130571     u32 *aSzDel = 0;
130572     sqlite3_stmt *pStmt = 0;
130573     int nEntry = 0;
130574
130575     /* Compose and prepare an SQL statement to loop through the content table */
130576     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
130577     if( !zSql ){
130578       rc = SQLITE_NOMEM;
130579     }else{
130580       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
130581       sqlite3_free(zSql);
130582     }
130583
130584     if( rc==SQLITE_OK ){
130585       int nByte = sizeof(u32) * (p->nColumn+1)*3;
130586       aSz = (u32 *)sqlite3_malloc(nByte);
130587       if( aSz==0 ){
130588         rc = SQLITE_NOMEM;
130589       }else{
130590         memset(aSz, 0, nByte);
130591         aSzIns = &aSz[p->nColumn+1];
130592         aSzDel = &aSzIns[p->nColumn+1];
130593       }
130594     }
130595
130596     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
130597       int iCol;
130598       int iLangid = langidFromSelect(p, pStmt);
130599       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
130600       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
130601       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
130602         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
130603         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
130604         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
130605       }
130606       if( p->bHasDocsize ){
130607         fts3InsertDocsize(&rc, p, aSz);
130608       }
130609       if( rc!=SQLITE_OK ){
130610         sqlite3_finalize(pStmt);
130611         pStmt = 0;
130612       }else{
130613         nEntry++;
130614         for(iCol=0; iCol<=p->nColumn; iCol++){
130615           aSzIns[iCol] += aSz[iCol];
130616         }
130617       }
130618     }
130619     if( p->bFts4 ){
130620       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
130621     }
130622     sqlite3_free(aSz);
130623
130624     if( pStmt ){
130625       int rc2 = sqlite3_finalize(pStmt);
130626       if( rc==SQLITE_OK ){
130627         rc = rc2;
130628       }
130629     }
130630   }
130631
130632   return rc;
130633 }
130634
130635
130636 /*
130637 ** This function opens a cursor used to read the input data for an
130638 ** incremental merge operation. Specifically, it opens a cursor to scan
130639 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
130640 ** level iAbsLevel.
130641 */
130642 static int fts3IncrmergeCsr(
130643   Fts3Table *p,                   /* FTS3 table handle */
130644   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
130645   int nSeg,                       /* Number of segments to merge */
130646   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
130647 ){
130648   int rc;                         /* Return Code */
130649   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
130650   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
130651
130652   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
130653   memset(pCsr, 0, sizeof(*pCsr));
130654   nByte = sizeof(Fts3SegReader *) * nSeg;
130655   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
130656
130657   if( pCsr->apSegment==0 ){
130658     rc = SQLITE_NOMEM;
130659   }else{
130660     memset(pCsr->apSegment, 0, nByte);
130661     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
130662   }
130663   if( rc==SQLITE_OK ){
130664     int i;
130665     int rc2;
130666     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
130667     assert( pCsr->nSegment==0 );
130668     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
130669       rc = sqlite3Fts3SegReaderNew(i, 0,
130670           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
130671           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
130672           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
130673           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
130674           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
130675           &pCsr->apSegment[i]
130676       );
130677       pCsr->nSegment++;
130678     }
130679     rc2 = sqlite3_reset(pStmt);
130680     if( rc==SQLITE_OK ) rc = rc2;
130681   }
130682
130683   return rc;
130684 }
130685
130686 typedef struct IncrmergeWriter IncrmergeWriter;
130687 typedef struct NodeWriter NodeWriter;
130688 typedef struct Blob Blob;
130689 typedef struct NodeReader NodeReader;
130690
130691 /*
130692 ** An instance of the following structure is used as a dynamic buffer
130693 ** to build up nodes or other blobs of data in.
130694 **
130695 ** The function blobGrowBuffer() is used to extend the allocation.
130696 */
130697 struct Blob {
130698   char *a;                        /* Pointer to allocation */
130699   int n;                          /* Number of valid bytes of data in a[] */
130700   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
130701 };
130702
130703 /*
130704 ** This structure is used to build up buffers containing segment b-tree
130705 ** nodes (blocks).
130706 */
130707 struct NodeWriter {
130708   sqlite3_int64 iBlock;           /* Current block id */
130709   Blob key;                       /* Last key written to the current block */
130710   Blob block;                     /* Current block image */
130711 };
130712
130713 /*
130714 ** An object of this type contains the state required to create or append
130715 ** to an appendable b-tree segment.
130716 */
130717 struct IncrmergeWriter {
130718   int nLeafEst;                   /* Space allocated for leaf blocks */
130719   int nWork;                      /* Number of leaf pages flushed */
130720   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
130721   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
130722   sqlite3_int64 iStart;           /* Block number of first allocated block */
130723   sqlite3_int64 iEnd;             /* Block number of last allocated block */
130724   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
130725 };
130726
130727 /*
130728 ** An object of the following type is used to read data from a single
130729 ** FTS segment node. See the following functions:
130730 **
130731 **     nodeReaderInit()
130732 **     nodeReaderNext()
130733 **     nodeReaderRelease()
130734 */
130735 struct NodeReader {
130736   const char *aNode;
130737   int nNode;
130738   int iOff;                       /* Current offset within aNode[] */
130739
130740   /* Output variables. Containing the current node entry. */
130741   sqlite3_int64 iChild;           /* Pointer to child node */
130742   Blob term;                      /* Current term */
130743   const char *aDoclist;           /* Pointer to doclist */
130744   int nDoclist;                   /* Size of doclist in bytes */
130745 };
130746
130747 /*
130748 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130749 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
130750 ** bytes in size, extend (realloc) it to be so.
130751 **
130752 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
130753 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
130754 ** to reflect the new size of the pBlob->a[] buffer.
130755 */
130756 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
130757   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
130758     int nAlloc = nMin;
130759     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
130760     if( a ){
130761       pBlob->nAlloc = nAlloc;
130762       pBlob->a = a;
130763     }else{
130764       *pRc = SQLITE_NOMEM;
130765     }
130766   }
130767 }
130768
130769 /*
130770 ** Attempt to advance the node-reader object passed as the first argument to
130771 ** the next entry on the node.
130772 **
130773 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
130774 ** Otherwise return SQLITE_OK. If there is no next entry on the node
130775 ** (e.g. because the current entry is the last) set NodeReader->aNode to
130776 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
130777 ** variables for the new entry.
130778 */
130779 static int nodeReaderNext(NodeReader *p){
130780   int bFirst = (p->term.n==0);    /* True for first term on the node */
130781   int nPrefix = 0;                /* Bytes to copy from previous term */
130782   int nSuffix = 0;                /* Bytes to append to the prefix */
130783   int rc = SQLITE_OK;             /* Return code */
130784
130785   assert( p->aNode );
130786   if( p->iChild && bFirst==0 ) p->iChild++;
130787   if( p->iOff>=p->nNode ){
130788     /* EOF */
130789     p->aNode = 0;
130790   }else{
130791     if( bFirst==0 ){
130792       p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
130793     }
130794     p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
130795
130796     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
130797     if( rc==SQLITE_OK ){
130798       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
130799       p->term.n = nPrefix+nSuffix;
130800       p->iOff += nSuffix;
130801       if( p->iChild==0 ){
130802         p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
130803         p->aDoclist = &p->aNode[p->iOff];
130804         p->iOff += p->nDoclist;
130805       }
130806     }
130807   }
130808
130809   assert( p->iOff<=p->nNode );
130810
130811   return rc;
130812 }
130813
130814 /*
130815 ** Release all dynamic resources held by node-reader object *p.
130816 */
130817 static void nodeReaderRelease(NodeReader *p){
130818   sqlite3_free(p->term.a);
130819 }
130820
130821 /*
130822 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
130823 **
130824 ** If successful, SQLITE_OK is returned and the NodeReader object set to
130825 ** point to the first entry on the node (if any). Otherwise, an SQLite
130826 ** error code is returned.
130827 */
130828 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
130829   memset(p, 0, sizeof(NodeReader));
130830   p->aNode = aNode;
130831   p->nNode = nNode;
130832
130833   /* Figure out if this is a leaf or an internal node. */
130834   if( p->aNode[0] ){
130835     /* An internal node. */
130836     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
130837   }else{
130838     p->iOff = 1;
130839   }
130840
130841   return nodeReaderNext(p);
130842 }
130843
130844 /*
130845 ** This function is called while writing an FTS segment each time a leaf o
130846 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
130847 ** to be greater than the largest key on the node just written, but smaller
130848 ** than or equal to the first key that will be written to the next leaf
130849 ** node.
130850 **
130851 ** The block id of the leaf node just written to disk may be found in
130852 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
130853 */
130854 static int fts3IncrmergePush(
130855   Fts3Table *p,                   /* Fts3 table handle */
130856   IncrmergeWriter *pWriter,       /* Writer object */
130857   const char *zTerm,              /* Term to write to internal node */
130858   int nTerm                       /* Bytes at zTerm */
130859 ){
130860   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
130861   int iLayer;
130862
130863   assert( nTerm>0 );
130864   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
130865     sqlite3_int64 iNextPtr = 0;
130866     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
130867     int rc = SQLITE_OK;
130868     int nPrefix;
130869     int nSuffix;
130870     int nSpace;
130871
130872     /* Figure out how much space the key will consume if it is written to
130873     ** the current node of layer iLayer. Due to the prefix compression,
130874     ** the space required changes depending on which node the key is to
130875     ** be added to.  */
130876     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
130877     nSuffix = nTerm - nPrefix;
130878     nSpace  = sqlite3Fts3VarintLen(nPrefix);
130879     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
130880
130881     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
130882       /* If the current node of layer iLayer contains zero keys, or if adding
130883       ** the key to it will not cause it to grow to larger than nNodeSize
130884       ** bytes in size, write the key here.  */
130885
130886       Blob *pBlk = &pNode->block;
130887       if( pBlk->n==0 ){
130888         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
130889         if( rc==SQLITE_OK ){
130890           pBlk->a[0] = (char)iLayer;
130891           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
130892         }
130893       }
130894       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
130895       blobGrowBuffer(&pNode->key, nTerm, &rc);
130896
130897       if( rc==SQLITE_OK ){
130898         if( pNode->key.n ){
130899           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
130900         }
130901         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
130902         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
130903         pBlk->n += nSuffix;
130904
130905         memcpy(pNode->key.a, zTerm, nTerm);
130906         pNode->key.n = nTerm;
130907       }
130908     }else{
130909       /* Otherwise, flush the current node of layer iLayer to disk.
130910       ** Then allocate a new, empty sibling node. The key will be written
130911       ** into the parent of this node. */
130912       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
130913
130914       assert( pNode->block.nAlloc>=p->nNodeSize );
130915       pNode->block.a[0] = (char)iLayer;
130916       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
130917
130918       iNextPtr = pNode->iBlock;
130919       pNode->iBlock++;
130920       pNode->key.n = 0;
130921     }
130922
130923     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
130924     iPtr = iNextPtr;
130925   }
130926
130927   assert( 0 );
130928   return 0;
130929 }
130930
130931 /*
130932 ** Append a term and (optionally) doclist to the FTS segment node currently
130933 ** stored in blob *pNode. The node need not contain any terms, but the
130934 ** header must be written before this function is called.
130935 **
130936 ** A node header is a single 0x00 byte for a leaf node, or a height varint
130937 ** followed by the left-hand-child varint for an internal node.
130938 **
130939 ** The term to be appended is passed via arguments zTerm/nTerm. For a
130940 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
130941 ** node, both aDoclist and nDoclist must be passed 0.
130942 **
130943 ** If the size of the value in blob pPrev is zero, then this is the first
130944 ** term written to the node. Otherwise, pPrev contains a copy of the
130945 ** previous term. Before this function returns, it is updated to contain a
130946 ** copy of zTerm/nTerm.
130947 **
130948 ** It is assumed that the buffer associated with pNode is already large
130949 ** enough to accommodate the new entry. The buffer associated with pPrev
130950 ** is extended by this function if requrired.
130951 **
130952 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
130953 ** returned. Otherwise, SQLITE_OK.
130954 */
130955 static int fts3AppendToNode(
130956   Blob *pNode,                    /* Current node image to append to */
130957   Blob *pPrev,                    /* Buffer containing previous term written */
130958   const char *zTerm,              /* New term to write */
130959   int nTerm,                      /* Size of zTerm in bytes */
130960   const char *aDoclist,           /* Doclist (or NULL) to write */
130961   int nDoclist                    /* Size of aDoclist in bytes */
130962 ){
130963   int rc = SQLITE_OK;             /* Return code */
130964   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
130965   int nPrefix;                    /* Size of term prefix in bytes */
130966   int nSuffix;                    /* Size of term suffix in bytes */
130967
130968   /* Node must have already been started. There must be a doclist for a
130969   ** leaf node, and there must not be a doclist for an internal node.  */
130970   assert( pNode->n>0 );
130971   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
130972
130973   blobGrowBuffer(pPrev, nTerm, &rc);
130974   if( rc!=SQLITE_OK ) return rc;
130975
130976   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
130977   nSuffix = nTerm - nPrefix;
130978   memcpy(pPrev->a, zTerm, nTerm);
130979   pPrev->n = nTerm;
130980
130981   if( bFirst==0 ){
130982     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
130983   }
130984   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
130985   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
130986   pNode->n += nSuffix;
130987
130988   if( aDoclist ){
130989     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
130990     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
130991     pNode->n += nDoclist;
130992   }
130993
130994   assert( pNode->n<=pNode->nAlloc );
130995
130996   return SQLITE_OK;
130997 }
130998
130999 /*
131000 ** Append the current term and doclist pointed to by cursor pCsr to the
131001 ** appendable b-tree segment opened for writing by pWriter.
131002 **
131003 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
131004 */
131005 static int fts3IncrmergeAppend(
131006   Fts3Table *p,                   /* Fts3 table handle */
131007   IncrmergeWriter *pWriter,       /* Writer object */
131008   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
131009 ){
131010   const char *zTerm = pCsr->zTerm;
131011   int nTerm = pCsr->nTerm;
131012   const char *aDoclist = pCsr->aDoclist;
131013   int nDoclist = pCsr->nDoclist;
131014   int rc = SQLITE_OK;           /* Return code */
131015   int nSpace;                   /* Total space in bytes required on leaf */
131016   int nPrefix;                  /* Size of prefix shared with previous term */
131017   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
131018   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
131019
131020   pLeaf = &pWriter->aNodeWriter[0];
131021   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
131022   nSuffix = nTerm - nPrefix;
131023
131024   nSpace  = sqlite3Fts3VarintLen(nPrefix);
131025   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
131026   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
131027
131028   /* If the current block is not empty, and if adding this term/doclist
131029   ** to the current block would make it larger than Fts3Table.nNodeSize
131030   ** bytes, write this block out to the database. */
131031   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
131032     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
131033     pWriter->nWork++;
131034
131035     /* Add the current term to the parent node. The term added to the
131036     ** parent must:
131037     **
131038     **   a) be greater than the largest term on the leaf node just written
131039     **      to the database (still available in pLeaf->key), and
131040     **
131041     **   b) be less than or equal to the term about to be added to the new
131042     **      leaf node (zTerm/nTerm).
131043     **
131044     ** In other words, it must be the prefix of zTerm 1 byte longer than
131045     ** the common prefix (if any) of zTerm and pWriter->zTerm.
131046     */
131047     if( rc==SQLITE_OK ){
131048       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
131049     }
131050
131051     /* Advance to the next output block */
131052     pLeaf->iBlock++;
131053     pLeaf->key.n = 0;
131054     pLeaf->block.n = 0;
131055
131056     nSuffix = nTerm;
131057     nSpace  = 1;
131058     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
131059     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
131060   }
131061
131062   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
131063
131064   if( rc==SQLITE_OK ){
131065     if( pLeaf->block.n==0 ){
131066       pLeaf->block.n = 1;
131067       pLeaf->block.a[0] = '\0';
131068     }
131069     rc = fts3AppendToNode(
131070         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
131071     );
131072   }
131073
131074   return rc;
131075 }
131076
131077 /*
131078 ** This function is called to release all dynamic resources held by the
131079 ** merge-writer object pWriter, and if no error has occurred, to flush
131080 ** all outstanding node buffers held by pWriter to disk.
131081 **
131082 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
131083 ** is made to write any data to disk. Instead, this function serves only
131084 ** to release outstanding resources.
131085 **
131086 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
131087 ** flushing buffers to disk, *pRc is set to an SQLite error code before
131088 ** returning.
131089 */
131090 static void fts3IncrmergeRelease(
131091   Fts3Table *p,                   /* FTS3 table handle */
131092   IncrmergeWriter *pWriter,       /* Merge-writer object */
131093   int *pRc                        /* IN/OUT: Error code */
131094 ){
131095   int i;                          /* Used to iterate through non-root layers */
131096   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
131097   NodeWriter *pRoot;              /* NodeWriter for root node */
131098   int rc = *pRc;                  /* Error code */
131099
131100   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
131101   ** root node. If the segment fits entirely on a single leaf node, iRoot
131102   ** will be set to 0. If the root node is the parent of the leaves, iRoot
131103   ** will be 1. And so on.  */
131104   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
131105     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
131106     if( pNode->block.n>0 ) break;
131107     assert( *pRc || pNode->block.nAlloc==0 );
131108     assert( *pRc || pNode->key.nAlloc==0 );
131109     sqlite3_free(pNode->block.a);
131110     sqlite3_free(pNode->key.a);
131111   }
131112
131113   /* Empty output segment. This is a no-op. */
131114   if( iRoot<0 ) return;
131115
131116   /* The entire output segment fits on a single node. Normally, this means
131117   ** the node would be stored as a blob in the "root" column of the %_segdir
131118   ** table. However, this is not permitted in this case. The problem is that
131119   ** space has already been reserved in the %_segments table, and so the
131120   ** start_block and end_block fields of the %_segdir table must be populated.
131121   ** And, by design or by accident, released versions of FTS cannot handle
131122   ** segments that fit entirely on the root node with start_block!=0.
131123   **
131124   ** Instead, create a synthetic root node that contains nothing but a
131125   ** pointer to the single content node. So that the segment consists of a
131126   ** single leaf and a single interior (root) node.
131127   **
131128   ** Todo: Better might be to defer allocating space in the %_segments
131129   ** table until we are sure it is needed.
131130   */
131131   if( iRoot==0 ){
131132     Blob *pBlock = &pWriter->aNodeWriter[1].block;
131133     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
131134     if( rc==SQLITE_OK ){
131135       pBlock->a[0] = 0x01;
131136       pBlock->n = 1 + sqlite3Fts3PutVarint(
131137           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
131138       );
131139     }
131140     iRoot = 1;
131141   }
131142   pRoot = &pWriter->aNodeWriter[iRoot];
131143
131144   /* Flush all currently outstanding nodes to disk. */
131145   for(i=0; i<iRoot; i++){
131146     NodeWriter *pNode = &pWriter->aNodeWriter[i];
131147     if( pNode->block.n>0 && rc==SQLITE_OK ){
131148       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
131149     }
131150     sqlite3_free(pNode->block.a);
131151     sqlite3_free(pNode->key.a);
131152   }
131153
131154   /* Write the %_segdir record. */
131155   if( rc==SQLITE_OK ){
131156     rc = fts3WriteSegdir(p,
131157         pWriter->iAbsLevel+1,               /* level */
131158         pWriter->iIdx,                      /* idx */
131159         pWriter->iStart,                    /* start_block */
131160         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
131161         pWriter->iEnd,                      /* end_block */
131162         pRoot->block.a, pRoot->block.n      /* root */
131163     );
131164   }
131165   sqlite3_free(pRoot->block.a);
131166   sqlite3_free(pRoot->key.a);
131167
131168   *pRc = rc;
131169 }
131170
131171 /*
131172 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
131173 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
131174 ** the other, it is considered to be smaller than the other.
131175 **
131176 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
131177 ** if it is greater.
131178 */
131179 static int fts3TermCmp(
131180   const char *zLhs, int nLhs,     /* LHS of comparison */
131181   const char *zRhs, int nRhs      /* RHS of comparison */
131182 ){
131183   int nCmp = MIN(nLhs, nRhs);
131184   int res;
131185
131186   res = memcmp(zLhs, zRhs, nCmp);
131187   if( res==0 ) res = nLhs - nRhs;
131188
131189   return res;
131190 }
131191
131192
131193 /*
131194 ** Query to see if the entry in the %_segments table with blockid iEnd is
131195 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
131196 ** returning. Otherwise, set *pbRes to 0.
131197 **
131198 ** Or, if an error occurs while querying the database, return an SQLite
131199 ** error code. The final value of *pbRes is undefined in this case.
131200 **
131201 ** This is used to test if a segment is an "appendable" segment. If it
131202 ** is, then a NULL entry has been inserted into the %_segments table
131203 ** with blockid %_segdir.end_block.
131204 */
131205 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
131206   int bRes = 0;                   /* Result to set *pbRes to */
131207   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
131208   int rc;                         /* Return code */
131209
131210   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
131211   if( rc==SQLITE_OK ){
131212     sqlite3_bind_int64(pCheck, 1, iEnd);
131213     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
131214     rc = sqlite3_reset(pCheck);
131215   }
131216
131217   *pbRes = bRes;
131218   return rc;
131219 }
131220
131221 /*
131222 ** This function is called when initializing an incremental-merge operation.
131223 ** It checks if the existing segment with index value iIdx at absolute level
131224 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
131225 ** merge-writer object *pWriter is initialized to write to it.
131226 **
131227 ** An existing segment can be appended to by an incremental merge if:
131228 **
131229 **   * It was initially created as an appendable segment (with all required
131230 **     space pre-allocated), and
131231 **
131232 **   * The first key read from the input (arguments zKey and nKey) is
131233 **     greater than the largest key currently stored in the potential
131234 **     output segment.
131235 */
131236 static int fts3IncrmergeLoad(
131237   Fts3Table *p,                   /* Fts3 table handle */
131238   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
131239   int iIdx,                       /* Index of candidate output segment */
131240   const char *zKey,               /* First key to write */
131241   int nKey,                       /* Number of bytes in nKey */
131242   IncrmergeWriter *pWriter        /* Populate this object */
131243 ){
131244   int rc;                         /* Return code */
131245   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
131246
131247   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
131248   if( rc==SQLITE_OK ){
131249     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
131250     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
131251     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
131252     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
131253     int nRoot = 0;                /* Size of aRoot[] in bytes */
131254     int rc2;                      /* Return code from sqlite3_reset() */
131255     int bAppendable = 0;          /* Set to true if segment is appendable */
131256
131257     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
131258     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
131259     sqlite3_bind_int(pSelect, 2, iIdx);
131260     if( sqlite3_step(pSelect)==SQLITE_ROW ){
131261       iStart = sqlite3_column_int64(pSelect, 1);
131262       iLeafEnd = sqlite3_column_int64(pSelect, 2);
131263       iEnd = sqlite3_column_int64(pSelect, 3);
131264       nRoot = sqlite3_column_bytes(pSelect, 4);
131265       aRoot = sqlite3_column_blob(pSelect, 4);
131266     }else{
131267       return sqlite3_reset(pSelect);
131268     }
131269
131270     /* Check for the zero-length marker in the %_segments table */
131271     rc = fts3IsAppendable(p, iEnd, &bAppendable);
131272
131273     /* Check that zKey/nKey is larger than the largest key the candidate */
131274     if( rc==SQLITE_OK && bAppendable ){
131275       char *aLeaf = 0;
131276       int nLeaf = 0;
131277
131278       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
131279       if( rc==SQLITE_OK ){
131280         NodeReader reader;
131281         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
131282             rc==SQLITE_OK && reader.aNode;
131283             rc = nodeReaderNext(&reader)
131284         ){
131285           assert( reader.aNode );
131286         }
131287         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
131288           bAppendable = 0;
131289         }
131290         nodeReaderRelease(&reader);
131291       }
131292       sqlite3_free(aLeaf);
131293     }
131294
131295     if( rc==SQLITE_OK && bAppendable ){
131296       /* It is possible to append to this segment. Set up the IncrmergeWriter
131297       ** object to do so.  */
131298       int i;
131299       int nHeight = (int)aRoot[0];
131300       NodeWriter *pNode;
131301
131302       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
131303       pWriter->iStart = iStart;
131304       pWriter->iEnd = iEnd;
131305       pWriter->iAbsLevel = iAbsLevel;
131306       pWriter->iIdx = iIdx;
131307
131308       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
131309         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
131310       }
131311
131312       pNode = &pWriter->aNodeWriter[nHeight];
131313       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
131314       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
131315       if( rc==SQLITE_OK ){
131316         memcpy(pNode->block.a, aRoot, nRoot);
131317         pNode->block.n = nRoot;
131318       }
131319
131320       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
131321         NodeReader reader;
131322         pNode = &pWriter->aNodeWriter[i];
131323
131324         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
131325         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
131326         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
131327         if( rc==SQLITE_OK ){
131328           memcpy(pNode->key.a, reader.term.a, reader.term.n);
131329           pNode->key.n = reader.term.n;
131330           if( i>0 ){
131331             char *aBlock = 0;
131332             int nBlock = 0;
131333             pNode = &pWriter->aNodeWriter[i-1];
131334             pNode->iBlock = reader.iChild;
131335             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
131336             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
131337             if( rc==SQLITE_OK ){
131338               memcpy(pNode->block.a, aBlock, nBlock);
131339               pNode->block.n = nBlock;
131340             }
131341             sqlite3_free(aBlock);
131342           }
131343         }
131344         nodeReaderRelease(&reader);
131345       }
131346     }
131347
131348     rc2 = sqlite3_reset(pSelect);
131349     if( rc==SQLITE_OK ) rc = rc2;
131350   }
131351
131352   return rc;
131353 }
131354
131355 /*
131356 ** Determine the largest segment index value that exists within absolute
131357 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
131358 ** one before returning SQLITE_OK. Or, if there are no segments at all
131359 ** within level iAbsLevel, set *piIdx to zero.
131360 **
131361 ** If an error occurs, return an SQLite error code. The final value of
131362 ** *piIdx is undefined in this case.
131363 */
131364 static int fts3IncrmergeOutputIdx(
131365   Fts3Table *p,                   /* FTS Table handle */
131366   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
131367   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
131368 ){
131369   int rc;
131370   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
131371
131372   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
131373   if( rc==SQLITE_OK ){
131374     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
131375     sqlite3_step(pOutputIdx);
131376     *piIdx = sqlite3_column_int(pOutputIdx, 0);
131377     rc = sqlite3_reset(pOutputIdx);
131378   }
131379
131380   return rc;
131381 }
131382
131383 /*
131384 ** Allocate an appendable output segment on absolute level iAbsLevel+1
131385 ** with idx value iIdx.
131386 **
131387 ** In the %_segdir table, a segment is defined by the values in three
131388 ** columns:
131389 **
131390 **     start_block
131391 **     leaves_end_block
131392 **     end_block
131393 **
131394 ** When an appendable segment is allocated, it is estimated that the
131395 ** maximum number of leaf blocks that may be required is the sum of the
131396 ** number of leaf blocks consumed by the input segments, plus the number
131397 ** of input segments, multiplied by two. This value is stored in stack
131398 ** variable nLeafEst.
131399 **
131400 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
131401 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
131402 ** array of leaf nodes starts at the first block allocated. The array
131403 ** of interior nodes that are parents of the leaf nodes start at block
131404 ** (start_block + (1 + end_block - start_block) / 16). And so on.
131405 **
131406 ** In the actual code below, the value "16" is replaced with the
131407 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
131408 */
131409 static int fts3IncrmergeWriter(
131410   Fts3Table *p,                   /* Fts3 table handle */
131411   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
131412   int iIdx,                       /* Index of new output segment */
131413   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
131414   IncrmergeWriter *pWriter        /* Populate this object */
131415 ){
131416   int rc;                         /* Return Code */
131417   int i;                          /* Iterator variable */
131418   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
131419   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
131420   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
131421
131422   /* Calculate nLeafEst. */
131423   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
131424   if( rc==SQLITE_OK ){
131425     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
131426     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
131427     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
131428       nLeafEst = sqlite3_column_int(pLeafEst, 0);
131429     }
131430     rc = sqlite3_reset(pLeafEst);
131431   }
131432   if( rc!=SQLITE_OK ) return rc;
131433
131434   /* Calculate the first block to use in the output segment */
131435   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
131436   if( rc==SQLITE_OK ){
131437     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
131438       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
131439       pWriter->iEnd = pWriter->iStart - 1;
131440       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
131441     }
131442     rc = sqlite3_reset(pFirstBlock);
131443   }
131444   if( rc!=SQLITE_OK ) return rc;
131445
131446   /* Insert the marker in the %_segments table to make sure nobody tries
131447   ** to steal the space just allocated. This is also used to identify
131448   ** appendable segments.  */
131449   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
131450   if( rc!=SQLITE_OK ) return rc;
131451
131452   pWriter->iAbsLevel = iAbsLevel;
131453   pWriter->nLeafEst = nLeafEst;
131454   pWriter->iIdx = iIdx;
131455
131456   /* Set up the array of NodeWriter objects */
131457   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
131458     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
131459   }
131460   return SQLITE_OK;
131461 }
131462
131463 /*
131464 ** Remove an entry from the %_segdir table. This involves running the
131465 ** following two statements:
131466 **
131467 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
131468 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
131469 **
131470 ** The DELETE statement removes the specific %_segdir level. The UPDATE
131471 ** statement ensures that the remaining segments have contiguously allocated
131472 ** idx values.
131473 */
131474 static int fts3RemoveSegdirEntry(
131475   Fts3Table *p,                   /* FTS3 table handle */
131476   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
131477   int iIdx                        /* Index of %_segdir entry to delete */
131478 ){
131479   int rc;                         /* Return code */
131480   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
131481
131482   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
131483   if( rc==SQLITE_OK ){
131484     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
131485     sqlite3_bind_int(pDelete, 2, iIdx);
131486     sqlite3_step(pDelete);
131487     rc = sqlite3_reset(pDelete);
131488   }
131489
131490   return rc;
131491 }
131492
131493 /*
131494 ** One or more segments have just been removed from absolute level iAbsLevel.
131495 ** Update the 'idx' values of the remaining segments in the level so that
131496 ** the idx values are a contiguous sequence starting from 0.
131497 */
131498 static int fts3RepackSegdirLevel(
131499   Fts3Table *p,                   /* FTS3 table handle */
131500   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
131501 ){
131502   int rc;                         /* Return code */
131503   int *aIdx = 0;                  /* Array of remaining idx values */
131504   int nIdx = 0;                   /* Valid entries in aIdx[] */
131505   int nAlloc = 0;                 /* Allocated size of aIdx[] */
131506   int i;                          /* Iterator variable */
131507   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
131508   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
131509
131510   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
131511   if( rc==SQLITE_OK ){
131512     int rc2;
131513     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
131514     while( SQLITE_ROW==sqlite3_step(pSelect) ){
131515       if( nIdx>=nAlloc ){
131516         int *aNew;
131517         nAlloc += 16;
131518         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
131519         if( !aNew ){
131520           rc = SQLITE_NOMEM;
131521           break;
131522         }
131523         aIdx = aNew;
131524       }
131525       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
131526     }
131527     rc2 = sqlite3_reset(pSelect);
131528     if( rc==SQLITE_OK ) rc = rc2;
131529   }
131530
131531   if( rc==SQLITE_OK ){
131532     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
131533   }
131534   if( rc==SQLITE_OK ){
131535     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
131536   }
131537
131538   assert( p->bIgnoreSavepoint==0 );
131539   p->bIgnoreSavepoint = 1;
131540   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
131541     if( aIdx[i]!=i ){
131542       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
131543       sqlite3_bind_int(pUpdate, 1, i);
131544       sqlite3_step(pUpdate);
131545       rc = sqlite3_reset(pUpdate);
131546     }
131547   }
131548   p->bIgnoreSavepoint = 0;
131549
131550   sqlite3_free(aIdx);
131551   return rc;
131552 }
131553
131554 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
131555   pNode->a[0] = (char)iHeight;
131556   if( iChild ){
131557     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
131558     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
131559   }else{
131560     assert( pNode->nAlloc>=1 );
131561     pNode->n = 1;
131562   }
131563 }
131564
131565 /*
131566 ** The first two arguments are a pointer to and the size of a segment b-tree
131567 ** node. The node may be a leaf or an internal node.
131568 **
131569 ** This function creates a new node image in blob object *pNew by copying
131570 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
131571 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
131572 */
131573 static int fts3TruncateNode(
131574   const char *aNode,              /* Current node image */
131575   int nNode,                      /* Size of aNode in bytes */
131576   Blob *pNew,                     /* OUT: Write new node image here */
131577   const char *zTerm,              /* Omit all terms smaller than this */
131578   int nTerm,                      /* Size of zTerm in bytes */
131579   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
131580 ){
131581   NodeReader reader;              /* Reader object */
131582   Blob prev = {0, 0, 0};          /* Previous term written to new node */
131583   int rc = SQLITE_OK;             /* Return code */
131584   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
131585
131586   /* Allocate required output space */
131587   blobGrowBuffer(pNew, nNode, &rc);
131588   if( rc!=SQLITE_OK ) return rc;
131589   pNew->n = 0;
131590
131591   /* Populate new node buffer */
131592   for(rc = nodeReaderInit(&reader, aNode, nNode);
131593       rc==SQLITE_OK && reader.aNode;
131594       rc = nodeReaderNext(&reader)
131595   ){
131596     if( pNew->n==0 ){
131597       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
131598       if( res<0 || (bLeaf==0 && res==0) ) continue;
131599       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
131600       *piBlock = reader.iChild;
131601     }
131602     rc = fts3AppendToNode(
131603         pNew, &prev, reader.term.a, reader.term.n,
131604         reader.aDoclist, reader.nDoclist
131605     );
131606     if( rc!=SQLITE_OK ) break;
131607   }
131608   if( pNew->n==0 ){
131609     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
131610     *piBlock = reader.iChild;
131611   }
131612   assert( pNew->n<=pNew->nAlloc );
131613
131614   nodeReaderRelease(&reader);
131615   sqlite3_free(prev.a);
131616   return rc;
131617 }
131618
131619 /*
131620 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
131621 ** level iAbsLevel. This may involve deleting entries from the %_segments
131622 ** table, and modifying existing entries in both the %_segments and %_segdir
131623 ** tables.
131624 **
131625 ** SQLITE_OK is returned if the segment is updated successfully. Or an
131626 ** SQLite error code otherwise.
131627 */
131628 static int fts3TruncateSegment(
131629   Fts3Table *p,                   /* FTS3 table handle */
131630   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
131631   int iIdx,                       /* Index within level of segment to modify */
131632   const char *zTerm,              /* Remove terms smaller than this */
131633   int nTerm                      /* Number of bytes in buffer zTerm */
131634 ){
131635   int rc = SQLITE_OK;             /* Return code */
131636   Blob root = {0,0,0};            /* New root page image */
131637   Blob block = {0,0,0};           /* Buffer used for any other block */
131638   sqlite3_int64 iBlock = 0;       /* Block id */
131639   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
131640   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
131641   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
131642
131643   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
131644   if( rc==SQLITE_OK ){
131645     int rc2;                      /* sqlite3_reset() return code */
131646     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
131647     sqlite3_bind_int(pFetch, 2, iIdx);
131648     if( SQLITE_ROW==sqlite3_step(pFetch) ){
131649       const char *aRoot = sqlite3_column_blob(pFetch, 4);
131650       int nRoot = sqlite3_column_bytes(pFetch, 4);
131651       iOldStart = sqlite3_column_int64(pFetch, 1);
131652       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
131653     }
131654     rc2 = sqlite3_reset(pFetch);
131655     if( rc==SQLITE_OK ) rc = rc2;
131656   }
131657
131658   while( rc==SQLITE_OK && iBlock ){
131659     char *aBlock = 0;
131660     int nBlock = 0;
131661     iNewStart = iBlock;
131662
131663     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
131664     if( rc==SQLITE_OK ){
131665       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
131666     }
131667     if( rc==SQLITE_OK ){
131668       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
131669     }
131670     sqlite3_free(aBlock);
131671   }
131672
131673   /* Variable iNewStart now contains the first valid leaf node. */
131674   if( rc==SQLITE_OK && iNewStart ){
131675     sqlite3_stmt *pDel = 0;
131676     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
131677     if( rc==SQLITE_OK ){
131678       sqlite3_bind_int64(pDel, 1, iOldStart);
131679       sqlite3_bind_int64(pDel, 2, iNewStart-1);
131680       sqlite3_step(pDel);
131681       rc = sqlite3_reset(pDel);
131682     }
131683   }
131684
131685   if( rc==SQLITE_OK ){
131686     sqlite3_stmt *pChomp = 0;
131687     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
131688     if( rc==SQLITE_OK ){
131689       sqlite3_bind_int64(pChomp, 1, iNewStart);
131690       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
131691       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
131692       sqlite3_bind_int(pChomp, 4, iIdx);
131693       sqlite3_step(pChomp);
131694       rc = sqlite3_reset(pChomp);
131695     }
131696   }
131697
131698   sqlite3_free(root.a);
131699   sqlite3_free(block.a);
131700   return rc;
131701 }
131702
131703 /*
131704 ** This function is called after an incrmental-merge operation has run to
131705 ** merge (or partially merge) two or more segments from absolute level
131706 ** iAbsLevel.
131707 **
131708 ** Each input segment is either removed from the db completely (if all of
131709 ** its data was copied to the output segment by the incrmerge operation)
131710 ** or modified in place so that it no longer contains those entries that
131711 ** have been duplicated in the output segment.
131712 */
131713 static int fts3IncrmergeChomp(
131714   Fts3Table *p,                   /* FTS table handle */
131715   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
131716   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
131717   int *pnRem                      /* Number of segments not deleted */
131718 ){
131719   int i;
131720   int nRem = 0;
131721   int rc = SQLITE_OK;
131722
131723   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
131724     Fts3SegReader *pSeg = 0;
131725     int j;
131726
131727     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
131728     ** somewhere in the pCsr->apSegment[] array.  */
131729     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
131730       pSeg = pCsr->apSegment[j];
131731       if( pSeg->iIdx==i ) break;
131732     }
131733     assert( j<pCsr->nSegment && pSeg->iIdx==i );
131734
131735     if( pSeg->aNode==0 ){
131736       /* Seg-reader is at EOF. Remove the entire input segment. */
131737       rc = fts3DeleteSegment(p, pSeg);
131738       if( rc==SQLITE_OK ){
131739         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
131740       }
131741       *pnRem = 0;
131742     }else{
131743       /* The incremental merge did not copy all the data from this
131744       ** segment to the upper level. The segment is modified in place
131745       ** so that it contains no keys smaller than zTerm/nTerm. */
131746       const char *zTerm = pSeg->zTerm;
131747       int nTerm = pSeg->nTerm;
131748       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
131749       nRem++;
131750     }
131751   }
131752
131753   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
131754     rc = fts3RepackSegdirLevel(p, iAbsLevel);
131755   }
131756
131757   *pnRem = nRem;
131758   return rc;
131759 }
131760
131761 /*
131762 ** Store an incr-merge hint in the database.
131763 */
131764 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
131765   sqlite3_stmt *pReplace = 0;
131766   int rc;                         /* Return code */
131767
131768   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
131769   if( rc==SQLITE_OK ){
131770     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
131771     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
131772     sqlite3_step(pReplace);
131773     rc = sqlite3_reset(pReplace);
131774   }
131775
131776   return rc;
131777 }
131778
131779 /*
131780 ** Load an incr-merge hint from the database. The incr-merge hint, if one
131781 ** exists, is stored in the rowid==1 row of the %_stat table.
131782 **
131783 ** If successful, populate blob *pHint with the value read from the %_stat
131784 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
131785 ** SQLite error code.
131786 */
131787 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
131788   sqlite3_stmt *pSelect = 0;
131789   int rc;
131790
131791   pHint->n = 0;
131792   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
131793   if( rc==SQLITE_OK ){
131794     int rc2;
131795     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
131796     if( SQLITE_ROW==sqlite3_step(pSelect) ){
131797       const char *aHint = sqlite3_column_blob(pSelect, 0);
131798       int nHint = sqlite3_column_bytes(pSelect, 0);
131799       if( aHint ){
131800         blobGrowBuffer(pHint, nHint, &rc);
131801         if( rc==SQLITE_OK ){
131802           memcpy(pHint->a, aHint, nHint);
131803           pHint->n = nHint;
131804         }
131805       }
131806     }
131807     rc2 = sqlite3_reset(pSelect);
131808     if( rc==SQLITE_OK ) rc = rc2;
131809   }
131810
131811   return rc;
131812 }
131813
131814 /*
131815 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
131816 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
131817 ** consists of two varints, the absolute level number of the input segments
131818 ** and the number of input segments.
131819 **
131820 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
131821 ** set *pRc to an SQLite error code before returning.
131822 */
131823 static void fts3IncrmergeHintPush(
131824   Blob *pHint,                    /* Hint blob to append to */
131825   i64 iAbsLevel,                  /* First varint to store in hint */
131826   int nInput,                     /* Second varint to store in hint */
131827   int *pRc                        /* IN/OUT: Error code */
131828 ){
131829   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
131830   if( *pRc==SQLITE_OK ){
131831     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
131832     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
131833   }
131834 }
131835
131836 /*
131837 ** Read the last entry (most recently pushed) from the hint blob *pHint
131838 ** and then remove the entry. Write the two values read to *piAbsLevel and
131839 ** *pnInput before returning.
131840 **
131841 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
131842 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
131843 */
131844 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
131845   const int nHint = pHint->n;
131846   int i;
131847
131848   i = pHint->n-2;
131849   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
131850   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
131851
131852   pHint->n = i;
131853   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
131854   i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
131855   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
131856
131857   return SQLITE_OK;
131858 }
131859
131860
131861 /*
131862 ** Attempt an incremental merge that writes nMerge leaf blocks.
131863 **
131864 ** Incremental merges happen nMin segments at a time. The two
131865 ** segments to be merged are the nMin oldest segments (the ones with
131866 ** the smallest indexes) in the highest level that contains at least
131867 ** nMin segments. Multiple merges might occur in an attempt to write the
131868 ** quota of nMerge leaf blocks.
131869 */
131870 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
131871   int rc;                         /* Return code */
131872   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
131873   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
131874   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
131875   IncrmergeWriter *pWriter;       /* Writer object */
131876   int nSeg = 0;                   /* Number of input segments */
131877   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
131878   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
131879   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
131880
131881   /* Allocate space for the cursor, filter and writer objects */
131882   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
131883   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
131884   if( !pWriter ) return SQLITE_NOMEM;
131885   pFilter = (Fts3SegFilter *)&pWriter[1];
131886   pCsr = (Fts3MultiSegReader *)&pFilter[1];
131887
131888   rc = fts3IncrmergeHintLoad(p, &hint);
131889   while( rc==SQLITE_OK && nRem>0 ){
131890     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
131891     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
131892     int bUseHint = 0;             /* True if attempting to append */
131893
131894     /* Search the %_segdir table for the absolute level with the smallest
131895     ** relative level number that contains at least nMin segments, if any.
131896     ** If one is found, set iAbsLevel to the absolute level number and
131897     ** nSeg to nMin. If no level with at least nMin segments can be found,
131898     ** set nSeg to -1.
131899     */
131900     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
131901     sqlite3_bind_int(pFindLevel, 1, nMin);
131902     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
131903       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
131904       nSeg = nMin;
131905     }else{
131906       nSeg = -1;
131907     }
131908     rc = sqlite3_reset(pFindLevel);
131909
131910     /* If the hint read from the %_stat table is not empty, check if the
131911     ** last entry in it specifies a relative level smaller than or equal
131912     ** to the level identified by the block above (if any). If so, this
131913     ** iteration of the loop will work on merging at the hinted level.
131914     */
131915     if( rc==SQLITE_OK && hint.n ){
131916       int nHint = hint.n;
131917       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
131918       int nHintSeg = 0;                     /* Hint number of segments */
131919
131920       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
131921       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
131922         iAbsLevel = iHintAbsLevel;
131923         nSeg = nHintSeg;
131924         bUseHint = 1;
131925         bDirtyHint = 1;
131926       }else{
131927         /* This undoes the effect of the HintPop() above - so that no entry
131928         ** is removed from the hint blob.  */
131929         hint.n = nHint;
131930       }
131931     }
131932
131933     /* If nSeg is less that zero, then there is no level with at least
131934     ** nMin segments and no hint in the %_stat table. No work to do.
131935     ** Exit early in this case.  */
131936     if( nSeg<0 ) break;
131937
131938     /* Open a cursor to iterate through the contents of the oldest nSeg
131939     ** indexes of absolute level iAbsLevel. If this cursor is opened using
131940     ** the 'hint' parameters, it is possible that there are less than nSeg
131941     ** segments available in level iAbsLevel. In this case, no work is
131942     ** done on iAbsLevel - fall through to the next iteration of the loop
131943     ** to start work on some other level.  */
131944     memset(pWriter, 0, nAlloc);
131945     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
131946     if( rc==SQLITE_OK ){
131947       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
131948     }
131949     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
131950      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
131951      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
131952     ){
131953       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
131954       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
131955       if( rc==SQLITE_OK ){
131956         if( bUseHint && iIdx>0 ){
131957           const char *zKey = pCsr->zTerm;
131958           int nKey = pCsr->nTerm;
131959           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
131960         }else{
131961           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
131962         }
131963       }
131964
131965       if( rc==SQLITE_OK && pWriter->nLeafEst ){
131966         fts3LogMerge(nSeg, iAbsLevel);
131967         do {
131968           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
131969           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
131970           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
131971         }while( rc==SQLITE_ROW );
131972
131973         /* Update or delete the input segments */
131974         if( rc==SQLITE_OK ){
131975           nRem -= (1 + pWriter->nWork);
131976           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
131977           if( nSeg!=0 ){
131978             bDirtyHint = 1;
131979             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
131980           }
131981         }
131982       }
131983
131984       fts3IncrmergeRelease(p, pWriter, &rc);
131985     }
131986
131987     sqlite3Fts3SegReaderFinish(pCsr);
131988   }
131989
131990   /* Write the hint values into the %_stat table for the next incr-merger */
131991   if( bDirtyHint && rc==SQLITE_OK ){
131992     rc = fts3IncrmergeHintStore(p, &hint);
131993   }
131994
131995   sqlite3_free(pWriter);
131996   sqlite3_free(hint.a);
131997   return rc;
131998 }
131999
132000 /*
132001 ** Convert the text beginning at *pz into an integer and return
132002 ** its value.  Advance *pz to point to the first character past
132003 ** the integer.
132004 */
132005 static int fts3Getint(const char **pz){
132006   const char *z = *pz;
132007   int i = 0;
132008   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
132009   *pz = z;
132010   return i;
132011 }
132012
132013 /*
132014 ** Process statements of the form:
132015 **
132016 **    INSERT INTO table(table) VALUES('merge=A,B');
132017 **
132018 ** A and B are integers that decode to be the number of leaf pages
132019 ** written for the merge, and the minimum number of segments on a level
132020 ** before it will be selected for a merge, respectively.
132021 */
132022 static int fts3DoIncrmerge(
132023   Fts3Table *p,                   /* FTS3 table handle */
132024   const char *zParam              /* Nul-terminated string containing "A,B" */
132025 ){
132026   int rc;
132027   int nMin = (FTS3_MERGE_COUNT / 2);
132028   int nMerge = 0;
132029   const char *z = zParam;
132030
132031   /* Read the first integer value */
132032   nMerge = fts3Getint(&z);
132033
132034   /* If the first integer value is followed by a ',',  read the second
132035   ** integer value. */
132036   if( z[0]==',' && z[1]!='\0' ){
132037     z++;
132038     nMin = fts3Getint(&z);
132039   }
132040
132041   if( z[0]!='\0' || nMin<2 ){
132042     rc = SQLITE_ERROR;
132043   }else{
132044     rc = SQLITE_OK;
132045     if( !p->bHasStat ){
132046       assert( p->bFts4==0 );
132047       sqlite3Fts3CreateStatTable(&rc, p);
132048     }
132049     if( rc==SQLITE_OK ){
132050       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
132051     }
132052     sqlite3Fts3SegmentsClose(p);
132053   }
132054   return rc;
132055 }
132056
132057 /*
132058 ** Process statements of the form:
132059 **
132060 **    INSERT INTO table(table) VALUES('automerge=X');
132061 **
132062 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
132063 ** turn it on.  The setting is persistent.
132064 */
132065 static int fts3DoAutoincrmerge(
132066   Fts3Table *p,                   /* FTS3 table handle */
132067   const char *zParam              /* Nul-terminated string containing boolean */
132068 ){
132069   int rc = SQLITE_OK;
132070   sqlite3_stmt *pStmt = 0;
132071   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
132072   if( !p->bHasStat ){
132073     assert( p->bFts4==0 );
132074     sqlite3Fts3CreateStatTable(&rc, p);
132075     if( rc ) return rc;
132076   }
132077   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
132078   if( rc ) return rc;;
132079   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
132080   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
132081   sqlite3_step(pStmt);
132082   rc = sqlite3_reset(pStmt);
132083   return rc;
132084 }
132085
132086 /*
132087 ** Return a 64-bit checksum for the FTS index entry specified by the
132088 ** arguments to this function.
132089 */
132090 static u64 fts3ChecksumEntry(
132091   const char *zTerm,              /* Pointer to buffer containing term */
132092   int nTerm,                      /* Size of zTerm in bytes */
132093   int iLangid,                    /* Language id for current row */
132094   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
132095   i64 iDocid,                     /* Docid for current row. */
132096   int iCol,                       /* Column number */
132097   int iPos                        /* Position */
132098 ){
132099   int i;
132100   u64 ret = (u64)iDocid;
132101
132102   ret += (ret<<3) + iLangid;
132103   ret += (ret<<3) + iIndex;
132104   ret += (ret<<3) + iCol;
132105   ret += (ret<<3) + iPos;
132106   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
132107
132108   return ret;
132109 }
132110
132111 /*
132112 ** Return a checksum of all entries in the FTS index that correspond to
132113 ** language id iLangid. The checksum is calculated by XORing the checksums
132114 ** of each individual entry (see fts3ChecksumEntry()) together.
132115 **
132116 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
132117 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
132118 ** return value is undefined in this case.
132119 */
132120 static u64 fts3ChecksumIndex(
132121   Fts3Table *p,                   /* FTS3 table handle */
132122   int iLangid,                    /* Language id to return cksum for */
132123   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
132124   int *pRc                        /* OUT: Return code */
132125 ){
132126   Fts3SegFilter filter;
132127   Fts3MultiSegReader csr;
132128   int rc;
132129   u64 cksum = 0;
132130
132131   assert( *pRc==SQLITE_OK );
132132
132133   memset(&filter, 0, sizeof(filter));
132134   memset(&csr, 0, sizeof(csr));
132135   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
132136   filter.flags |= FTS3_SEGMENT_SCAN;
132137
132138   rc = sqlite3Fts3SegReaderCursor(
132139       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
132140   );
132141   if( rc==SQLITE_OK ){
132142     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
132143   }
132144
132145   if( rc==SQLITE_OK ){
132146     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
132147       char *pCsr = csr.aDoclist;
132148       char *pEnd = &pCsr[csr.nDoclist];
132149
132150       i64 iDocid = 0;
132151       i64 iCol = 0;
132152       i64 iPos = 0;
132153
132154       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
132155       while( pCsr<pEnd ){
132156         i64 iVal = 0;
132157         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
132158         if( pCsr<pEnd ){
132159           if( iVal==0 || iVal==1 ){
132160             iCol = 0;
132161             iPos = 0;
132162             if( iVal ){
132163               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
132164             }else{
132165               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
132166               iDocid += iVal;
132167             }
132168           }else{
132169             iPos += (iVal - 2);
132170             cksum = cksum ^ fts3ChecksumEntry(
132171                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
132172                 (int)iCol, (int)iPos
132173             );
132174           }
132175         }
132176       }
132177     }
132178   }
132179   sqlite3Fts3SegReaderFinish(&csr);
132180
132181   *pRc = rc;
132182   return cksum;
132183 }
132184
132185 /*
132186 ** Check if the contents of the FTS index match the current contents of the
132187 ** content table. If no error occurs and the contents do match, set *pbOk
132188 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
132189 ** to false before returning.
132190 **
132191 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
132192 ** code. The final value of *pbOk is undefined in this case.
132193 */
132194 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
132195   int rc = SQLITE_OK;             /* Return code */
132196   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
132197   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
132198   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
132199
132200   /* This block calculates the checksum according to the FTS index. */
132201   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
132202   if( rc==SQLITE_OK ){
132203     int rc2;
132204     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
132205     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
132206       int iLangid = sqlite3_column_int(pAllLangid, 0);
132207       int i;
132208       for(i=0; i<p->nIndex; i++){
132209         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
132210       }
132211     }
132212     rc2 = sqlite3_reset(pAllLangid);
132213     if( rc==SQLITE_OK ) rc = rc2;
132214   }
132215
132216   /* This block calculates the checksum according to the %_content table */
132217   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
132218   if( rc==SQLITE_OK ){
132219     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
132220     sqlite3_stmt *pStmt = 0;
132221     char *zSql;
132222
132223     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
132224     if( !zSql ){
132225       rc = SQLITE_NOMEM;
132226     }else{
132227       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
132228       sqlite3_free(zSql);
132229     }
132230
132231     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
132232       i64 iDocid = sqlite3_column_int64(pStmt, 0);
132233       int iLang = langidFromSelect(p, pStmt);
132234       int iCol;
132235
132236       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
132237         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
132238         int nText = sqlite3_column_bytes(pStmt, iCol+1);
132239         sqlite3_tokenizer_cursor *pT = 0;
132240
132241         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
132242         while( rc==SQLITE_OK ){
132243           char const *zToken;       /* Buffer containing token */
132244           int nToken = 0;           /* Number of bytes in token */
132245           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
132246           int iPos = 0;             /* Position of token in zText */
132247
132248           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
132249           if( rc==SQLITE_OK ){
132250             int i;
132251             cksum2 = cksum2 ^ fts3ChecksumEntry(
132252                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
132253             );
132254             for(i=1; i<p->nIndex; i++){
132255               if( p->aIndex[i].nPrefix<=nToken ){
132256                 cksum2 = cksum2 ^ fts3ChecksumEntry(
132257                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
132258                 );
132259               }
132260             }
132261           }
132262         }
132263         if( pT ) pModule->xClose(pT);
132264         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
132265       }
132266     }
132267
132268     sqlite3_finalize(pStmt);
132269   }
132270
132271   *pbOk = (cksum1==cksum2);
132272   return rc;
132273 }
132274
132275 /*
132276 ** Run the integrity-check. If no error occurs and the current contents of
132277 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
132278 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
132279 **
132280 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
132281 ** error code.
132282 **
132283 ** The integrity-check works as follows. For each token and indexed token
132284 ** prefix in the document set, a 64-bit checksum is calculated (by code
132285 ** in fts3ChecksumEntry()) based on the following:
132286 **
132287 **     + The index number (0 for the main index, 1 for the first prefix
132288 **       index etc.),
132289 **     + The token (or token prefix) text itself,
132290 **     + The language-id of the row it appears in,
132291 **     + The docid of the row it appears in,
132292 **     + The column it appears in, and
132293 **     + The tokens position within that column.
132294 **
132295 ** The checksums for all entries in the index are XORed together to create
132296 ** a single checksum for the entire index.
132297 **
132298 ** The integrity-check code calculates the same checksum in two ways:
132299 **
132300 **     1. By scanning the contents of the FTS index, and
132301 **     2. By scanning and tokenizing the content table.
132302 **
132303 ** If the two checksums are identical, the integrity-check is deemed to have
132304 ** passed.
132305 */
132306 static int fts3DoIntegrityCheck(
132307   Fts3Table *p                    /* FTS3 table handle */
132308 ){
132309   int rc;
132310   int bOk = 0;
132311   rc = fts3IntegrityCheck(p, &bOk);
132312   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
132313   return rc;
132314 }
132315
132316 /*
132317 ** Handle a 'special' INSERT of the form:
132318 **
132319 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
132320 **
132321 ** Argument pVal contains the result of <expr>. Currently the only
132322 ** meaningful value to insert is the text 'optimize'.
132323 */
132324 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
132325   int rc;                         /* Return Code */
132326   const char *zVal = (const char *)sqlite3_value_text(pVal);
132327   int nVal = sqlite3_value_bytes(pVal);
132328
132329   if( !zVal ){
132330     return SQLITE_NOMEM;
132331   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
132332     rc = fts3DoOptimize(p, 0);
132333   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
132334     rc = fts3DoRebuild(p);
132335   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
132336     rc = fts3DoIntegrityCheck(p);
132337   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
132338     rc = fts3DoIncrmerge(p, &zVal[6]);
132339   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
132340     rc = fts3DoAutoincrmerge(p, &zVal[10]);
132341 #ifdef SQLITE_TEST
132342   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
132343     p->nNodeSize = atoi(&zVal[9]);
132344     rc = SQLITE_OK;
132345   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
132346     p->nMaxPendingData = atoi(&zVal[11]);
132347     rc = SQLITE_OK;
132348 #endif
132349   }else{
132350     rc = SQLITE_ERROR;
132351   }
132352
132353   return rc;
132354 }
132355
132356 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
132357 /*
132358 ** Delete all cached deferred doclists. Deferred doclists are cached
132359 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
132360 */
132361 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
132362   Fts3DeferredToken *pDef;
132363   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
132364     fts3PendingListDelete(pDef->pList);
132365     pDef->pList = 0;
132366   }
132367 }
132368
132369 /*
132370 ** Free all entries in the pCsr->pDeffered list. Entries are added to
132371 ** this list using sqlite3Fts3DeferToken().
132372 */
132373 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
132374   Fts3DeferredToken *pDef;
132375   Fts3DeferredToken *pNext;
132376   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
132377     pNext = pDef->pNext;
132378     fts3PendingListDelete(pDef->pList);
132379     sqlite3_free(pDef);
132380   }
132381   pCsr->pDeferred = 0;
132382 }
132383
132384 /*
132385 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
132386 ** based on the row that pCsr currently points to.
132387 **
132388 ** A deferred-doclist is like any other doclist with position information
132389 ** included, except that it only contains entries for a single row of the
132390 ** table, not for all rows.
132391 */
132392 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
132393   int rc = SQLITE_OK;             /* Return code */
132394   if( pCsr->pDeferred ){
132395     int i;                        /* Used to iterate through table columns */
132396     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
132397     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
132398
132399     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
132400     sqlite3_tokenizer *pT = p->pTokenizer;
132401     sqlite3_tokenizer_module const *pModule = pT->pModule;
132402
132403     assert( pCsr->isRequireSeek==0 );
132404     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
132405
132406     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
132407       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
132408       sqlite3_tokenizer_cursor *pTC = 0;
132409
132410       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
132411       while( rc==SQLITE_OK ){
132412         char const *zToken;       /* Buffer containing token */
132413         int nToken = 0;           /* Number of bytes in token */
132414         int iDum1 = 0, iDum2 = 0; /* Dummy variables */
132415         int iPos = 0;             /* Position of token in zText */
132416
132417         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
132418         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
132419           Fts3PhraseToken *pPT = pDef->pToken;
132420           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
132421            && (pPT->bFirst==0 || iPos==0)
132422            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
132423            && (0==memcmp(zToken, pPT->z, pPT->n))
132424           ){
132425             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
132426           }
132427         }
132428       }
132429       if( pTC ) pModule->xClose(pTC);
132430       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
132431     }
132432
132433     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
132434       if( pDef->pList ){
132435         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
132436       }
132437     }
132438   }
132439
132440   return rc;
132441 }
132442
132443 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
132444   Fts3DeferredToken *p,
132445   char **ppData,
132446   int *pnData
132447 ){
132448   char *pRet;
132449   int nSkip;
132450   sqlite3_int64 dummy;
132451
132452   *ppData = 0;
132453   *pnData = 0;
132454
132455   if( p->pList==0 ){
132456     return SQLITE_OK;
132457   }
132458
132459   pRet = (char *)sqlite3_malloc(p->pList->nData);
132460   if( !pRet ) return SQLITE_NOMEM;
132461
132462   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
132463   *pnData = p->pList->nData - nSkip;
132464   *ppData = pRet;
132465
132466   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
132467   return SQLITE_OK;
132468 }
132469
132470 /*
132471 ** Add an entry for token pToken to the pCsr->pDeferred list.
132472 */
132473 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
132474   Fts3Cursor *pCsr,               /* Fts3 table cursor */
132475   Fts3PhraseToken *pToken,        /* Token to defer */
132476   int iCol                        /* Column that token must appear in (or -1) */
132477 ){
132478   Fts3DeferredToken *pDeferred;
132479   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
132480   if( !pDeferred ){
132481     return SQLITE_NOMEM;
132482   }
132483   memset(pDeferred, 0, sizeof(*pDeferred));
132484   pDeferred->pToken = pToken;
132485   pDeferred->pNext = pCsr->pDeferred;
132486   pDeferred->iCol = iCol;
132487   pCsr->pDeferred = pDeferred;
132488
132489   assert( pToken->pDeferred==0 );
132490   pToken->pDeferred = pDeferred;
132491
132492   return SQLITE_OK;
132493 }
132494 #endif
132495
132496 /*
132497 ** SQLite value pRowid contains the rowid of a row that may or may not be
132498 ** present in the FTS3 table. If it is, delete it and adjust the contents
132499 ** of subsiduary data structures accordingly.
132500 */
132501 static int fts3DeleteByRowid(
132502   Fts3Table *p,
132503   sqlite3_value *pRowid,
132504   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
132505   u32 *aSzDel
132506 ){
132507   int rc = SQLITE_OK;             /* Return code */
132508   int bFound = 0;                 /* True if *pRowid really is in the table */
132509
132510   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
132511   if( bFound && rc==SQLITE_OK ){
132512     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
132513     rc = fts3IsEmpty(p, pRowid, &isEmpty);
132514     if( rc==SQLITE_OK ){
132515       if( isEmpty ){
132516         /* Deleting this row means the whole table is empty. In this case
132517         ** delete the contents of all three tables and throw away any
132518         ** data in the pendingTerms hash table.  */
132519         rc = fts3DeleteAll(p, 1);
132520         *pnChng = 0;
132521         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
132522       }else{
132523         *pnChng = *pnChng - 1;
132524         if( p->zContentTbl==0 ){
132525           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
132526         }
132527         if( p->bHasDocsize ){
132528           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
132529         }
132530       }
132531     }
132532   }
132533
132534   return rc;
132535 }
132536
132537 /*
132538 ** This function does the work for the xUpdate method of FTS3 virtual
132539 ** tables. The schema of the virtual table being:
132540 **
132541 **     CREATE TABLE <table name>(
132542 **       <user columns>,
132543 **       <table name> HIDDEN,
132544 **       docid HIDDEN,
132545 **       <langid> HIDDEN
132546 **     );
132547 **
132548 **
132549 */
132550 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
132551   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
132552   int nArg,                       /* Size of argument array */
132553   sqlite3_value **apVal,          /* Array of arguments */
132554   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
132555 ){
132556   Fts3Table *p = (Fts3Table *)pVtab;
132557   int rc = SQLITE_OK;             /* Return Code */
132558   int isRemove = 0;               /* True for an UPDATE or DELETE */
132559   u32 *aSzIns = 0;                /* Sizes of inserted documents */
132560   u32 *aSzDel = 0;                /* Sizes of deleted documents */
132561   int nChng = 0;                  /* Net change in number of documents */
132562   int bInsertDone = 0;
132563
132564   assert( p->pSegments==0 );
132565   assert(
132566       nArg==1                     /* DELETE operations */
132567    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
132568   );
132569
132570   /* Check for a "special" INSERT operation. One of the form:
132571   **
132572   **   INSERT INTO xyz(xyz) VALUES('command');
132573   */
132574   if( nArg>1
132575    && sqlite3_value_type(apVal[0])==SQLITE_NULL
132576    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
132577   ){
132578     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
132579     goto update_out;
132580   }
132581
132582   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
132583     rc = SQLITE_CONSTRAINT;
132584     goto update_out;
132585   }
132586
132587   /* Allocate space to hold the change in document sizes */
132588   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
132589   if( aSzDel==0 ){
132590     rc = SQLITE_NOMEM;
132591     goto update_out;
132592   }
132593   aSzIns = &aSzDel[p->nColumn+1];
132594   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
132595
132596   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
132597   ** value, then this operation requires constraint handling.
132598   **
132599   ** If the on-conflict mode is REPLACE, this means that the existing row
132600   ** should be deleted from the database before inserting the new row. Or,
132601   ** if the on-conflict mode is other than REPLACE, then this method must
132602   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
132603   ** modify the database file.
132604   */
132605   if( nArg>1 && p->zContentTbl==0 ){
132606     /* Find the value object that holds the new rowid value. */
132607     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
132608     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
132609       pNewRowid = apVal[1];
132610     }
132611
132612     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
132613         sqlite3_value_type(apVal[0])==SQLITE_NULL
132614      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
132615     )){
132616       /* The new rowid is not NULL (in this case the rowid will be
132617       ** automatically assigned and there is no chance of a conflict), and
132618       ** the statement is either an INSERT or an UPDATE that modifies the
132619       ** rowid column. So if the conflict mode is REPLACE, then delete any
132620       ** existing row with rowid=pNewRowid.
132621       **
132622       ** Or, if the conflict mode is not REPLACE, insert the new record into
132623       ** the %_content table. If we hit the duplicate rowid constraint (or any
132624       ** other error) while doing so, return immediately.
132625       **
132626       ** This branch may also run if pNewRowid contains a value that cannot
132627       ** be losslessly converted to an integer. In this case, the eventual
132628       ** call to fts3InsertData() (either just below or further on in this
132629       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
132630       ** invoked, it will delete zero rows (since no row will have
132631       ** docid=$pNewRowid if $pNewRowid is not an integer value).
132632       */
132633       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
132634         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
132635       }else{
132636         rc = fts3InsertData(p, apVal, pRowid);
132637         bInsertDone = 1;
132638       }
132639     }
132640   }
132641   if( rc!=SQLITE_OK ){
132642     goto update_out;
132643   }
132644
132645   /* If this is a DELETE or UPDATE operation, remove the old record. */
132646   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
132647     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
132648     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
132649     isRemove = 1;
132650   }
132651
132652   /* If this is an INSERT or UPDATE operation, insert the new record. */
132653   if( nArg>1 && rc==SQLITE_OK ){
132654     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
132655     if( bInsertDone==0 ){
132656       rc = fts3InsertData(p, apVal, pRowid);
132657       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
132658         rc = FTS_CORRUPT_VTAB;
132659       }
132660     }
132661     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
132662       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
132663     }
132664     if( rc==SQLITE_OK ){
132665       assert( p->iPrevDocid==*pRowid );
132666       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
132667     }
132668     if( p->bHasDocsize ){
132669       fts3InsertDocsize(&rc, p, aSzIns);
132670     }
132671     nChng++;
132672   }
132673
132674   if( p->bFts4 ){
132675     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
132676   }
132677
132678  update_out:
132679   sqlite3_free(aSzDel);
132680   sqlite3Fts3SegmentsClose(p);
132681   return rc;
132682 }
132683
132684 /*
132685 ** Flush any data in the pending-terms hash table to disk. If successful,
132686 ** merge all segments in the database (including the new segment, if
132687 ** there was any data to flush) into a single segment.
132688 */
132689 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
132690   int rc;
132691   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
132692   if( rc==SQLITE_OK ){
132693     rc = fts3DoOptimize(p, 1);
132694     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
132695       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
132696       if( rc2!=SQLITE_OK ) rc = rc2;
132697     }else{
132698       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
132699       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
132700     }
132701   }
132702   sqlite3Fts3SegmentsClose(p);
132703   return rc;
132704 }
132705
132706 #endif
132707
132708 /************** End of fts3_write.c ******************************************/
132709 /************** Begin file fts3_snippet.c ************************************/
132710 /*
132711 ** 2009 Oct 23
132712 **
132713 ** The author disclaims copyright to this source code.  In place of
132714 ** a legal notice, here is a blessing:
132715 **
132716 **    May you do good and not evil.
132717 **    May you find forgiveness for yourself and forgive others.
132718 **    May you share freely, never taking more than you give.
132719 **
132720 ******************************************************************************
132721 */
132722
132723 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132724
132725 /* #include <string.h> */
132726 /* #include <assert.h> */
132727
132728 /*
132729 ** Characters that may appear in the second argument to matchinfo().
132730 */
132731 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
132732 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
132733 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
132734 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
132735 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
132736 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
132737 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
132738
132739 /*
132740 ** The default value for the second argument to matchinfo().
132741 */
132742 #define FTS3_MATCHINFO_DEFAULT   "pcx"
132743
132744
132745 /*
132746 ** Used as an fts3ExprIterate() context when loading phrase doclists to
132747 ** Fts3Expr.aDoclist[]/nDoclist.
132748 */
132749 typedef struct LoadDoclistCtx LoadDoclistCtx;
132750 struct LoadDoclistCtx {
132751   Fts3Cursor *pCsr;               /* FTS3 Cursor */
132752   int nPhrase;                    /* Number of phrases seen so far */
132753   int nToken;                     /* Number of tokens seen so far */
132754 };
132755
132756 /*
132757 ** The following types are used as part of the implementation of the
132758 ** fts3BestSnippet() routine.
132759 */
132760 typedef struct SnippetIter SnippetIter;
132761 typedef struct SnippetPhrase SnippetPhrase;
132762 typedef struct SnippetFragment SnippetFragment;
132763
132764 struct SnippetIter {
132765   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
132766   int iCol;                       /* Extract snippet from this column */
132767   int nSnippet;                   /* Requested snippet length (in tokens) */
132768   int nPhrase;                    /* Number of phrases in query */
132769   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
132770   int iCurrent;                   /* First token of current snippet */
132771 };
132772
132773 struct SnippetPhrase {
132774   int nToken;                     /* Number of tokens in phrase */
132775   char *pList;                    /* Pointer to start of phrase position list */
132776   int iHead;                      /* Next value in position list */
132777   char *pHead;                    /* Position list data following iHead */
132778   int iTail;                      /* Next value in trailing position list */
132779   char *pTail;                    /* Position list data following iTail */
132780 };
132781
132782 struct SnippetFragment {
132783   int iCol;                       /* Column snippet is extracted from */
132784   int iPos;                       /* Index of first token in snippet */
132785   u64 covered;                    /* Mask of query phrases covered */
132786   u64 hlmask;                     /* Mask of snippet terms to highlight */
132787 };
132788
132789 /*
132790 ** This type is used as an fts3ExprIterate() context object while
132791 ** accumulating the data returned by the matchinfo() function.
132792 */
132793 typedef struct MatchInfo MatchInfo;
132794 struct MatchInfo {
132795   Fts3Cursor *pCursor;            /* FTS3 Cursor */
132796   int nCol;                       /* Number of columns in table */
132797   int nPhrase;                    /* Number of matchable phrases in query */
132798   sqlite3_int64 nDoc;             /* Number of docs in database */
132799   u32 *aMatchinfo;                /* Pre-allocated buffer */
132800 };
132801
132802
132803
132804 /*
132805 ** The snippet() and offsets() functions both return text values. An instance
132806 ** of the following structure is used to accumulate those values while the
132807 ** functions are running. See fts3StringAppend() for details.
132808 */
132809 typedef struct StrBuffer StrBuffer;
132810 struct StrBuffer {
132811   char *z;                        /* Pointer to buffer containing string */
132812   int n;                          /* Length of z in bytes (excl. nul-term) */
132813   int nAlloc;                     /* Allocated size of buffer z in bytes */
132814 };
132815
132816
132817 /*
132818 ** This function is used to help iterate through a position-list. A position
132819 ** list is a list of unique integers, sorted from smallest to largest. Each
132820 ** element of the list is represented by an FTS3 varint that takes the value
132821 ** of the difference between the current element and the previous one plus
132822 ** two. For example, to store the position-list:
132823 **
132824 **     4 9 113
132825 **
132826 ** the three varints:
132827 **
132828 **     6 7 106
132829 **
132830 ** are encoded.
132831 **
132832 ** When this function is called, *pp points to the start of an element of
132833 ** the list. *piPos contains the value of the previous entry in the list.
132834 ** After it returns, *piPos contains the value of the next element of the
132835 ** list and *pp is advanced to the following varint.
132836 */
132837 static void fts3GetDeltaPosition(char **pp, int *piPos){
132838   int iVal;
132839   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
132840   *piPos += (iVal-2);
132841 }
132842
132843 /*
132844 ** Helper function for fts3ExprIterate() (see below).
132845 */
132846 static int fts3ExprIterate2(
132847   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
132848   int *piPhrase,                  /* Pointer to phrase counter */
132849   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
132850   void *pCtx                      /* Second argument to pass to callback */
132851 ){
132852   int rc;                         /* Return code */
132853   int eType = pExpr->eType;       /* Type of expression node pExpr */
132854
132855   if( eType!=FTSQUERY_PHRASE ){
132856     assert( pExpr->pLeft && pExpr->pRight );
132857     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
132858     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
132859       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
132860     }
132861   }else{
132862     rc = x(pExpr, *piPhrase, pCtx);
132863     (*piPhrase)++;
132864   }
132865   return rc;
132866 }
132867
132868 /*
132869 ** Iterate through all phrase nodes in an FTS3 query, except those that
132870 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
132871 ** For each phrase node found, the supplied callback function is invoked.
132872 **
132873 ** If the callback function returns anything other than SQLITE_OK,
132874 ** the iteration is abandoned and the error code returned immediately.
132875 ** Otherwise, SQLITE_OK is returned after a callback has been made for
132876 ** all eligible phrase nodes.
132877 */
132878 static int fts3ExprIterate(
132879   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
132880   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
132881   void *pCtx                      /* Second argument to pass to callback */
132882 ){
132883   int iPhrase = 0;                /* Variable used as the phrase counter */
132884   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
132885 }
132886
132887 /*
132888 ** This is an fts3ExprIterate() callback used while loading the doclists
132889 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
132890 ** fts3ExprLoadDoclists().
132891 */
132892 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
132893   int rc = SQLITE_OK;
132894   Fts3Phrase *pPhrase = pExpr->pPhrase;
132895   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
132896
132897   UNUSED_PARAMETER(iPhrase);
132898
132899   p->nPhrase++;
132900   p->nToken += pPhrase->nToken;
132901
132902   return rc;
132903 }
132904
132905 /*
132906 ** Load the doclists for each phrase in the query associated with FTS3 cursor
132907 ** pCsr.
132908 **
132909 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
132910 ** phrases in the expression (all phrases except those directly or
132911 ** indirectly descended from the right-hand-side of a NOT operator). If
132912 ** pnToken is not NULL, then it is set to the number of tokens in all
132913 ** matchable phrases of the expression.
132914 */
132915 static int fts3ExprLoadDoclists(
132916   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
132917   int *pnPhrase,                  /* OUT: Number of phrases in query */
132918   int *pnToken                    /* OUT: Number of tokens in query */
132919 ){
132920   int rc;                         /* Return Code */
132921   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
132922   sCtx.pCsr = pCsr;
132923   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
132924   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
132925   if( pnToken ) *pnToken = sCtx.nToken;
132926   return rc;
132927 }
132928
132929 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
132930   (*(int *)ctx)++;
132931   UNUSED_PARAMETER(pExpr);
132932   UNUSED_PARAMETER(iPhrase);
132933   return SQLITE_OK;
132934 }
132935 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
132936   int nPhrase = 0;
132937   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
132938   return nPhrase;
132939 }
132940
132941 /*
132942 ** Advance the position list iterator specified by the first two
132943 ** arguments so that it points to the first element with a value greater
132944 ** than or equal to parameter iNext.
132945 */
132946 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
132947   char *pIter = *ppIter;
132948   if( pIter ){
132949     int iIter = *piIter;
132950
132951     while( iIter<iNext ){
132952       if( 0==(*pIter & 0xFE) ){
132953         iIter = -1;
132954         pIter = 0;
132955         break;
132956       }
132957       fts3GetDeltaPosition(&pIter, &iIter);
132958     }
132959
132960     *piIter = iIter;
132961     *ppIter = pIter;
132962   }
132963 }
132964
132965 /*
132966 ** Advance the snippet iterator to the next candidate snippet.
132967 */
132968 static int fts3SnippetNextCandidate(SnippetIter *pIter){
132969   int i;                          /* Loop counter */
132970
132971   if( pIter->iCurrent<0 ){
132972     /* The SnippetIter object has just been initialized. The first snippet
132973     ** candidate always starts at offset 0 (even if this candidate has a
132974     ** score of 0.0).
132975     */
132976     pIter->iCurrent = 0;
132977
132978     /* Advance the 'head' iterator of each phrase to the first offset that
132979     ** is greater than or equal to (iNext+nSnippet).
132980     */
132981     for(i=0; i<pIter->nPhrase; i++){
132982       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132983       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
132984     }
132985   }else{
132986     int iStart;
132987     int iEnd = 0x7FFFFFFF;
132988
132989     for(i=0; i<pIter->nPhrase; i++){
132990       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
132991       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
132992         iEnd = pPhrase->iHead;
132993       }
132994     }
132995     if( iEnd==0x7FFFFFFF ){
132996       return 1;
132997     }
132998
132999     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
133000     for(i=0; i<pIter->nPhrase; i++){
133001       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
133002       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
133003       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
133004     }
133005   }
133006
133007   return 0;
133008 }
133009
133010 /*
133011 ** Retrieve information about the current candidate snippet of snippet
133012 ** iterator pIter.
133013 */
133014 static void fts3SnippetDetails(
133015   SnippetIter *pIter,             /* Snippet iterator */
133016   u64 mCovered,                   /* Bitmask of phrases already covered */
133017   int *piToken,                   /* OUT: First token of proposed snippet */
133018   int *piScore,                   /* OUT: "Score" for this snippet */
133019   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
133020   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
133021 ){
133022   int iStart = pIter->iCurrent;   /* First token of snippet */
133023   int iScore = 0;                 /* Score of this snippet */
133024   int i;                          /* Loop counter */
133025   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
133026   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
133027
133028   for(i=0; i<pIter->nPhrase; i++){
133029     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
133030     if( pPhrase->pTail ){
133031       char *pCsr = pPhrase->pTail;
133032       int iCsr = pPhrase->iTail;
133033
133034       while( iCsr<(iStart+pIter->nSnippet) ){
133035         int j;
133036         u64 mPhrase = (u64)1 << i;
133037         u64 mPos = (u64)1 << (iCsr - iStart);
133038         assert( iCsr>=iStart );
133039         if( (mCover|mCovered)&mPhrase ){
133040           iScore++;
133041         }else{
133042           iScore += 1000;
133043         }
133044         mCover |= mPhrase;
133045
133046         for(j=0; j<pPhrase->nToken; j++){
133047           mHighlight |= (mPos>>j);
133048         }
133049
133050         if( 0==(*pCsr & 0x0FE) ) break;
133051         fts3GetDeltaPosition(&pCsr, &iCsr);
133052       }
133053     }
133054   }
133055
133056   /* Set the output variables before returning. */
133057   *piToken = iStart;
133058   *piScore = iScore;
133059   *pmCover = mCover;
133060   *pmHighlight = mHighlight;
133061 }
133062
133063 /*
133064 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
133065 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
133066 */
133067 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
133068   SnippetIter *p = (SnippetIter *)ctx;
133069   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
133070   char *pCsr;
133071   int rc;
133072
133073   pPhrase->nToken = pExpr->pPhrase->nToken;
133074   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
133075   assert( rc==SQLITE_OK || pCsr==0 );
133076   if( pCsr ){
133077     int iFirst = 0;
133078     pPhrase->pList = pCsr;
133079     fts3GetDeltaPosition(&pCsr, &iFirst);
133080     assert( iFirst>=0 );
133081     pPhrase->pHead = pCsr;
133082     pPhrase->pTail = pCsr;
133083     pPhrase->iHead = iFirst;
133084     pPhrase->iTail = iFirst;
133085   }else{
133086     assert( rc!=SQLITE_OK || (
133087        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
133088     ));
133089   }
133090
133091   return rc;
133092 }
133093
133094 /*
133095 ** Select the fragment of text consisting of nFragment contiguous tokens
133096 ** from column iCol that represent the "best" snippet. The best snippet
133097 ** is the snippet with the highest score, where scores are calculated
133098 ** by adding:
133099 **
133100 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
133101 **
133102 **   (b) +1000 points for the first occurence of each matchable phrase in
133103 **       the snippet for which the corresponding mCovered bit is not set.
133104 **
133105 ** The selected snippet parameters are stored in structure *pFragment before
133106 ** returning. The score of the selected snippet is stored in *piScore
133107 ** before returning.
133108 */
133109 static int fts3BestSnippet(
133110   int nSnippet,                   /* Desired snippet length */
133111   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
133112   int iCol,                       /* Index of column to create snippet from */
133113   u64 mCovered,                   /* Mask of phrases already covered */
133114   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
133115   SnippetFragment *pFragment,     /* OUT: Best snippet found */
133116   int *piScore                    /* OUT: Score of snippet pFragment */
133117 ){
133118   int rc;                         /* Return Code */
133119   int nList;                      /* Number of phrases in expression */
133120   SnippetIter sIter;              /* Iterates through snippet candidates */
133121   int nByte;                      /* Number of bytes of space to allocate */
133122   int iBestScore = -1;            /* Best snippet score found so far */
133123   int i;                          /* Loop counter */
133124
133125   memset(&sIter, 0, sizeof(sIter));
133126
133127   /* Iterate through the phrases in the expression to count them. The same
133128   ** callback makes sure the doclists are loaded for each phrase.
133129   */
133130   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
133131   if( rc!=SQLITE_OK ){
133132     return rc;
133133   }
133134
133135   /* Now that it is known how many phrases there are, allocate and zero
133136   ** the required space using malloc().
133137   */
133138   nByte = sizeof(SnippetPhrase) * nList;
133139   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
133140   if( !sIter.aPhrase ){
133141     return SQLITE_NOMEM;
133142   }
133143   memset(sIter.aPhrase, 0, nByte);
133144
133145   /* Initialize the contents of the SnippetIter object. Then iterate through
133146   ** the set of phrases in the expression to populate the aPhrase[] array.
133147   */
133148   sIter.pCsr = pCsr;
133149   sIter.iCol = iCol;
133150   sIter.nSnippet = nSnippet;
133151   sIter.nPhrase = nList;
133152   sIter.iCurrent = -1;
133153   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
133154
133155   /* Set the *pmSeen output variable. */
133156   for(i=0; i<nList; i++){
133157     if( sIter.aPhrase[i].pHead ){
133158       *pmSeen |= (u64)1 << i;
133159     }
133160   }
133161
133162   /* Loop through all candidate snippets. Store the best snippet in
133163   ** *pFragment. Store its associated 'score' in iBestScore.
133164   */
133165   pFragment->iCol = iCol;
133166   while( !fts3SnippetNextCandidate(&sIter) ){
133167     int iPos;
133168     int iScore;
133169     u64 mCover;
133170     u64 mHighlight;
133171     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
133172     assert( iScore>=0 );
133173     if( iScore>iBestScore ){
133174       pFragment->iPos = iPos;
133175       pFragment->hlmask = mHighlight;
133176       pFragment->covered = mCover;
133177       iBestScore = iScore;
133178     }
133179   }
133180
133181   sqlite3_free(sIter.aPhrase);
133182   *piScore = iBestScore;
133183   return SQLITE_OK;
133184 }
133185
133186
133187 /*
133188 ** Append a string to the string-buffer passed as the first argument.
133189 **
133190 ** If nAppend is negative, then the length of the string zAppend is
133191 ** determined using strlen().
133192 */
133193 static int fts3StringAppend(
133194   StrBuffer *pStr,                /* Buffer to append to */
133195   const char *zAppend,            /* Pointer to data to append to buffer */
133196   int nAppend                     /* Size of zAppend in bytes (or -1) */
133197 ){
133198   if( nAppend<0 ){
133199     nAppend = (int)strlen(zAppend);
133200   }
133201
133202   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
133203   ** to grow the buffer until so that it is big enough to accomadate the
133204   ** appended data.
133205   */
133206   if( pStr->n+nAppend+1>=pStr->nAlloc ){
133207     int nAlloc = pStr->nAlloc+nAppend+100;
133208     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
133209     if( !zNew ){
133210       return SQLITE_NOMEM;
133211     }
133212     pStr->z = zNew;
133213     pStr->nAlloc = nAlloc;
133214   }
133215
133216   /* Append the data to the string buffer. */
133217   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
133218   pStr->n += nAppend;
133219   pStr->z[pStr->n] = '\0';
133220
133221   return SQLITE_OK;
133222 }
133223
133224 /*
133225 ** The fts3BestSnippet() function often selects snippets that end with a
133226 ** query term. That is, the final term of the snippet is always a term
133227 ** that requires highlighting. For example, if 'X' is a highlighted term
133228 ** and '.' is a non-highlighted term, BestSnippet() may select:
133229 **
133230 **     ........X.....X
133231 **
133232 ** This function "shifts" the beginning of the snippet forward in the
133233 ** document so that there are approximately the same number of
133234 ** non-highlighted terms to the right of the final highlighted term as there
133235 ** are to the left of the first highlighted term. For example, to this:
133236 **
133237 **     ....X.....X....
133238 **
133239 ** This is done as part of extracting the snippet text, not when selecting
133240 ** the snippet. Snippet selection is done based on doclists only, so there
133241 ** is no way for fts3BestSnippet() to know whether or not the document
133242 ** actually contains terms that follow the final highlighted term.
133243 */
133244 static int fts3SnippetShift(
133245   Fts3Table *pTab,                /* FTS3 table snippet comes from */
133246   int iLangid,                    /* Language id to use in tokenizing */
133247   int nSnippet,                   /* Number of tokens desired for snippet */
133248   const char *zDoc,               /* Document text to extract snippet from */
133249   int nDoc,                       /* Size of buffer zDoc in bytes */
133250   int *piPos,                     /* IN/OUT: First token of snippet */
133251   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
133252 ){
133253   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
133254
133255   if( hlmask ){
133256     int nLeft;                    /* Tokens to the left of first highlight */
133257     int nRight;                   /* Tokens to the right of last highlight */
133258     int nDesired;                 /* Ideal number of tokens to shift forward */
133259
133260     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
133261     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
133262     nDesired = (nLeft-nRight)/2;
133263
133264     /* Ideally, the start of the snippet should be pushed forward in the
133265     ** document nDesired tokens. This block checks if there are actually
133266     ** nDesired tokens to the right of the snippet. If so, *piPos and
133267     ** *pHlMask are updated to shift the snippet nDesired tokens to the
133268     ** right. Otherwise, the snippet is shifted by the number of tokens
133269     ** available.
133270     */
133271     if( nDesired>0 ){
133272       int nShift;                 /* Number of tokens to shift snippet by */
133273       int iCurrent = 0;           /* Token counter */
133274       int rc;                     /* Return Code */
133275       sqlite3_tokenizer_module *pMod;
133276       sqlite3_tokenizer_cursor *pC;
133277       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
133278
133279       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
133280       ** or more tokens in zDoc/nDoc.
133281       */
133282       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
133283       if( rc!=SQLITE_OK ){
133284         return rc;
133285       }
133286       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
133287         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
133288         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
133289       }
133290       pMod->xClose(pC);
133291       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
133292
133293       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
133294       assert( nShift<=nDesired );
133295       if( nShift>0 ){
133296         *piPos += nShift;
133297         *pHlmask = hlmask >> nShift;
133298       }
133299     }
133300   }
133301   return SQLITE_OK;
133302 }
133303
133304 /*
133305 ** Extract the snippet text for fragment pFragment from cursor pCsr and
133306 ** append it to string buffer pOut.
133307 */
133308 static int fts3SnippetText(
133309   Fts3Cursor *pCsr,               /* FTS3 Cursor */
133310   SnippetFragment *pFragment,     /* Snippet to extract */
133311   int iFragment,                  /* Fragment number */
133312   int isLast,                     /* True for final fragment in snippet */
133313   int nSnippet,                   /* Number of tokens in extracted snippet */
133314   const char *zOpen,              /* String inserted before highlighted term */
133315   const char *zClose,             /* String inserted after highlighted term */
133316   const char *zEllipsis,          /* String inserted between snippets */
133317   StrBuffer *pOut                 /* Write output here */
133318 ){
133319   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133320   int rc;                         /* Return code */
133321   const char *zDoc;               /* Document text to extract snippet from */
133322   int nDoc;                       /* Size of zDoc in bytes */
133323   int iCurrent = 0;               /* Current token number of document */
133324   int iEnd = 0;                   /* Byte offset of end of current token */
133325   int isShiftDone = 0;            /* True after snippet is shifted */
133326   int iPos = pFragment->iPos;     /* First token of snippet */
133327   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
133328   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
133329   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
133330   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
133331
133332   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
133333   if( zDoc==0 ){
133334     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
133335       return SQLITE_NOMEM;
133336     }
133337     return SQLITE_OK;
133338   }
133339   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
133340
133341   /* Open a token cursor on the document. */
133342   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
133343   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
133344   if( rc!=SQLITE_OK ){
133345     return rc;
133346   }
133347
133348   while( rc==SQLITE_OK ){
133349     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
133350     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
133351     int iBegin = 0;               /* Offset in zDoc of start of token */
133352     int iFin = 0;                 /* Offset in zDoc of end of token */
133353     int isHighlight = 0;          /* True for highlighted terms */
133354
133355     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
133356     ** in the FTS code the variable that the third argument to xNext points to
133357     ** is initialized to zero before the first (*but not necessarily
133358     ** subsequent*) call to xNext(). This is done for a particular application
133359     ** that needs to know whether or not the tokenizer is being used for
133360     ** snippet generation or for some other purpose.
133361     **
133362     ** Extreme care is required when writing code to depend on this
133363     ** initialization. It is not a documented part of the tokenizer interface.
133364     ** If a tokenizer is used directly by any code outside of FTS, this
133365     ** convention might not be respected.  */
133366     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
133367     if( rc!=SQLITE_OK ){
133368       if( rc==SQLITE_DONE ){
133369         /* Special case - the last token of the snippet is also the last token
133370         ** of the column. Append any punctuation that occurred between the end
133371         ** of the previous token and the end of the document to the output.
133372         ** Then break out of the loop. */
133373         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
133374       }
133375       break;
133376     }
133377     if( iCurrent<iPos ){ continue; }
133378
133379     if( !isShiftDone ){
133380       int n = nDoc - iBegin;
133381       rc = fts3SnippetShift(
133382           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
133383       );
133384       isShiftDone = 1;
133385
133386       /* Now that the shift has been done, check if the initial "..." are
133387       ** required. They are required if (a) this is not the first fragment,
133388       ** or (b) this fragment does not begin at position 0 of its column.
133389       */
133390       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
133391         rc = fts3StringAppend(pOut, zEllipsis, -1);
133392       }
133393       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
133394     }
133395
133396     if( iCurrent>=(iPos+nSnippet) ){
133397       if( isLast ){
133398         rc = fts3StringAppend(pOut, zEllipsis, -1);
133399       }
133400       break;
133401     }
133402
133403     /* Set isHighlight to true if this term should be highlighted. */
133404     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
133405
133406     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
133407     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
133408     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
133409     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
133410
133411     iEnd = iFin;
133412   }
133413
133414   pMod->xClose(pC);
133415   return rc;
133416 }
133417
133418
133419 /*
133420 ** This function is used to count the entries in a column-list (a
133421 ** delta-encoded list of term offsets within a single column of a single
133422 ** row). When this function is called, *ppCollist should point to the
133423 ** beginning of the first varint in the column-list (the varint that
133424 ** contains the position of the first matching term in the column data).
133425 ** Before returning, *ppCollist is set to point to the first byte after
133426 ** the last varint in the column-list (either the 0x00 signifying the end
133427 ** of the position-list, or the 0x01 that precedes the column number of
133428 ** the next column in the position-list).
133429 **
133430 ** The number of elements in the column-list is returned.
133431 */
133432 static int fts3ColumnlistCount(char **ppCollist){
133433   char *pEnd = *ppCollist;
133434   char c = 0;
133435   int nEntry = 0;
133436
133437   /* A column-list is terminated by either a 0x01 or 0x00. */
133438   while( 0xFE & (*pEnd | c) ){
133439     c = *pEnd++ & 0x80;
133440     if( !c ) nEntry++;
133441   }
133442
133443   *ppCollist = pEnd;
133444   return nEntry;
133445 }
133446
133447 /*
133448 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
133449 ** for a single query.
133450 **
133451 ** fts3ExprIterate() callback to load the 'global' elements of a
133452 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
133453 ** of the matchinfo array that are constant for all rows returned by the
133454 ** current query.
133455 **
133456 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
133457 ** function populates Matchinfo.aMatchinfo[] as follows:
133458 **
133459 **   for(iCol=0; iCol<nCol; iCol++){
133460 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
133461 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
133462 **   }
133463 **
133464 ** where X is the number of matches for phrase iPhrase is column iCol of all
133465 ** rows of the table. Y is the number of rows for which column iCol contains
133466 ** at least one instance of phrase iPhrase.
133467 **
133468 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
133469 ** Y values are set to nDoc, where nDoc is the number of documents in the
133470 ** file system. This is done because the full-text index doclist is required
133471 ** to calculate these values properly, and the full-text index doclist is
133472 ** not available for deferred tokens.
133473 */
133474 static int fts3ExprGlobalHitsCb(
133475   Fts3Expr *pExpr,                /* Phrase expression node */
133476   int iPhrase,                    /* Phrase number (numbered from zero) */
133477   void *pCtx                      /* Pointer to MatchInfo structure */
133478 ){
133479   MatchInfo *p = (MatchInfo *)pCtx;
133480   return sqlite3Fts3EvalPhraseStats(
133481       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
133482   );
133483 }
133484
133485 /*
133486 ** fts3ExprIterate() callback used to collect the "local" part of the
133487 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
133488 ** array that are different for each row returned by the query.
133489 */
133490 static int fts3ExprLocalHitsCb(
133491   Fts3Expr *pExpr,                /* Phrase expression node */
133492   int iPhrase,                    /* Phrase number */
133493   void *pCtx                      /* Pointer to MatchInfo structure */
133494 ){
133495   int rc = SQLITE_OK;
133496   MatchInfo *p = (MatchInfo *)pCtx;
133497   int iStart = iPhrase * p->nCol * 3;
133498   int i;
133499
133500   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
133501     char *pCsr;
133502     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
133503     if( pCsr ){
133504       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
133505     }else{
133506       p->aMatchinfo[iStart+i*3] = 0;
133507     }
133508   }
133509
133510   return rc;
133511 }
133512
133513 static int fts3MatchinfoCheck(
133514   Fts3Table *pTab,
133515   char cArg,
133516   char **pzErr
133517 ){
133518   if( (cArg==FTS3_MATCHINFO_NPHRASE)
133519    || (cArg==FTS3_MATCHINFO_NCOL)
133520    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
133521    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
133522    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
133523    || (cArg==FTS3_MATCHINFO_LCS)
133524    || (cArg==FTS3_MATCHINFO_HITS)
133525   ){
133526     return SQLITE_OK;
133527   }
133528   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
133529   return SQLITE_ERROR;
133530 }
133531
133532 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
133533   int nVal;                       /* Number of integers output by cArg */
133534
133535   switch( cArg ){
133536     case FTS3_MATCHINFO_NDOC:
133537     case FTS3_MATCHINFO_NPHRASE:
133538     case FTS3_MATCHINFO_NCOL:
133539       nVal = 1;
133540       break;
133541
133542     case FTS3_MATCHINFO_AVGLENGTH:
133543     case FTS3_MATCHINFO_LENGTH:
133544     case FTS3_MATCHINFO_LCS:
133545       nVal = pInfo->nCol;
133546       break;
133547
133548     default:
133549       assert( cArg==FTS3_MATCHINFO_HITS );
133550       nVal = pInfo->nCol * pInfo->nPhrase * 3;
133551       break;
133552   }
133553
133554   return nVal;
133555 }
133556
133557 static int fts3MatchinfoSelectDoctotal(
133558   Fts3Table *pTab,
133559   sqlite3_stmt **ppStmt,
133560   sqlite3_int64 *pnDoc,
133561   const char **paLen
133562 ){
133563   sqlite3_stmt *pStmt;
133564   const char *a;
133565   sqlite3_int64 nDoc;
133566
133567   if( !*ppStmt ){
133568     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
133569     if( rc!=SQLITE_OK ) return rc;
133570   }
133571   pStmt = *ppStmt;
133572   assert( sqlite3_data_count(pStmt)==1 );
133573
133574   a = sqlite3_column_blob(pStmt, 0);
133575   a += sqlite3Fts3GetVarint(a, &nDoc);
133576   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
133577   *pnDoc = (u32)nDoc;
133578
133579   if( paLen ) *paLen = a;
133580   return SQLITE_OK;
133581 }
133582
133583 /*
133584 ** An instance of the following structure is used to store state while
133585 ** iterating through a multi-column position-list corresponding to the
133586 ** hits for a single phrase on a single row in order to calculate the
133587 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
133588 */
133589 typedef struct LcsIterator LcsIterator;
133590 struct LcsIterator {
133591   Fts3Expr *pExpr;                /* Pointer to phrase expression */
133592   int iPosOffset;                 /* Tokens count up to end of this phrase */
133593   char *pRead;                    /* Cursor used to iterate through aDoclist */
133594   int iPos;                       /* Current position */
133595 };
133596
133597 /*
133598 ** If LcsIterator.iCol is set to the following value, the iterator has
133599 ** finished iterating through all offsets for all columns.
133600 */
133601 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
133602
133603 static int fts3MatchinfoLcsCb(
133604   Fts3Expr *pExpr,                /* Phrase expression node */
133605   int iPhrase,                    /* Phrase number (numbered from zero) */
133606   void *pCtx                      /* Pointer to MatchInfo structure */
133607 ){
133608   LcsIterator *aIter = (LcsIterator *)pCtx;
133609   aIter[iPhrase].pExpr = pExpr;
133610   return SQLITE_OK;
133611 }
133612
133613 /*
133614 ** Advance the iterator passed as an argument to the next position. Return
133615 ** 1 if the iterator is at EOF or if it now points to the start of the
133616 ** position list for the next column.
133617 */
133618 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
133619   char *pRead = pIter->pRead;
133620   sqlite3_int64 iRead;
133621   int rc = 0;
133622
133623   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
133624   if( iRead==0 || iRead==1 ){
133625     pRead = 0;
133626     rc = 1;
133627   }else{
133628     pIter->iPos += (int)(iRead-2);
133629   }
133630
133631   pIter->pRead = pRead;
133632   return rc;
133633 }
133634
133635 /*
133636 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
133637 **
133638 ** If the call is successful, the longest-common-substring lengths for each
133639 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
133640 ** array before returning. SQLITE_OK is returned in this case.
133641 **
133642 ** Otherwise, if an error occurs, an SQLite error code is returned and the
133643 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
133644 ** undefined.
133645 */
133646 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
133647   LcsIterator *aIter;
133648   int i;
133649   int iCol;
133650   int nToken = 0;
133651
133652   /* Allocate and populate the array of LcsIterator objects. The array
133653   ** contains one element for each matchable phrase in the query.
133654   **/
133655   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
133656   if( !aIter ) return SQLITE_NOMEM;
133657   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
133658   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
133659
133660   for(i=0; i<pInfo->nPhrase; i++){
133661     LcsIterator *pIter = &aIter[i];
133662     nToken -= pIter->pExpr->pPhrase->nToken;
133663     pIter->iPosOffset = nToken;
133664   }
133665
133666   for(iCol=0; iCol<pInfo->nCol; iCol++){
133667     int nLcs = 0;                 /* LCS value for this column */
133668     int nLive = 0;                /* Number of iterators in aIter not at EOF */
133669
133670     for(i=0; i<pInfo->nPhrase; i++){
133671       int rc;
133672       LcsIterator *pIt = &aIter[i];
133673       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
133674       if( rc!=SQLITE_OK ) return rc;
133675       if( pIt->pRead ){
133676         pIt->iPos = pIt->iPosOffset;
133677         fts3LcsIteratorAdvance(&aIter[i]);
133678         nLive++;
133679       }
133680     }
133681
133682     while( nLive>0 ){
133683       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
133684       int nThisLcs = 0;           /* LCS for the current iterator positions */
133685
133686       for(i=0; i<pInfo->nPhrase; i++){
133687         LcsIterator *pIter = &aIter[i];
133688         if( pIter->pRead==0 ){
133689           /* This iterator is already at EOF for this column. */
133690           nThisLcs = 0;
133691         }else{
133692           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
133693             pAdv = pIter;
133694           }
133695           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
133696             nThisLcs++;
133697           }else{
133698             nThisLcs = 1;
133699           }
133700           if( nThisLcs>nLcs ) nLcs = nThisLcs;
133701         }
133702       }
133703       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
133704     }
133705
133706     pInfo->aMatchinfo[iCol] = nLcs;
133707   }
133708
133709   sqlite3_free(aIter);
133710   return SQLITE_OK;
133711 }
133712
133713 /*
133714 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
133715 ** be returned by the matchinfo() function. Argument zArg contains the
133716 ** format string passed as the second argument to matchinfo (or the
133717 ** default value "pcx" if no second argument was specified). The format
133718 ** string has already been validated and the pInfo->aMatchinfo[] array
133719 ** is guaranteed to be large enough for the output.
133720 **
133721 ** If bGlobal is true, then populate all fields of the matchinfo() output.
133722 ** If it is false, then assume that those fields that do not change between
133723 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
133724 ** have already been populated.
133725 **
133726 ** Return SQLITE_OK if successful, or an SQLite error code if an error
133727 ** occurs. If a value other than SQLITE_OK is returned, the state the
133728 ** pInfo->aMatchinfo[] buffer is left in is undefined.
133729 */
133730 static int fts3MatchinfoValues(
133731   Fts3Cursor *pCsr,               /* FTS3 cursor object */
133732   int bGlobal,                    /* True to grab the global stats */
133733   MatchInfo *pInfo,               /* Matchinfo context object */
133734   const char *zArg                /* Matchinfo format string */
133735 ){
133736   int rc = SQLITE_OK;
133737   int i;
133738   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133739   sqlite3_stmt *pSelect = 0;
133740
133741   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
133742
133743     switch( zArg[i] ){
133744       case FTS3_MATCHINFO_NPHRASE:
133745         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
133746         break;
133747
133748       case FTS3_MATCHINFO_NCOL:
133749         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
133750         break;
133751
133752       case FTS3_MATCHINFO_NDOC:
133753         if( bGlobal ){
133754           sqlite3_int64 nDoc = 0;
133755           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
133756           pInfo->aMatchinfo[0] = (u32)nDoc;
133757         }
133758         break;
133759
133760       case FTS3_MATCHINFO_AVGLENGTH:
133761         if( bGlobal ){
133762           sqlite3_int64 nDoc;     /* Number of rows in table */
133763           const char *a;          /* Aggregate column length array */
133764
133765           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
133766           if( rc==SQLITE_OK ){
133767             int iCol;
133768             for(iCol=0; iCol<pInfo->nCol; iCol++){
133769               u32 iVal;
133770               sqlite3_int64 nToken;
133771               a += sqlite3Fts3GetVarint(a, &nToken);
133772               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
133773               pInfo->aMatchinfo[iCol] = iVal;
133774             }
133775           }
133776         }
133777         break;
133778
133779       case FTS3_MATCHINFO_LENGTH: {
133780         sqlite3_stmt *pSelectDocsize = 0;
133781         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
133782         if( rc==SQLITE_OK ){
133783           int iCol;
133784           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
133785           for(iCol=0; iCol<pInfo->nCol; iCol++){
133786             sqlite3_int64 nToken;
133787             a += sqlite3Fts3GetVarint(a, &nToken);
133788             pInfo->aMatchinfo[iCol] = (u32)nToken;
133789           }
133790         }
133791         sqlite3_reset(pSelectDocsize);
133792         break;
133793       }
133794
133795       case FTS3_MATCHINFO_LCS:
133796         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
133797         if( rc==SQLITE_OK ){
133798           rc = fts3MatchinfoLcs(pCsr, pInfo);
133799         }
133800         break;
133801
133802       default: {
133803         Fts3Expr *pExpr;
133804         assert( zArg[i]==FTS3_MATCHINFO_HITS );
133805         pExpr = pCsr->pExpr;
133806         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
133807         if( rc!=SQLITE_OK ) break;
133808         if( bGlobal ){
133809           if( pCsr->pDeferred ){
133810             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
133811             if( rc!=SQLITE_OK ) break;
133812           }
133813           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
133814           if( rc!=SQLITE_OK ) break;
133815         }
133816         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
133817         break;
133818       }
133819     }
133820
133821     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
133822   }
133823
133824   sqlite3_reset(pSelect);
133825   return rc;
133826 }
133827
133828
133829 /*
133830 ** Populate pCsr->aMatchinfo[] with data for the current row. The
133831 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
133832 */
133833 static int fts3GetMatchinfo(
133834   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
133835   const char *zArg                /* Second argument to matchinfo() function */
133836 ){
133837   MatchInfo sInfo;
133838   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133839   int rc = SQLITE_OK;
133840   int bGlobal = 0;                /* Collect 'global' stats as well as local */
133841
133842   memset(&sInfo, 0, sizeof(MatchInfo));
133843   sInfo.pCursor = pCsr;
133844   sInfo.nCol = pTab->nColumn;
133845
133846   /* If there is cached matchinfo() data, but the format string for the
133847   ** cache does not match the format string for this request, discard
133848   ** the cached data. */
133849   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
133850     assert( pCsr->aMatchinfo );
133851     sqlite3_free(pCsr->aMatchinfo);
133852     pCsr->zMatchinfo = 0;
133853     pCsr->aMatchinfo = 0;
133854   }
133855
133856   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
133857   ** matchinfo function has been called for this query. In this case
133858   ** allocate the array used to accumulate the matchinfo data and
133859   ** initialize those elements that are constant for every row.
133860   */
133861   if( pCsr->aMatchinfo==0 ){
133862     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
133863     int nArg;                     /* Bytes in zArg */
133864     int i;                        /* Used to iterate through zArg */
133865
133866     /* Determine the number of phrases in the query */
133867     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
133868     sInfo.nPhrase = pCsr->nPhrase;
133869
133870     /* Determine the number of integers in the buffer returned by this call. */
133871     for(i=0; zArg[i]; i++){
133872       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
133873     }
133874
133875     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
133876     nArg = (int)strlen(zArg);
133877     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
133878     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
133879
133880     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
133881     pCsr->nMatchinfo = nMatchinfo;
133882     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
133883     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
133884     pCsr->isMatchinfoNeeded = 1;
133885     bGlobal = 1;
133886   }
133887
133888   sInfo.aMatchinfo = pCsr->aMatchinfo;
133889   sInfo.nPhrase = pCsr->nPhrase;
133890   if( pCsr->isMatchinfoNeeded ){
133891     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
133892     pCsr->isMatchinfoNeeded = 0;
133893   }
133894
133895   return rc;
133896 }
133897
133898 /*
133899 ** Implementation of snippet() function.
133900 */
133901 SQLITE_PRIVATE void sqlite3Fts3Snippet(
133902   sqlite3_context *pCtx,          /* SQLite function call context */
133903   Fts3Cursor *pCsr,               /* Cursor object */
133904   const char *zStart,             /* Snippet start text - "<b>" */
133905   const char *zEnd,               /* Snippet end text - "</b>" */
133906   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
133907   int iCol,                       /* Extract snippet from this column */
133908   int nToken                      /* Approximate number of tokens in snippet */
133909 ){
133910   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
133911   int rc = SQLITE_OK;
133912   int i;
133913   StrBuffer res = {0, 0, 0};
133914
133915   /* The returned text includes up to four fragments of text extracted from
133916   ** the data in the current row. The first iteration of the for(...) loop
133917   ** below attempts to locate a single fragment of text nToken tokens in
133918   ** size that contains at least one instance of all phrases in the query
133919   ** expression that appear in the current row. If such a fragment of text
133920   ** cannot be found, the second iteration of the loop attempts to locate
133921   ** a pair of fragments, and so on.
133922   */
133923   int nSnippet = 0;               /* Number of fragments in this snippet */
133924   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
133925   int nFToken = -1;               /* Number of tokens in each fragment */
133926
133927   if( !pCsr->pExpr ){
133928     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
133929     return;
133930   }
133931
133932   for(nSnippet=1; 1; nSnippet++){
133933
133934     int iSnip;                    /* Loop counter 0..nSnippet-1 */
133935     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
133936     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
133937
133938     if( nToken>=0 ){
133939       nFToken = (nToken+nSnippet-1) / nSnippet;
133940     }else{
133941       nFToken = -1 * nToken;
133942     }
133943
133944     for(iSnip=0; iSnip<nSnippet; iSnip++){
133945       int iBestScore = -1;        /* Best score of columns checked so far */
133946       int iRead;                  /* Used to iterate through columns */
133947       SnippetFragment *pFragment = &aSnippet[iSnip];
133948
133949       memset(pFragment, 0, sizeof(*pFragment));
133950
133951       /* Loop through all columns of the table being considered for snippets.
133952       ** If the iCol argument to this function was negative, this means all
133953       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
133954       */
133955       for(iRead=0; iRead<pTab->nColumn; iRead++){
133956         SnippetFragment sF = {0, 0, 0, 0};
133957         int iS;
133958         if( iCol>=0 && iRead!=iCol ) continue;
133959
133960         /* Find the best snippet of nFToken tokens in column iRead. */
133961         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
133962         if( rc!=SQLITE_OK ){
133963           goto snippet_out;
133964         }
133965         if( iS>iBestScore ){
133966           *pFragment = sF;
133967           iBestScore = iS;
133968         }
133969       }
133970
133971       mCovered |= pFragment->covered;
133972     }
133973
133974     /* If all query phrases seen by fts3BestSnippet() are present in at least
133975     ** one of the nSnippet snippet fragments, break out of the loop.
133976     */
133977     assert( (mCovered&mSeen)==mCovered );
133978     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
133979   }
133980
133981   assert( nFToken>0 );
133982
133983   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
133984     rc = fts3SnippetText(pCsr, &aSnippet[i],
133985         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
133986     );
133987   }
133988
133989  snippet_out:
133990   sqlite3Fts3SegmentsClose(pTab);
133991   if( rc!=SQLITE_OK ){
133992     sqlite3_result_error_code(pCtx, rc);
133993     sqlite3_free(res.z);
133994   }else{
133995     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
133996   }
133997 }
133998
133999
134000 typedef struct TermOffset TermOffset;
134001 typedef struct TermOffsetCtx TermOffsetCtx;
134002
134003 struct TermOffset {
134004   char *pList;                    /* Position-list */
134005   int iPos;                       /* Position just read from pList */
134006   int iOff;                       /* Offset of this term from read positions */
134007 };
134008
134009 struct TermOffsetCtx {
134010   Fts3Cursor *pCsr;
134011   int iCol;                       /* Column of table to populate aTerm for */
134012   int iTerm;
134013   sqlite3_int64 iDocid;
134014   TermOffset *aTerm;
134015 };
134016
134017 /*
134018 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
134019 */
134020 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
134021   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
134022   int nTerm;                      /* Number of tokens in phrase */
134023   int iTerm;                      /* For looping through nTerm phrase terms */
134024   char *pList;                    /* Pointer to position list for phrase */
134025   int iPos = 0;                   /* First position in position-list */
134026   int rc;
134027
134028   UNUSED_PARAMETER(iPhrase);
134029   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
134030   nTerm = pExpr->pPhrase->nToken;
134031   if( pList ){
134032     fts3GetDeltaPosition(&pList, &iPos);
134033     assert( iPos>=0 );
134034   }
134035
134036   for(iTerm=0; iTerm<nTerm; iTerm++){
134037     TermOffset *pT = &p->aTerm[p->iTerm++];
134038     pT->iOff = nTerm-iTerm-1;
134039     pT->pList = pList;
134040     pT->iPos = iPos;
134041   }
134042
134043   return rc;
134044 }
134045
134046 /*
134047 ** Implementation of offsets() function.
134048 */
134049 SQLITE_PRIVATE void sqlite3Fts3Offsets(
134050   sqlite3_context *pCtx,          /* SQLite function call context */
134051   Fts3Cursor *pCsr                /* Cursor object */
134052 ){
134053   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134054   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
134055   int rc;                         /* Return Code */
134056   int nToken;                     /* Number of tokens in query */
134057   int iCol;                       /* Column currently being processed */
134058   StrBuffer res = {0, 0, 0};      /* Result string */
134059   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
134060
134061   if( !pCsr->pExpr ){
134062     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
134063     return;
134064   }
134065
134066   memset(&sCtx, 0, sizeof(sCtx));
134067   assert( pCsr->isRequireSeek==0 );
134068
134069   /* Count the number of terms in the query */
134070   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
134071   if( rc!=SQLITE_OK ) goto offsets_out;
134072
134073   /* Allocate the array of TermOffset iterators. */
134074   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
134075   if( 0==sCtx.aTerm ){
134076     rc = SQLITE_NOMEM;
134077     goto offsets_out;
134078   }
134079   sCtx.iDocid = pCsr->iPrevId;
134080   sCtx.pCsr = pCsr;
134081
134082   /* Loop through the table columns, appending offset information to
134083   ** string-buffer res for each column.
134084   */
134085   for(iCol=0; iCol<pTab->nColumn; iCol++){
134086     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
134087     const char *ZDUMMY;           /* Dummy argument used with xNext() */
134088     int NDUMMY = 0;               /* Dummy argument used with xNext() */
134089     int iStart = 0;
134090     int iEnd = 0;
134091     int iCurrent = 0;
134092     const char *zDoc;
134093     int nDoc;
134094
134095     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
134096     ** no way that this operation can fail, so the return code from
134097     ** fts3ExprIterate() can be discarded.
134098     */
134099     sCtx.iCol = iCol;
134100     sCtx.iTerm = 0;
134101     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
134102
134103     /* Retreive the text stored in column iCol. If an SQL NULL is stored
134104     ** in column iCol, jump immediately to the next iteration of the loop.
134105     ** If an OOM occurs while retrieving the data (this can happen if SQLite
134106     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
134107     ** to the caller.
134108     */
134109     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
134110     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
134111     if( zDoc==0 ){
134112       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
134113         continue;
134114       }
134115       rc = SQLITE_NOMEM;
134116       goto offsets_out;
134117     }
134118
134119     /* Initialize a tokenizer iterator to iterate through column iCol. */
134120     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
134121         zDoc, nDoc, &pC
134122     );
134123     if( rc!=SQLITE_OK ) goto offsets_out;
134124
134125     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
134126     while( rc==SQLITE_OK ){
134127       int i;                      /* Used to loop through terms */
134128       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
134129       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
134130
134131       for(i=0; i<nToken; i++){
134132         TermOffset *pT = &sCtx.aTerm[i];
134133         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
134134           iMinPos = pT->iPos-pT->iOff;
134135           pTerm = pT;
134136         }
134137       }
134138
134139       if( !pTerm ){
134140         /* All offsets for this column have been gathered. */
134141         rc = SQLITE_DONE;
134142       }else{
134143         assert( iCurrent<=iMinPos );
134144         if( 0==(0xFE&*pTerm->pList) ){
134145           pTerm->pList = 0;
134146         }else{
134147           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
134148         }
134149         while( rc==SQLITE_OK && iCurrent<iMinPos ){
134150           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
134151         }
134152         if( rc==SQLITE_OK ){
134153           char aBuffer[64];
134154           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
134155               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
134156           );
134157           rc = fts3StringAppend(&res, aBuffer, -1);
134158         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
134159           rc = FTS_CORRUPT_VTAB;
134160         }
134161       }
134162     }
134163     if( rc==SQLITE_DONE ){
134164       rc = SQLITE_OK;
134165     }
134166
134167     pMod->xClose(pC);
134168     if( rc!=SQLITE_OK ) goto offsets_out;
134169   }
134170
134171  offsets_out:
134172   sqlite3_free(sCtx.aTerm);
134173   assert( rc!=SQLITE_DONE );
134174   sqlite3Fts3SegmentsClose(pTab);
134175   if( rc!=SQLITE_OK ){
134176     sqlite3_result_error_code(pCtx,  rc);
134177     sqlite3_free(res.z);
134178   }else{
134179     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
134180   }
134181   return;
134182 }
134183
134184 /*
134185 ** Implementation of matchinfo() function.
134186 */
134187 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
134188   sqlite3_context *pContext,      /* Function call context */
134189   Fts3Cursor *pCsr,               /* FTS3 table cursor */
134190   const char *zArg                /* Second arg to matchinfo() function */
134191 ){
134192   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134193   int rc;
134194   int i;
134195   const char *zFormat;
134196
134197   if( zArg ){
134198     for(i=0; zArg[i]; i++){
134199       char *zErr = 0;
134200       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
134201         sqlite3_result_error(pContext, zErr, -1);
134202         sqlite3_free(zErr);
134203         return;
134204       }
134205     }
134206     zFormat = zArg;
134207   }else{
134208     zFormat = FTS3_MATCHINFO_DEFAULT;
134209   }
134210
134211   if( !pCsr->pExpr ){
134212     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
134213     return;
134214   }
134215
134216   /* Retrieve matchinfo() data. */
134217   rc = fts3GetMatchinfo(pCsr, zFormat);
134218   sqlite3Fts3SegmentsClose(pTab);
134219
134220   if( rc!=SQLITE_OK ){
134221     sqlite3_result_error_code(pContext, rc);
134222   }else{
134223     int n = pCsr->nMatchinfo * sizeof(u32);
134224     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
134225   }
134226 }
134227
134228 #endif
134229
134230 /************** End of fts3_snippet.c ****************************************/
134231 /************** Begin file fts3_unicode.c ************************************/
134232 /*
134233 ** 2012 May 24
134234 **
134235 ** The author disclaims copyright to this source code.  In place of
134236 ** a legal notice, here is a blessing:
134237 **
134238 **    May you do good and not evil.
134239 **    May you find forgiveness for yourself and forgive others.
134240 **    May you share freely, never taking more than you give.
134241 **
134242 ******************************************************************************
134243 **
134244 ** Implementation of the "unicode" full-text-search tokenizer.
134245 */
134246
134247 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
134248
134249 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
134250
134251 /* #include <assert.h> */
134252 /* #include <stdlib.h> */
134253 /* #include <stdio.h> */
134254 /* #include <string.h> */
134255
134256
134257 /*
134258 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
134259 ** from the sqlite3 source file utf.c. If this file is compiled as part
134260 ** of the amalgamation, they are not required.
134261 */
134262 #ifndef SQLITE_AMALGAMATION
134263
134264 static const unsigned char sqlite3Utf8Trans1[] = {
134265   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
134266   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
134267   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
134268   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
134269   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
134270   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
134271   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
134272   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
134273 };
134274
134275 #define READ_UTF8(zIn, zTerm, c)                           \
134276   c = *(zIn++);                                            \
134277   if( c>=0xc0 ){                                           \
134278     c = sqlite3Utf8Trans1[c-0xc0];                         \
134279     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
134280       c = (c<<6) + (0x3f & *(zIn++));                      \
134281     }                                                      \
134282     if( c<0x80                                             \
134283         || (c&0xFFFFF800)==0xD800                          \
134284         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
134285   }
134286
134287 #define WRITE_UTF8(zOut, c) {                          \
134288   if( c<0x00080 ){                                     \
134289     *zOut++ = (u8)(c&0xFF);                            \
134290   }                                                    \
134291   else if( c<0x00800 ){                                \
134292     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
134293     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
134294   }                                                    \
134295   else if( c<0x10000 ){                                \
134296     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
134297     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
134298     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
134299   }else{                                               \
134300     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
134301     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
134302     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
134303     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
134304   }                                                    \
134305 }
134306
134307 #endif /* ifndef SQLITE_AMALGAMATION */
134308
134309 typedef struct unicode_tokenizer unicode_tokenizer;
134310 typedef struct unicode_cursor unicode_cursor;
134311
134312 struct unicode_tokenizer {
134313   sqlite3_tokenizer base;
134314   int bRemoveDiacritic;
134315   int nException;
134316   int *aiException;
134317 };
134318
134319 struct unicode_cursor {
134320   sqlite3_tokenizer_cursor base;
134321   const unsigned char *aInput;    /* Input text being tokenized */
134322   int nInput;                     /* Size of aInput[] in bytes */
134323   int iOff;                       /* Current offset within aInput[] */
134324   int iToken;                     /* Index of next token to be returned */
134325   char *zToken;                   /* storage for current token */
134326   int nAlloc;                     /* space allocated at zToken */
134327 };
134328
134329
134330 /*
134331 ** Destroy a tokenizer allocated by unicodeCreate().
134332 */
134333 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
134334   if( pTokenizer ){
134335     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
134336     sqlite3_free(p->aiException);
134337     sqlite3_free(p);
134338   }
134339   return SQLITE_OK;
134340 }
134341
134342 /*
134343 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
134344 ** statement has specified that the tokenizer for this table shall consider
134345 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
134346 ** token characters (if bAlnum==1).
134347 **
134348 ** For each codepoint in the zIn/nIn string, this function checks if the
134349 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
134350 ** If so, no action is taken. Otherwise, the codepoint is added to the
134351 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
134352 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
134353 ** codepoints in the aiException[] array.
134354 **
134355 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
134356 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
134357 ** It is not possible to change the behaviour of the tokenizer with respect
134358 ** to these codepoints.
134359 */
134360 static int unicodeAddExceptions(
134361   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
134362   int bAlnum,                     /* Replace Isalnum() return value with this */
134363   const char *zIn,                /* Array of characters to make exceptions */
134364   int nIn                         /* Length of z in bytes */
134365 ){
134366   const unsigned char *z = (const unsigned char *)zIn;
134367   const unsigned char *zTerm = &z[nIn];
134368   int iCode;
134369   int nEntry = 0;
134370
134371   assert( bAlnum==0 || bAlnum==1 );
134372
134373   while( z<zTerm ){
134374     READ_UTF8(z, zTerm, iCode);
134375     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
134376     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
134377      && sqlite3FtsUnicodeIsdiacritic(iCode)==0
134378     ){
134379       nEntry++;
134380     }
134381   }
134382
134383   if( nEntry ){
134384     int *aNew;                    /* New aiException[] array */
134385     int nNew;                     /* Number of valid entries in array aNew[] */
134386
134387     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
134388     if( aNew==0 ) return SQLITE_NOMEM;
134389     nNew = p->nException;
134390
134391     z = (const unsigned char *)zIn;
134392     while( z<zTerm ){
134393       READ_UTF8(z, zTerm, iCode);
134394       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
134395        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
134396       ){
134397         int i, j;
134398         for(i=0; i<nNew && aNew[i]<iCode; i++);
134399         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
134400         aNew[i] = iCode;
134401         nNew++;
134402       }
134403     }
134404     p->aiException = aNew;
134405     p->nException = nNew;
134406   }
134407
134408   return SQLITE_OK;
134409 }
134410
134411 /*
134412 ** Return true if the p->aiException[] array contains the value iCode.
134413 */
134414 static int unicodeIsException(unicode_tokenizer *p, int iCode){
134415   if( p->nException>0 ){
134416     int *a = p->aiException;
134417     int iLo = 0;
134418     int iHi = p->nException-1;
134419
134420     while( iHi>=iLo ){
134421       int iTest = (iHi + iLo) / 2;
134422       if( iCode==a[iTest] ){
134423         return 1;
134424       }else if( iCode>a[iTest] ){
134425         iLo = iTest+1;
134426       }else{
134427         iHi = iTest-1;
134428       }
134429     }
134430   }
134431
134432   return 0;
134433 }
134434
134435 /*
134436 ** Return true if, for the purposes of tokenization, codepoint iCode is
134437 ** considered a token character (not a separator).
134438 */
134439 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
134440   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
134441   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
134442 }
134443
134444 /*
134445 ** Create a new tokenizer instance.
134446 */
134447 static int unicodeCreate(
134448   int nArg,                       /* Size of array argv[] */
134449   const char * const *azArg,      /* Tokenizer creation arguments */
134450   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
134451 ){
134452   unicode_tokenizer *pNew;        /* New tokenizer object */
134453   int i;
134454   int rc = SQLITE_OK;
134455
134456   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
134457   if( pNew==NULL ) return SQLITE_NOMEM;
134458   memset(pNew, 0, sizeof(unicode_tokenizer));
134459   pNew->bRemoveDiacritic = 1;
134460
134461   for(i=0; rc==SQLITE_OK && i<nArg; i++){
134462     const char *z = azArg[i];
134463     int n = strlen(z);
134464
134465     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
134466       pNew->bRemoveDiacritic = 1;
134467     }
134468     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
134469       pNew->bRemoveDiacritic = 0;
134470     }
134471     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
134472       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
134473     }
134474     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
134475       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
134476     }
134477     else{
134478       /* Unrecognized argument */
134479       rc  = SQLITE_ERROR;
134480     }
134481   }
134482
134483   if( rc!=SQLITE_OK ){
134484     unicodeDestroy((sqlite3_tokenizer *)pNew);
134485     pNew = 0;
134486   }
134487   *pp = (sqlite3_tokenizer *)pNew;
134488   return rc;
134489 }
134490
134491 /*
134492 ** Prepare to begin tokenizing a particular string.  The input
134493 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
134494 ** used to incrementally tokenize this string is returned in
134495 ** *ppCursor.
134496 */
134497 static int unicodeOpen(
134498   sqlite3_tokenizer *p,           /* The tokenizer */
134499   const char *aInput,             /* Input string */
134500   int nInput,                     /* Size of string aInput in bytes */
134501   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
134502 ){
134503   unicode_cursor *pCsr;
134504
134505   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
134506   if( pCsr==0 ){
134507     return SQLITE_NOMEM;
134508   }
134509   memset(pCsr, 0, sizeof(unicode_cursor));
134510
134511   pCsr->aInput = (const unsigned char *)aInput;
134512   if( aInput==0 ){
134513     pCsr->nInput = 0;
134514   }else if( nInput<0 ){
134515     pCsr->nInput = (int)strlen(aInput);
134516   }else{
134517     pCsr->nInput = nInput;
134518   }
134519
134520   *pp = &pCsr->base;
134521   UNUSED_PARAMETER(p);
134522   return SQLITE_OK;
134523 }
134524
134525 /*
134526 ** Close a tokenization cursor previously opened by a call to
134527 ** simpleOpen() above.
134528 */
134529 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
134530   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
134531   sqlite3_free(pCsr->zToken);
134532   sqlite3_free(pCsr);
134533   return SQLITE_OK;
134534 }
134535
134536 /*
134537 ** Extract the next token from a tokenization cursor.  The cursor must
134538 ** have been opened by a prior call to simpleOpen().
134539 */
134540 static int unicodeNext(
134541   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
134542   const char **paToken,           /* OUT: Token text */
134543   int *pnToken,                   /* OUT: Number of bytes at *paToken */
134544   int *piStart,                   /* OUT: Starting offset of token */
134545   int *piEnd,                     /* OUT: Ending offset of token */
134546   int *piPos                      /* OUT: Position integer of token */
134547 ){
134548   unicode_cursor *pCsr = (unicode_cursor *)pC;
134549   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
134550   int iCode;
134551   char *zOut;
134552   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
134553   const unsigned char *zStart = z;
134554   const unsigned char *zEnd;
134555   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
134556
134557   /* Scan past any delimiter characters before the start of the next token.
134558   ** Return SQLITE_DONE early if this takes us all the way to the end of
134559   ** the input.  */
134560   while( z<zTerm ){
134561     READ_UTF8(z, zTerm, iCode);
134562     if( unicodeIsAlnum(p, iCode) ) break;
134563     zStart = z;
134564   }
134565   if( zStart>=zTerm ) return SQLITE_DONE;
134566
134567   zOut = pCsr->zToken;
134568   do {
134569     int iOut;
134570
134571     /* Grow the output buffer if required. */
134572     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
134573       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
134574       if( !zNew ) return SQLITE_NOMEM;
134575       zOut = &zNew[zOut - pCsr->zToken];
134576       pCsr->zToken = zNew;
134577       pCsr->nAlloc += 64;
134578     }
134579
134580     /* Write the folded case of the last character read to the output */
134581     zEnd = z;
134582     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
134583     if( iOut ){
134584       WRITE_UTF8(zOut, iOut);
134585     }
134586
134587     /* If the cursor is not at EOF, read the next character */
134588     if( z>=zTerm ) break;
134589     READ_UTF8(z, zTerm, iCode);
134590   }while( unicodeIsAlnum(p, iCode)
134591        || sqlite3FtsUnicodeIsdiacritic(iCode)
134592   );
134593
134594   /* Set the output variables and return. */
134595   pCsr->iOff = (z - pCsr->aInput);
134596   *paToken = pCsr->zToken;
134597   *pnToken = zOut - pCsr->zToken;
134598   *piStart = (zStart - pCsr->aInput);
134599   *piEnd = (zEnd - pCsr->aInput);
134600   *piPos = pCsr->iToken++;
134601   return SQLITE_OK;
134602 }
134603
134604 /*
134605 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
134606 ** structure for the unicode tokenizer.
134607 */
134608 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
134609   static const sqlite3_tokenizer_module module = {
134610     0,
134611     unicodeCreate,
134612     unicodeDestroy,
134613     unicodeOpen,
134614     unicodeClose,
134615     unicodeNext,
134616     0,
134617   };
134618   *ppModule = &module;
134619 }
134620
134621 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
134622 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
134623
134624 /************** End of fts3_unicode.c ****************************************/
134625 /************** Begin file fts3_unicode2.c ***********************************/
134626 /*
134627 ** 2012 May 25
134628 **
134629 ** The author disclaims copyright to this source code.  In place of
134630 ** a legal notice, here is a blessing:
134631 **
134632 **    May you do good and not evil.
134633 **    May you find forgiveness for yourself and forgive others.
134634 **    May you share freely, never taking more than you give.
134635 **
134636 ******************************************************************************
134637 */
134638
134639 /*
134640 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
134641 */
134642
134643 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
134644 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
134645
134646 /* #include <assert.h> */
134647
134648 /*
134649 ** Return true if the argument corresponds to a unicode codepoint
134650 ** classified as either a letter or a number. Otherwise false.
134651 **
134652 ** The results are undefined if the value passed to this function
134653 ** is less than zero.
134654 */
134655 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
134656   /* Each unsigned integer in the following array corresponds to a contiguous
134657   ** range of unicode codepoints that are not either letters or numbers (i.e.
134658   ** codepoints for which this function should return 0).
134659   **
134660   ** The most significant 22 bits in each 32-bit value contain the first
134661   ** codepoint in the range. The least significant 10 bits are used to store
134662   ** the size of the range (always at least 1). In other words, the value
134663   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
134664   ** C. It is not possible to represent a range larger than 1023 codepoints
134665   ** using this format.
134666   */
134667   const static unsigned int aEntry[] = {
134668     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
134669     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
134670     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
134671     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
134672     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
134673     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
134674     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
134675     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
134676     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
134677     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
134678     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
134679     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
134680     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
134681     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
134682     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
134683     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
134684     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
134685     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
134686     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
134687     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
134688     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
134689     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
134690     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
134691     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
134692     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
134693     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
134694     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
134695     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
134696     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
134697     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
134698     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
134699     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
134700     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
134701     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
134702     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
134703     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
134704     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
134705     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
134706     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
134707     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
134708     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
134709     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
134710     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
134711     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
134712     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
134713     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
134714     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
134715     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
134716     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
134717     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
134718     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
134719     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
134720     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
134721     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
134722     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
134723     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
134724     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
134725     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
134726     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
134727     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
134728     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
134729     0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
134730     0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
134731     0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
134732     0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
134733     0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
134734     0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
134735     0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
134736     0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
134737     0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
134738     0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
134739     0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
134740     0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
134741     0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
134742     0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
134743     0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
134744     0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
134745     0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
134746     0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
134747     0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
134748     0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
134749     0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
134750     0x43FFF401,
134751   };
134752   static const unsigned int aAscii[4] = {
134753     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
134754   };
134755
134756   if( c<128 ){
134757     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
134758   }else if( c<(1<<22) ){
134759     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
134760     int iRes;
134761     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
134762     int iLo = 0;
134763     while( iHi>=iLo ){
134764       int iTest = (iHi + iLo) / 2;
134765       if( key >= aEntry[iTest] ){
134766         iRes = iTest;
134767         iLo = iTest+1;
134768       }else{
134769         iHi = iTest-1;
134770       }
134771     }
134772     assert( aEntry[0]<key );
134773     assert( key>=aEntry[iRes] );
134774     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
134775   }
134776   return 1;
134777 }
134778
134779
134780 /*
134781 ** If the argument is a codepoint corresponding to a lowercase letter
134782 ** in the ASCII range with a diacritic added, return the codepoint
134783 ** of the ASCII letter only. For example, if passed 235 - "LATIN
134784 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
134785 ** E"). The resuls of passing a codepoint that corresponds to an
134786 ** uppercase letter are undefined.
134787 */
134788 static int remove_diacritic(int c){
134789   unsigned short aDia[] = {
134790         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
134791      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
134792      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
134793      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
134794      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
134795      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
134796      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
134797      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
134798     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
134799     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
134800     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
134801     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
134802     62924, 63050, 63082, 63274, 63390,
134803   };
134804   char aChar[] = {
134805     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
134806     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
134807     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
134808     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
134809     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
134810     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
134811     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
134812     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
134813     'e',  'i',  'o',  'u',  'y',
134814   };
134815
134816   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
134817   int iRes = 0;
134818   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
134819   int iLo = 0;
134820   while( iHi>=iLo ){
134821     int iTest = (iHi + iLo) / 2;
134822     if( key >= aDia[iTest] ){
134823       iRes = iTest;
134824       iLo = iTest+1;
134825     }else{
134826       iHi = iTest-1;
134827     }
134828   }
134829   assert( key>=aDia[iRes] );
134830   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
134831 };
134832
134833
134834 /*
134835 ** Return true if the argument interpreted as a unicode codepoint
134836 ** is a diacritical modifier character.
134837 */
134838 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
134839   unsigned int mask0 = 0x08029FDF;
134840   unsigned int mask1 = 0x000361F8;
134841   if( c<768 || c>817 ) return 0;
134842   return (c < 768+32) ?
134843       (mask0 & (1 << (c-768))) :
134844       (mask1 & (1 << (c-768-32)));
134845 }
134846
134847
134848 /*
134849 ** Interpret the argument as a unicode codepoint. If the codepoint
134850 ** is an upper case character that has a lower case equivalent,
134851 ** return the codepoint corresponding to the lower case version.
134852 ** Otherwise, return a copy of the argument.
134853 **
134854 ** The results are undefined if the value passed to this function
134855 ** is less than zero.
134856 */
134857 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
134858   /* Each entry in the following array defines a rule for folding a range
134859   ** of codepoints to lower case. The rule applies to a range of nRange
134860   ** codepoints starting at codepoint iCode.
134861   **
134862   ** If the least significant bit in flags is clear, then the rule applies
134863   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
134864   ** need to be folded). Or, if it is set, then the rule only applies to
134865   ** every second codepoint in the range, starting with codepoint C.
134866   **
134867   ** The 7 most significant bits in flags are an index into the aiOff[]
134868   ** array. If a specific codepoint C does require folding, then its lower
134869   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
134870   **
134871   ** The contents of this array are generated by parsing the CaseFolding.txt
134872   ** file distributed as part of the "Unicode Character Database". See
134873   ** http://www.unicode.org for details.
134874   */
134875   static const struct TableEntry {
134876     unsigned short iCode;
134877     unsigned char flags;
134878     unsigned char nRange;
134879   } aEntry[] = {
134880     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
134881     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
134882     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
134883     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
134884     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
134885     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
134886     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
134887     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
134888     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
134889     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
134890     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
134891     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
134892     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
134893     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
134894     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
134895     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
134896     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
134897     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
134898     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
134899     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
134900     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
134901     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
134902     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
134903     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
134904     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
134905     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
134906     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
134907     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
134908     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
134909     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
134910     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
134911     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
134912     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
134913     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
134914     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
134915     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
134916     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
134917     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
134918     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
134919     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
134920     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
134921     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
134922     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
134923     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
134924     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
134925     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
134926     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
134927     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
134928     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
134929     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
134930     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
134931     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
134932     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
134933     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
134934     {65313, 14, 26},
134935   };
134936   static const unsigned short aiOff[] = {
134937    1,     2,     8,     15,    16,    26,    28,    32,
134938    37,    38,    40,    48,    63,    64,    69,    71,
134939    79,    80,    116,   202,   203,   205,   206,   207,
134940    209,   210,   211,   213,   214,   217,   218,   219,
134941    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
134942    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
134943    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
134944    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
134945    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
134946    65514, 65521, 65527, 65528, 65529,
134947   };
134948
134949   int ret = c;
134950
134951   assert( c>=0 );
134952   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
134953
134954   if( c<128 ){
134955     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
134956   }else if( c<65536 ){
134957     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
134958     int iLo = 0;
134959     int iRes = -1;
134960
134961     while( iHi>=iLo ){
134962       int iTest = (iHi + iLo) / 2;
134963       int cmp = (c - aEntry[iTest].iCode);
134964       if( cmp>=0 ){
134965         iRes = iTest;
134966         iLo = iTest+1;
134967       }else{
134968         iHi = iTest-1;
134969       }
134970     }
134971     assert( iRes<0 || c>=aEntry[iRes].iCode );
134972
134973     if( iRes>=0 ){
134974       const struct TableEntry *p = &aEntry[iRes];
134975       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
134976         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
134977         assert( ret>0 );
134978       }
134979     }
134980
134981     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
134982   }
134983
134984   else if( c>=66560 && c<66600 ){
134985     ret = c + 40;
134986   }
134987
134988   return ret;
134989 }
134990 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
134991 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
134992
134993 /************** End of fts3_unicode2.c ***************************************/
134994 /************** Begin file rtree.c *******************************************/
134995 /*
134996 ** 2001 September 15
134997 **
134998 ** The author disclaims copyright to this source code.  In place of
134999 ** a legal notice, here is a blessing:
135000 **
135001 **    May you do good and not evil.
135002 **    May you find forgiveness for yourself and forgive others.
135003 **    May you share freely, never taking more than you give.
135004 **
135005 *************************************************************************
135006 ** This file contains code for implementations of the r-tree and r*-tree
135007 ** algorithms packaged as an SQLite virtual table module.
135008 */
135009
135010 /*
135011 ** Database Format of R-Tree Tables
135012 ** --------------------------------
135013 **
135014 ** The data structure for a single virtual r-tree table is stored in three
135015 ** native SQLite tables declared as follows. In each case, the '%' character
135016 ** in the table name is replaced with the user-supplied name of the r-tree
135017 ** table.
135018 **
135019 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
135020 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
135021 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
135022 **
135023 ** The data for each node of the r-tree structure is stored in the %_node
135024 ** table. For each node that is not the root node of the r-tree, there is
135025 ** an entry in the %_parent table associating the node with its parent.
135026 ** And for each row of data in the table, there is an entry in the %_rowid
135027 ** table that maps from the entries rowid to the id of the node that it
135028 ** is stored on.
135029 **
135030 ** The root node of an r-tree always exists, even if the r-tree table is
135031 ** empty. The nodeno of the root node is always 1. All other nodes in the
135032 ** table must be the same size as the root node. The content of each node
135033 ** is formatted as follows:
135034 **
135035 **   1. If the node is the root node (node 1), then the first 2 bytes
135036 **      of the node contain the tree depth as a big-endian integer.
135037 **      For non-root nodes, the first 2 bytes are left unused.
135038 **
135039 **   2. The next 2 bytes contain the number of entries currently
135040 **      stored in the node.
135041 **
135042 **   3. The remainder of the node contains the node entries. Each entry
135043 **      consists of a single 8-byte integer followed by an even number
135044 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
135045 **      of a record. For internal nodes it is the node number of a
135046 **      child page.
135047 */
135048
135049 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
135050
135051 /*
135052 ** This file contains an implementation of a couple of different variants
135053 ** of the r-tree algorithm. See the README file for further details. The
135054 ** same data-structure is used for all, but the algorithms for insert and
135055 ** delete operations vary. The variants used are selected at compile time
135056 ** by defining the following symbols:
135057 */
135058
135059 /* Either, both or none of the following may be set to activate
135060 ** r*tree variant algorithms.
135061 */
135062 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
135063 #define VARIANT_RSTARTREE_REINSERT      1
135064
135065 /*
135066 ** Exactly one of the following must be set to 1.
135067 */
135068 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
135069 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
135070 #define VARIANT_RSTARTREE_SPLIT         1
135071
135072 #define VARIANT_GUTTMAN_SPLIT \
135073         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
135074
135075 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
135076   #define PickNext QuadraticPickNext
135077   #define PickSeeds QuadraticPickSeeds
135078   #define AssignCells splitNodeGuttman
135079 #endif
135080 #if VARIANT_GUTTMAN_LINEAR_SPLIT
135081   #define PickNext LinearPickNext
135082   #define PickSeeds LinearPickSeeds
135083   #define AssignCells splitNodeGuttman
135084 #endif
135085 #if VARIANT_RSTARTREE_SPLIT
135086   #define AssignCells splitNodeStartree
135087 #endif
135088
135089 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
135090 # define NDEBUG 1
135091 #endif
135092
135093 #ifndef SQLITE_CORE
135094   SQLITE_EXTENSION_INIT1
135095 #else
135096 #endif
135097
135098 /* #include <string.h> */
135099 /* #include <assert.h> */
135100
135101 #ifndef SQLITE_AMALGAMATION
135102 #include "sqlite3rtree.h"
135103 typedef sqlite3_int64 i64;
135104 typedef unsigned char u8;
135105 typedef unsigned int u32;
135106 #endif
135107
135108 /*  The following macro is used to suppress compiler warnings.
135109 */
135110 #ifndef UNUSED_PARAMETER
135111 # define UNUSED_PARAMETER(x) (void)(x)
135112 #endif
135113
135114 typedef struct Rtree Rtree;
135115 typedef struct RtreeCursor RtreeCursor;
135116 typedef struct RtreeNode RtreeNode;
135117 typedef struct RtreeCell RtreeCell;
135118 typedef struct RtreeConstraint RtreeConstraint;
135119 typedef struct RtreeMatchArg RtreeMatchArg;
135120 typedef struct RtreeGeomCallback RtreeGeomCallback;
135121 typedef union RtreeCoord RtreeCoord;
135122
135123 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
135124 #define RTREE_MAX_DIMENSIONS 5
135125
135126 /* Size of hash table Rtree.aHash. This hash table is not expected to
135127 ** ever contain very many entries, so a fixed number of buckets is
135128 ** used.
135129 */
135130 #define HASHSIZE 128
135131
135132 /*
135133 ** An rtree virtual-table object.
135134 */
135135 struct Rtree {
135136   sqlite3_vtab base;
135137   sqlite3 *db;                /* Host database connection */
135138   int iNodeSize;              /* Size in bytes of each node in the node table */
135139   int nDim;                   /* Number of dimensions */
135140   int nBytesPerCell;          /* Bytes consumed per cell */
135141   int iDepth;                 /* Current depth of the r-tree structure */
135142   char *zDb;                  /* Name of database containing r-tree table */
135143   char *zName;                /* Name of r-tree table */
135144   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
135145   int nBusy;                  /* Current number of users of this structure */
135146
135147   /* List of nodes removed during a CondenseTree operation. List is
135148   ** linked together via the pointer normally used for hash chains -
135149   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
135150   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
135151   */
135152   RtreeNode *pDeleted;
135153   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
135154
135155   /* Statements to read/write/delete a record from xxx_node */
135156   sqlite3_stmt *pReadNode;
135157   sqlite3_stmt *pWriteNode;
135158   sqlite3_stmt *pDeleteNode;
135159
135160   /* Statements to read/write/delete a record from xxx_rowid */
135161   sqlite3_stmt *pReadRowid;
135162   sqlite3_stmt *pWriteRowid;
135163   sqlite3_stmt *pDeleteRowid;
135164
135165   /* Statements to read/write/delete a record from xxx_parent */
135166   sqlite3_stmt *pReadParent;
135167   sqlite3_stmt *pWriteParent;
135168   sqlite3_stmt *pDeleteParent;
135169
135170   int eCoordType;
135171 };
135172
135173 /* Possible values for eCoordType: */
135174 #define RTREE_COORD_REAL32 0
135175 #define RTREE_COORD_INT32  1
135176
135177 /*
135178 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
135179 ** only deal with integer coordinates.  No floating point operations
135180 ** will be done.
135181 */
135182 #ifdef SQLITE_RTREE_INT_ONLY
135183   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
135184   typedef int RtreeValue;                  /* Low accuracy coordinate */
135185 #else
135186   typedef double RtreeDValue;              /* High accuracy coordinate */
135187   typedef float RtreeValue;                /* Low accuracy coordinate */
135188 #endif
135189
135190 /*
135191 ** The minimum number of cells allowed for a node is a third of the
135192 ** maximum. In Gutman's notation:
135193 **
135194 **     m = M/3
135195 **
135196 ** If an R*-tree "Reinsert" operation is required, the same number of
135197 ** cells are removed from the overfull node and reinserted into the tree.
135198 */
135199 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
135200 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
135201 #define RTREE_MAXCELLS 51
135202
135203 /*
135204 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
135205 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
135206 ** Therefore all non-root nodes must contain at least 3 entries. Since
135207 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
135208 ** 40 or less.
135209 */
135210 #define RTREE_MAX_DEPTH 40
135211
135212 /*
135213 ** An rtree cursor object.
135214 */
135215 struct RtreeCursor {
135216   sqlite3_vtab_cursor base;
135217   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
135218   int iCell;                        /* Index of current cell in pNode */
135219   int iStrategy;                    /* Copy of idxNum search parameter */
135220   int nConstraint;                  /* Number of entries in aConstraint */
135221   RtreeConstraint *aConstraint;     /* Search constraints. */
135222 };
135223
135224 union RtreeCoord {
135225   RtreeValue f;
135226   int i;
135227 };
135228
135229 /*
135230 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
135231 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
135232 ** variable pRtree points to the Rtree structure associated with the
135233 ** RtreeCoord.
135234 */
135235 #ifdef SQLITE_RTREE_INT_ONLY
135236 # define DCOORD(coord) ((RtreeDValue)coord.i)
135237 #else
135238 # define DCOORD(coord) (                           \
135239     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
135240       ((double)coord.f) :                           \
135241       ((double)coord.i)                             \
135242   )
135243 #endif
135244
135245 /*
135246 ** A search constraint.
135247 */
135248 struct RtreeConstraint {
135249   int iCoord;                     /* Index of constrained coordinate */
135250   int op;                         /* Constraining operation */
135251   RtreeDValue rValue;             /* Constraint value. */
135252   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
135253   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
135254 };
135255
135256 /* Possible values for RtreeConstraint.op */
135257 #define RTREE_EQ    0x41
135258 #define RTREE_LE    0x42
135259 #define RTREE_LT    0x43
135260 #define RTREE_GE    0x44
135261 #define RTREE_GT    0x45
135262 #define RTREE_MATCH 0x46
135263
135264 /*
135265 ** An rtree structure node.
135266 */
135267 struct RtreeNode {
135268   RtreeNode *pParent;               /* Parent node */
135269   i64 iNode;
135270   int nRef;
135271   int isDirty;
135272   u8 *zData;
135273   RtreeNode *pNext;                 /* Next node in this hash chain */
135274 };
135275 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
135276
135277 /*
135278 ** Structure to store a deserialized rtree record.
135279 */
135280 struct RtreeCell {
135281   i64 iRowid;
135282   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
135283 };
135284
135285
135286 /*
135287 ** Value for the first field of every RtreeMatchArg object. The MATCH
135288 ** operator tests that the first field of a blob operand matches this
135289 ** value to avoid operating on invalid blobs (which could cause a segfault).
135290 */
135291 #define RTREE_GEOMETRY_MAGIC 0x891245AB
135292
135293 /*
135294 ** An instance of this structure must be supplied as a blob argument to
135295 ** the right-hand-side of an SQL MATCH operator used to constrain an
135296 ** r-tree query.
135297 */
135298 struct RtreeMatchArg {
135299   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
135300   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
135301   void *pContext;
135302   int nParam;
135303   RtreeDValue aParam[1];
135304 };
135305
135306 /*
135307 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
135308 ** a single instance of the following structure is allocated. It is used
135309 ** as the context for the user-function created by by s_r_g_c(). The object
135310 ** is eventually deleted by the destructor mechanism provided by
135311 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
135312 ** the geometry callback function).
135313 */
135314 struct RtreeGeomCallback {
135315   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
135316   void *pContext;
135317 };
135318
135319 #ifndef MAX
135320 # define MAX(x,y) ((x) < (y) ? (y) : (x))
135321 #endif
135322 #ifndef MIN
135323 # define MIN(x,y) ((x) > (y) ? (y) : (x))
135324 #endif
135325
135326 /*
135327 ** Functions to deserialize a 16 bit integer, 32 bit real number and
135328 ** 64 bit integer. The deserialized value is returned.
135329 */
135330 static int readInt16(u8 *p){
135331   return (p[0]<<8) + p[1];
135332 }
135333 static void readCoord(u8 *p, RtreeCoord *pCoord){
135334   u32 i = (
135335     (((u32)p[0]) << 24) +
135336     (((u32)p[1]) << 16) +
135337     (((u32)p[2]) <<  8) +
135338     (((u32)p[3]) <<  0)
135339   );
135340   *(u32 *)pCoord = i;
135341 }
135342 static i64 readInt64(u8 *p){
135343   return (
135344     (((i64)p[0]) << 56) +
135345     (((i64)p[1]) << 48) +
135346     (((i64)p[2]) << 40) +
135347     (((i64)p[3]) << 32) +
135348     (((i64)p[4]) << 24) +
135349     (((i64)p[5]) << 16) +
135350     (((i64)p[6]) <<  8) +
135351     (((i64)p[7]) <<  0)
135352   );
135353 }
135354
135355 /*
135356 ** Functions to serialize a 16 bit integer, 32 bit real number and
135357 ** 64 bit integer. The value returned is the number of bytes written
135358 ** to the argument buffer (always 2, 4 and 8 respectively).
135359 */
135360 static int writeInt16(u8 *p, int i){
135361   p[0] = (i>> 8)&0xFF;
135362   p[1] = (i>> 0)&0xFF;
135363   return 2;
135364 }
135365 static int writeCoord(u8 *p, RtreeCoord *pCoord){
135366   u32 i;
135367   assert( sizeof(RtreeCoord)==4 );
135368   assert( sizeof(u32)==4 );
135369   i = *(u32 *)pCoord;
135370   p[0] = (i>>24)&0xFF;
135371   p[1] = (i>>16)&0xFF;
135372   p[2] = (i>> 8)&0xFF;
135373   p[3] = (i>> 0)&0xFF;
135374   return 4;
135375 }
135376 static int writeInt64(u8 *p, i64 i){
135377   p[0] = (i>>56)&0xFF;
135378   p[1] = (i>>48)&0xFF;
135379   p[2] = (i>>40)&0xFF;
135380   p[3] = (i>>32)&0xFF;
135381   p[4] = (i>>24)&0xFF;
135382   p[5] = (i>>16)&0xFF;
135383   p[6] = (i>> 8)&0xFF;
135384   p[7] = (i>> 0)&0xFF;
135385   return 8;
135386 }
135387
135388 /*
135389 ** Increment the reference count of node p.
135390 */
135391 static void nodeReference(RtreeNode *p){
135392   if( p ){
135393     p->nRef++;
135394   }
135395 }
135396
135397 /*
135398 ** Clear the content of node p (set all bytes to 0x00).
135399 */
135400 static void nodeZero(Rtree *pRtree, RtreeNode *p){
135401   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
135402   p->isDirty = 1;
135403 }
135404
135405 /*
135406 ** Given a node number iNode, return the corresponding key to use
135407 ** in the Rtree.aHash table.
135408 */
135409 static int nodeHash(i64 iNode){
135410   return (
135411     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
135412     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
135413   ) % HASHSIZE;
135414 }
135415
135416 /*
135417 ** Search the node hash table for node iNode. If found, return a pointer
135418 ** to it. Otherwise, return 0.
135419 */
135420 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
135421   RtreeNode *p;
135422   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
135423   return p;
135424 }
135425
135426 /*
135427 ** Add node pNode to the node hash table.
135428 */
135429 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
135430   int iHash;
135431   assert( pNode->pNext==0 );
135432   iHash = nodeHash(pNode->iNode);
135433   pNode->pNext = pRtree->aHash[iHash];
135434   pRtree->aHash[iHash] = pNode;
135435 }
135436
135437 /*
135438 ** Remove node pNode from the node hash table.
135439 */
135440 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
135441   RtreeNode **pp;
135442   if( pNode->iNode!=0 ){
135443     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
135444     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
135445     *pp = pNode->pNext;
135446     pNode->pNext = 0;
135447   }
135448 }
135449
135450 /*
135451 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
135452 ** indicating that node has not yet been assigned a node number. It is
135453 ** assigned a node number when nodeWrite() is called to write the
135454 ** node contents out to the database.
135455 */
135456 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
135457   RtreeNode *pNode;
135458   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
135459   if( pNode ){
135460     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
135461     pNode->zData = (u8 *)&pNode[1];
135462     pNode->nRef = 1;
135463     pNode->pParent = pParent;
135464     pNode->isDirty = 1;
135465     nodeReference(pParent);
135466   }
135467   return pNode;
135468 }
135469
135470 /*
135471 ** Obtain a reference to an r-tree node.
135472 */
135473 static int
135474 nodeAcquire(
135475   Rtree *pRtree,             /* R-tree structure */
135476   i64 iNode,                 /* Node number to load */
135477   RtreeNode *pParent,        /* Either the parent node or NULL */
135478   RtreeNode **ppNode         /* OUT: Acquired node */
135479 ){
135480   int rc;
135481   int rc2 = SQLITE_OK;
135482   RtreeNode *pNode;
135483
135484   /* Check if the requested node is already in the hash table. If so,
135485   ** increase its reference count and return it.
135486   */
135487   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
135488     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
135489     if( pParent && !pNode->pParent ){
135490       nodeReference(pParent);
135491       pNode->pParent = pParent;
135492     }
135493     pNode->nRef++;
135494     *ppNode = pNode;
135495     return SQLITE_OK;
135496   }
135497
135498   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
135499   rc = sqlite3_step(pRtree->pReadNode);
135500   if( rc==SQLITE_ROW ){
135501     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
135502     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
135503       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
135504       if( !pNode ){
135505         rc2 = SQLITE_NOMEM;
135506       }else{
135507         pNode->pParent = pParent;
135508         pNode->zData = (u8 *)&pNode[1];
135509         pNode->nRef = 1;
135510         pNode->iNode = iNode;
135511         pNode->isDirty = 0;
135512         pNode->pNext = 0;
135513         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
135514         nodeReference(pParent);
135515       }
135516     }
135517   }
135518   rc = sqlite3_reset(pRtree->pReadNode);
135519   if( rc==SQLITE_OK ) rc = rc2;
135520
135521   /* If the root node was just loaded, set pRtree->iDepth to the height
135522   ** of the r-tree structure. A height of zero means all data is stored on
135523   ** the root node. A height of one means the children of the root node
135524   ** are the leaves, and so on. If the depth as specified on the root node
135525   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
135526   */
135527   if( pNode && iNode==1 ){
135528     pRtree->iDepth = readInt16(pNode->zData);
135529     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
135530       rc = SQLITE_CORRUPT_VTAB;
135531     }
135532   }
135533
135534   /* If no error has occurred so far, check if the "number of entries"
135535   ** field on the node is too large. If so, set the return code to
135536   ** SQLITE_CORRUPT_VTAB.
135537   */
135538   if( pNode && rc==SQLITE_OK ){
135539     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
135540       rc = SQLITE_CORRUPT_VTAB;
135541     }
135542   }
135543
135544   if( rc==SQLITE_OK ){
135545     if( pNode!=0 ){
135546       nodeHashInsert(pRtree, pNode);
135547     }else{
135548       rc = SQLITE_CORRUPT_VTAB;
135549     }
135550     *ppNode = pNode;
135551   }else{
135552     sqlite3_free(pNode);
135553     *ppNode = 0;
135554   }
135555
135556   return rc;
135557 }
135558
135559 /*
135560 ** Overwrite cell iCell of node pNode with the contents of pCell.
135561 */
135562 static void nodeOverwriteCell(
135563   Rtree *pRtree,
135564   RtreeNode *pNode,
135565   RtreeCell *pCell,
135566   int iCell
135567 ){
135568   int ii;
135569   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
135570   p += writeInt64(p, pCell->iRowid);
135571   for(ii=0; ii<(pRtree->nDim*2); ii++){
135572     p += writeCoord(p, &pCell->aCoord[ii]);
135573   }
135574   pNode->isDirty = 1;
135575 }
135576
135577 /*
135578 ** Remove cell the cell with index iCell from node pNode.
135579 */
135580 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
135581   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
135582   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
135583   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
135584   memmove(pDst, pSrc, nByte);
135585   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
135586   pNode->isDirty = 1;
135587 }
135588
135589 /*
135590 ** Insert the contents of cell pCell into node pNode. If the insert
135591 ** is successful, return SQLITE_OK.
135592 **
135593 ** If there is not enough free space in pNode, return SQLITE_FULL.
135594 */
135595 static int
135596 nodeInsertCell(
135597   Rtree *pRtree,
135598   RtreeNode *pNode,
135599   RtreeCell *pCell
135600 ){
135601   int nCell;                    /* Current number of cells in pNode */
135602   int nMaxCell;                 /* Maximum number of cells for pNode */
135603
135604   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
135605   nCell = NCELL(pNode);
135606
135607   assert( nCell<=nMaxCell );
135608   if( nCell<nMaxCell ){
135609     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
135610     writeInt16(&pNode->zData[2], nCell+1);
135611     pNode->isDirty = 1;
135612   }
135613
135614   return (nCell==nMaxCell);
135615 }
135616
135617 /*
135618 ** If the node is dirty, write it out to the database.
135619 */
135620 static int
135621 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
135622   int rc = SQLITE_OK;
135623   if( pNode->isDirty ){
135624     sqlite3_stmt *p = pRtree->pWriteNode;
135625     if( pNode->iNode ){
135626       sqlite3_bind_int64(p, 1, pNode->iNode);
135627     }else{
135628       sqlite3_bind_null(p, 1);
135629     }
135630     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
135631     sqlite3_step(p);
135632     pNode->isDirty = 0;
135633     rc = sqlite3_reset(p);
135634     if( pNode->iNode==0 && rc==SQLITE_OK ){
135635       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
135636       nodeHashInsert(pRtree, pNode);
135637     }
135638   }
135639   return rc;
135640 }
135641
135642 /*
135643 ** Release a reference to a node. If the node is dirty and the reference
135644 ** count drops to zero, the node data is written to the database.
135645 */
135646 static int
135647 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
135648   int rc = SQLITE_OK;
135649   if( pNode ){
135650     assert( pNode->nRef>0 );
135651     pNode->nRef--;
135652     if( pNode->nRef==0 ){
135653       if( pNode->iNode==1 ){
135654         pRtree->iDepth = -1;
135655       }
135656       if( pNode->pParent ){
135657         rc = nodeRelease(pRtree, pNode->pParent);
135658       }
135659       if( rc==SQLITE_OK ){
135660         rc = nodeWrite(pRtree, pNode);
135661       }
135662       nodeHashDelete(pRtree, pNode);
135663       sqlite3_free(pNode);
135664     }
135665   }
135666   return rc;
135667 }
135668
135669 /*
135670 ** Return the 64-bit integer value associated with cell iCell of
135671 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
135672 ** an internal node, then the 64-bit integer is a child page number.
135673 */
135674 static i64 nodeGetRowid(
135675   Rtree *pRtree,
135676   RtreeNode *pNode,
135677   int iCell
135678 ){
135679   assert( iCell<NCELL(pNode) );
135680   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
135681 }
135682
135683 /*
135684 ** Return coordinate iCoord from cell iCell in node pNode.
135685 */
135686 static void nodeGetCoord(
135687   Rtree *pRtree,
135688   RtreeNode *pNode,
135689   int iCell,
135690   int iCoord,
135691   RtreeCoord *pCoord           /* Space to write result to */
135692 ){
135693   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
135694 }
135695
135696 /*
135697 ** Deserialize cell iCell of node pNode. Populate the structure pointed
135698 ** to by pCell with the results.
135699 */
135700 static void nodeGetCell(
135701   Rtree *pRtree,
135702   RtreeNode *pNode,
135703   int iCell,
135704   RtreeCell *pCell
135705 ){
135706   int ii;
135707   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
135708   for(ii=0; ii<pRtree->nDim*2; ii++){
135709     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
135710   }
135711 }
135712
135713
135714 /* Forward declaration for the function that does the work of
135715 ** the virtual table module xCreate() and xConnect() methods.
135716 */
135717 static int rtreeInit(
135718   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
135719 );
135720
135721 /*
135722 ** Rtree virtual table module xCreate method.
135723 */
135724 static int rtreeCreate(
135725   sqlite3 *db,
135726   void *pAux,
135727   int argc, const char *const*argv,
135728   sqlite3_vtab **ppVtab,
135729   char **pzErr
135730 ){
135731   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
135732 }
135733
135734 /*
135735 ** Rtree virtual table module xConnect method.
135736 */
135737 static int rtreeConnect(
135738   sqlite3 *db,
135739   void *pAux,
135740   int argc, const char *const*argv,
135741   sqlite3_vtab **ppVtab,
135742   char **pzErr
135743 ){
135744   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
135745 }
135746
135747 /*
135748 ** Increment the r-tree reference count.
135749 */
135750 static void rtreeReference(Rtree *pRtree){
135751   pRtree->nBusy++;
135752 }
135753
135754 /*
135755 ** Decrement the r-tree reference count. When the reference count reaches
135756 ** zero the structure is deleted.
135757 */
135758 static void rtreeRelease(Rtree *pRtree){
135759   pRtree->nBusy--;
135760   if( pRtree->nBusy==0 ){
135761     sqlite3_finalize(pRtree->pReadNode);
135762     sqlite3_finalize(pRtree->pWriteNode);
135763     sqlite3_finalize(pRtree->pDeleteNode);
135764     sqlite3_finalize(pRtree->pReadRowid);
135765     sqlite3_finalize(pRtree->pWriteRowid);
135766     sqlite3_finalize(pRtree->pDeleteRowid);
135767     sqlite3_finalize(pRtree->pReadParent);
135768     sqlite3_finalize(pRtree->pWriteParent);
135769     sqlite3_finalize(pRtree->pDeleteParent);
135770     sqlite3_free(pRtree);
135771   }
135772 }
135773
135774 /*
135775 ** Rtree virtual table module xDisconnect method.
135776 */
135777 static int rtreeDisconnect(sqlite3_vtab *pVtab){
135778   rtreeRelease((Rtree *)pVtab);
135779   return SQLITE_OK;
135780 }
135781
135782 /*
135783 ** Rtree virtual table module xDestroy method.
135784 */
135785 static int rtreeDestroy(sqlite3_vtab *pVtab){
135786   Rtree *pRtree = (Rtree *)pVtab;
135787   int rc;
135788   char *zCreate = sqlite3_mprintf(
135789     "DROP TABLE '%q'.'%q_node';"
135790     "DROP TABLE '%q'.'%q_rowid';"
135791     "DROP TABLE '%q'.'%q_parent';",
135792     pRtree->zDb, pRtree->zName,
135793     pRtree->zDb, pRtree->zName,
135794     pRtree->zDb, pRtree->zName
135795   );
135796   if( !zCreate ){
135797     rc = SQLITE_NOMEM;
135798   }else{
135799     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
135800     sqlite3_free(zCreate);
135801   }
135802   if( rc==SQLITE_OK ){
135803     rtreeRelease(pRtree);
135804   }
135805
135806   return rc;
135807 }
135808
135809 /*
135810 ** Rtree virtual table module xOpen method.
135811 */
135812 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
135813   int rc = SQLITE_NOMEM;
135814   RtreeCursor *pCsr;
135815
135816   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
135817   if( pCsr ){
135818     memset(pCsr, 0, sizeof(RtreeCursor));
135819     pCsr->base.pVtab = pVTab;
135820     rc = SQLITE_OK;
135821   }
135822   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
135823
135824   return rc;
135825 }
135826
135827
135828 /*
135829 ** Free the RtreeCursor.aConstraint[] array and its contents.
135830 */
135831 static void freeCursorConstraints(RtreeCursor *pCsr){
135832   if( pCsr->aConstraint ){
135833     int i;                        /* Used to iterate through constraint array */
135834     for(i=0; i<pCsr->nConstraint; i++){
135835       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
135836       if( pGeom ){
135837         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
135838         sqlite3_free(pGeom);
135839       }
135840     }
135841     sqlite3_free(pCsr->aConstraint);
135842     pCsr->aConstraint = 0;
135843   }
135844 }
135845
135846 /*
135847 ** Rtree virtual table module xClose method.
135848 */
135849 static int rtreeClose(sqlite3_vtab_cursor *cur){
135850   Rtree *pRtree = (Rtree *)(cur->pVtab);
135851   int rc;
135852   RtreeCursor *pCsr = (RtreeCursor *)cur;
135853   freeCursorConstraints(pCsr);
135854   rc = nodeRelease(pRtree, pCsr->pNode);
135855   sqlite3_free(pCsr);
135856   return rc;
135857 }
135858
135859 /*
135860 ** Rtree virtual table module xEof method.
135861 **
135862 ** Return non-zero if the cursor does not currently point to a valid
135863 ** record (i.e if the scan has finished), or zero otherwise.
135864 */
135865 static int rtreeEof(sqlite3_vtab_cursor *cur){
135866   RtreeCursor *pCsr = (RtreeCursor *)cur;
135867   return (pCsr->pNode==0);
135868 }
135869
135870 /*
135871 ** The r-tree constraint passed as the second argument to this function is
135872 ** guaranteed to be a MATCH constraint.
135873 */
135874 static int testRtreeGeom(
135875   Rtree *pRtree,                  /* R-Tree object */
135876   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
135877   RtreeCell *pCell,               /* Cell to test */
135878   int *pbRes                      /* OUT: Test result */
135879 ){
135880   int i;
135881   RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
135882   int nCoord = pRtree->nDim*2;
135883
135884   assert( pConstraint->op==RTREE_MATCH );
135885   assert( pConstraint->pGeom );
135886
135887   for(i=0; i<nCoord; i++){
135888     aCoord[i] = DCOORD(pCell->aCoord[i]);
135889   }
135890   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
135891 }
135892
135893 /*
135894 ** Cursor pCursor currently points to a cell in a non-leaf page.
135895 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
135896 ** (excluded) by the constraints in the pCursor->aConstraint[]
135897 ** array, or false otherwise.
135898 **
135899 ** Return SQLITE_OK if successful or an SQLite error code if an error
135900 ** occurs within a geometry callback.
135901 */
135902 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
135903   RtreeCell cell;
135904   int ii;
135905   int bRes = 0;
135906   int rc = SQLITE_OK;
135907
135908   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
135909   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
135910     RtreeConstraint *p = &pCursor->aConstraint[ii];
135911     RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
135912     RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
135913
135914     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
135915         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
135916     );
135917
135918     switch( p->op ){
135919       case RTREE_LE: case RTREE_LT:
135920         bRes = p->rValue<cell_min;
135921         break;
135922
135923       case RTREE_GE: case RTREE_GT:
135924         bRes = p->rValue>cell_max;
135925         break;
135926
135927       case RTREE_EQ:
135928         bRes = (p->rValue>cell_max || p->rValue<cell_min);
135929         break;
135930
135931       default: {
135932         assert( p->op==RTREE_MATCH );
135933         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
135934         bRes = !bRes;
135935         break;
135936       }
135937     }
135938   }
135939
135940   *pbEof = bRes;
135941   return rc;
135942 }
135943
135944 /*
135945 ** Test if the cell that cursor pCursor currently points to
135946 ** would be filtered (excluded) by the constraints in the
135947 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
135948 ** returning. If the cell is not filtered (excluded) by the constraints,
135949 ** set pbEof to zero.
135950 **
135951 ** Return SQLITE_OK if successful or an SQLite error code if an error
135952 ** occurs within a geometry callback.
135953 **
135954 ** This function assumes that the cell is part of a leaf node.
135955 */
135956 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
135957   RtreeCell cell;
135958   int ii;
135959   *pbEof = 0;
135960
135961   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
135962   for(ii=0; ii<pCursor->nConstraint; ii++){
135963     RtreeConstraint *p = &pCursor->aConstraint[ii];
135964     RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
135965     int res;
135966     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
135967         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
135968     );
135969     switch( p->op ){
135970       case RTREE_LE: res = (coord<=p->rValue); break;
135971       case RTREE_LT: res = (coord<p->rValue);  break;
135972       case RTREE_GE: res = (coord>=p->rValue); break;
135973       case RTREE_GT: res = (coord>p->rValue);  break;
135974       case RTREE_EQ: res = (coord==p->rValue); break;
135975       default: {
135976         int rc;
135977         assert( p->op==RTREE_MATCH );
135978         rc = testRtreeGeom(pRtree, p, &cell, &res);
135979         if( rc!=SQLITE_OK ){
135980           return rc;
135981         }
135982         break;
135983       }
135984     }
135985
135986     if( !res ){
135987       *pbEof = 1;
135988       return SQLITE_OK;
135989     }
135990   }
135991
135992   return SQLITE_OK;
135993 }
135994
135995 /*
135996 ** Cursor pCursor currently points at a node that heads a sub-tree of
135997 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
135998 ** to point to the left-most cell of the sub-tree that matches the
135999 ** configured constraints.
136000 */
136001 static int descendToCell(
136002   Rtree *pRtree,
136003   RtreeCursor *pCursor,
136004   int iHeight,
136005   int *pEof                 /* OUT: Set to true if cannot descend */
136006 ){
136007   int isEof;
136008   int rc;
136009   int ii;
136010   RtreeNode *pChild;
136011   sqlite3_int64 iRowid;
136012
136013   RtreeNode *pSavedNode = pCursor->pNode;
136014   int iSavedCell = pCursor->iCell;
136015
136016   assert( iHeight>=0 );
136017
136018   if( iHeight==0 ){
136019     rc = testRtreeEntry(pRtree, pCursor, &isEof);
136020   }else{
136021     rc = testRtreeCell(pRtree, pCursor, &isEof);
136022   }
136023   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
136024     goto descend_to_cell_out;
136025   }
136026
136027   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
136028   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
136029   if( rc!=SQLITE_OK ){
136030     goto descend_to_cell_out;
136031   }
136032
136033   nodeRelease(pRtree, pCursor->pNode);
136034   pCursor->pNode = pChild;
136035   isEof = 1;
136036   for(ii=0; isEof && ii<NCELL(pChild); ii++){
136037     pCursor->iCell = ii;
136038     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
136039     if( rc!=SQLITE_OK ){
136040       goto descend_to_cell_out;
136041     }
136042   }
136043
136044   if( isEof ){
136045     assert( pCursor->pNode==pChild );
136046     nodeReference(pSavedNode);
136047     nodeRelease(pRtree, pChild);
136048     pCursor->pNode = pSavedNode;
136049     pCursor->iCell = iSavedCell;
136050   }
136051
136052 descend_to_cell_out:
136053   *pEof = isEof;
136054   return rc;
136055 }
136056
136057 /*
136058 ** One of the cells in node pNode is guaranteed to have a 64-bit
136059 ** integer value equal to iRowid. Return the index of this cell.
136060 */
136061 static int nodeRowidIndex(
136062   Rtree *pRtree,
136063   RtreeNode *pNode,
136064   i64 iRowid,
136065   int *piIndex
136066 ){
136067   int ii;
136068   int nCell = NCELL(pNode);
136069   for(ii=0; ii<nCell; ii++){
136070     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
136071       *piIndex = ii;
136072       return SQLITE_OK;
136073     }
136074   }
136075   return SQLITE_CORRUPT_VTAB;
136076 }
136077
136078 /*
136079 ** Return the index of the cell containing a pointer to node pNode
136080 ** in its parent. If pNode is the root node, return -1.
136081 */
136082 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
136083   RtreeNode *pParent = pNode->pParent;
136084   if( pParent ){
136085     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
136086   }
136087   *piIndex = -1;
136088   return SQLITE_OK;
136089 }
136090
136091 /*
136092 ** Rtree virtual table module xNext method.
136093 */
136094 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
136095   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
136096   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
136097   int rc = SQLITE_OK;
136098
136099   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
136100   ** already at EOF. It is against the rules to call the xNext() method of
136101   ** a cursor that has already reached EOF.
136102   */
136103   assert( pCsr->pNode );
136104
136105   if( pCsr->iStrategy==1 ){
136106     /* This "scan" is a direct lookup by rowid. There is no next entry. */
136107     nodeRelease(pRtree, pCsr->pNode);
136108     pCsr->pNode = 0;
136109   }else{
136110     /* Move to the next entry that matches the configured constraints. */
136111     int iHeight = 0;
136112     while( pCsr->pNode ){
136113       RtreeNode *pNode = pCsr->pNode;
136114       int nCell = NCELL(pNode);
136115       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
136116         int isEof;
136117         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
136118         if( rc!=SQLITE_OK || !isEof ){
136119           return rc;
136120         }
136121       }
136122       pCsr->pNode = pNode->pParent;
136123       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
136124       if( rc!=SQLITE_OK ){
136125         return rc;
136126       }
136127       nodeReference(pCsr->pNode);
136128       nodeRelease(pRtree, pNode);
136129       iHeight++;
136130     }
136131   }
136132
136133   return rc;
136134 }
136135
136136 /*
136137 ** Rtree virtual table module xRowid method.
136138 */
136139 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
136140   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
136141   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
136142
136143   assert(pCsr->pNode);
136144   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
136145
136146   return SQLITE_OK;
136147 }
136148
136149 /*
136150 ** Rtree virtual table module xColumn method.
136151 */
136152 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
136153   Rtree *pRtree = (Rtree *)cur->pVtab;
136154   RtreeCursor *pCsr = (RtreeCursor *)cur;
136155
136156   if( i==0 ){
136157     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
136158     sqlite3_result_int64(ctx, iRowid);
136159   }else{
136160     RtreeCoord c;
136161     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
136162 #ifndef SQLITE_RTREE_INT_ONLY
136163     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
136164       sqlite3_result_double(ctx, c.f);
136165     }else
136166 #endif
136167     {
136168       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
136169       sqlite3_result_int(ctx, c.i);
136170     }
136171   }
136172
136173   return SQLITE_OK;
136174 }
136175
136176 /*
136177 ** Use nodeAcquire() to obtain the leaf node containing the record with
136178 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
136179 ** return SQLITE_OK. If there is no such record in the table, set
136180 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
136181 ** to zero and return an SQLite error code.
136182 */
136183 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
136184   int rc;
136185   *ppLeaf = 0;
136186   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
136187   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
136188     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
136189     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
136190     sqlite3_reset(pRtree->pReadRowid);
136191   }else{
136192     rc = sqlite3_reset(pRtree->pReadRowid);
136193   }
136194   return rc;
136195 }
136196
136197 /*
136198 ** This function is called to configure the RtreeConstraint object passed
136199 ** as the second argument for a MATCH constraint. The value passed as the
136200 ** first argument to this function is the right-hand operand to the MATCH
136201 ** operator.
136202 */
136203 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
136204   RtreeMatchArg *p;
136205   sqlite3_rtree_geometry *pGeom;
136206   int nBlob;
136207
136208   /* Check that value is actually a blob. */
136209   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
136210
136211   /* Check that the blob is roughly the right size. */
136212   nBlob = sqlite3_value_bytes(pValue);
136213   if( nBlob<(int)sizeof(RtreeMatchArg)
136214    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
136215   ){
136216     return SQLITE_ERROR;
136217   }
136218
136219   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
136220       sizeof(sqlite3_rtree_geometry) + nBlob
136221   );
136222   if( !pGeom ) return SQLITE_NOMEM;
136223   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
136224   p = (RtreeMatchArg *)&pGeom[1];
136225
136226   memcpy(p, sqlite3_value_blob(pValue), nBlob);
136227   if( p->magic!=RTREE_GEOMETRY_MAGIC
136228    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
136229   ){
136230     sqlite3_free(pGeom);
136231     return SQLITE_ERROR;
136232   }
136233
136234   pGeom->pContext = p->pContext;
136235   pGeom->nParam = p->nParam;
136236   pGeom->aParam = p->aParam;
136237
136238   pCons->xGeom = p->xGeom;
136239   pCons->pGeom = pGeom;
136240   return SQLITE_OK;
136241 }
136242
136243 /*
136244 ** Rtree virtual table module xFilter method.
136245 */
136246 static int rtreeFilter(
136247   sqlite3_vtab_cursor *pVtabCursor,
136248   int idxNum, const char *idxStr,
136249   int argc, sqlite3_value **argv
136250 ){
136251   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
136252   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
136253
136254   RtreeNode *pRoot = 0;
136255   int ii;
136256   int rc = SQLITE_OK;
136257
136258   rtreeReference(pRtree);
136259
136260   freeCursorConstraints(pCsr);
136261   pCsr->iStrategy = idxNum;
136262
136263   if( idxNum==1 ){
136264     /* Special case - lookup by rowid. */
136265     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
136266     i64 iRowid = sqlite3_value_int64(argv[0]);
136267     rc = findLeafNode(pRtree, iRowid, &pLeaf);
136268     pCsr->pNode = pLeaf;
136269     if( pLeaf ){
136270       assert( rc==SQLITE_OK );
136271       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
136272     }
136273   }else{
136274     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
136275     ** with the configured constraints.
136276     */
136277     if( argc>0 ){
136278       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
136279       pCsr->nConstraint = argc;
136280       if( !pCsr->aConstraint ){
136281         rc = SQLITE_NOMEM;
136282       }else{
136283         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
136284         assert( (idxStr==0 && argc==0)
136285                 || (idxStr && (int)strlen(idxStr)==argc*2) );
136286         for(ii=0; ii<argc; ii++){
136287           RtreeConstraint *p = &pCsr->aConstraint[ii];
136288           p->op = idxStr[ii*2];
136289           p->iCoord = idxStr[ii*2+1]-'a';
136290           if( p->op==RTREE_MATCH ){
136291             /* A MATCH operator. The right-hand-side must be a blob that
136292             ** can be cast into an RtreeMatchArg object. One created using
136293             ** an sqlite3_rtree_geometry_callback() SQL user function.
136294             */
136295             rc = deserializeGeometry(argv[ii], p);
136296             if( rc!=SQLITE_OK ){
136297               break;
136298             }
136299           }else{
136300 #ifdef SQLITE_RTREE_INT_ONLY
136301             p->rValue = sqlite3_value_int64(argv[ii]);
136302 #else
136303             p->rValue = sqlite3_value_double(argv[ii]);
136304 #endif
136305           }
136306         }
136307       }
136308     }
136309
136310     if( rc==SQLITE_OK ){
136311       pCsr->pNode = 0;
136312       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
136313     }
136314     if( rc==SQLITE_OK ){
136315       int isEof = 1;
136316       int nCell = NCELL(pRoot);
136317       pCsr->pNode = pRoot;
136318       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
136319         assert( pCsr->pNode==pRoot );
136320         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
136321         if( !isEof ){
136322           break;
136323         }
136324       }
136325       if( rc==SQLITE_OK && isEof ){
136326         assert( pCsr->pNode==pRoot );
136327         nodeRelease(pRtree, pRoot);
136328         pCsr->pNode = 0;
136329       }
136330       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
136331     }
136332   }
136333
136334   rtreeRelease(pRtree);
136335   return rc;
136336 }
136337
136338 /*
136339 ** Rtree virtual table module xBestIndex method. There are three
136340 ** table scan strategies to choose from (in order from most to
136341 ** least desirable):
136342 **
136343 **   idxNum     idxStr        Strategy
136344 **   ------------------------------------------------
136345 **     1        Unused        Direct lookup by rowid.
136346 **     2        See below     R-tree query or full-table scan.
136347 **   ------------------------------------------------
136348 **
136349 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
136350 ** 2 is used, idxStr is formatted to contain 2 bytes for each
136351 ** constraint used. The first two bytes of idxStr correspond to
136352 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
136353 ** (argvIndex==1) etc.
136354 **
136355 ** The first of each pair of bytes in idxStr identifies the constraint
136356 ** operator as follows:
136357 **
136358 **   Operator    Byte Value
136359 **   ----------------------
136360 **      =        0x41 ('A')
136361 **     <=        0x42 ('B')
136362 **      <        0x43 ('C')
136363 **     >=        0x44 ('D')
136364 **      >        0x45 ('E')
136365 **   MATCH       0x46 ('F')
136366 **   ----------------------
136367 **
136368 ** The second of each pair of bytes identifies the coordinate column
136369 ** to which the constraint applies. The leftmost coordinate column
136370 ** is 'a', the second from the left 'b' etc.
136371 */
136372 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
136373   int rc = SQLITE_OK;
136374   int ii;
136375
136376   int iIdx = 0;
136377   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
136378   memset(zIdxStr, 0, sizeof(zIdxStr));
136379   UNUSED_PARAMETER(tab);
136380
136381   assert( pIdxInfo->idxStr==0 );
136382   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
136383     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
136384
136385     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
136386       /* We have an equality constraint on the rowid. Use strategy 1. */
136387       int jj;
136388       for(jj=0; jj<ii; jj++){
136389         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
136390         pIdxInfo->aConstraintUsage[jj].omit = 0;
136391       }
136392       pIdxInfo->idxNum = 1;
136393       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
136394       pIdxInfo->aConstraintUsage[jj].omit = 1;
136395
136396       /* This strategy involves a two rowid lookups on an B-Tree structures
136397       ** and then a linear search of an R-Tree node. This should be
136398       ** considered almost as quick as a direct rowid lookup (for which
136399       ** sqlite uses an internal cost of 0.0).
136400       */
136401       pIdxInfo->estimatedCost = 10.0;
136402       return SQLITE_OK;
136403     }
136404
136405     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
136406       u8 op;
136407       switch( p->op ){
136408         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
136409         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
136410         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
136411         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
136412         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
136413         default:
136414           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
136415           op = RTREE_MATCH;
136416           break;
136417       }
136418       zIdxStr[iIdx++] = op;
136419       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
136420       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
136421       pIdxInfo->aConstraintUsage[ii].omit = 1;
136422     }
136423   }
136424
136425   pIdxInfo->idxNum = 2;
136426   pIdxInfo->needToFreeIdxStr = 1;
136427   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
136428     return SQLITE_NOMEM;
136429   }
136430   assert( iIdx>=0 );
136431   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
136432   return rc;
136433 }
136434
136435 /*
136436 ** Return the N-dimensional volumn of the cell stored in *p.
136437 */
136438 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
136439   RtreeDValue area = (RtreeDValue)1;
136440   int ii;
136441   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136442     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
136443   }
136444   return area;
136445 }
136446
136447 /*
136448 ** Return the margin length of cell p. The margin length is the sum
136449 ** of the objects size in each dimension.
136450 */
136451 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
136452   RtreeDValue margin = (RtreeDValue)0;
136453   int ii;
136454   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136455     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
136456   }
136457   return margin;
136458 }
136459
136460 /*
136461 ** Store the union of cells p1 and p2 in p1.
136462 */
136463 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
136464   int ii;
136465   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
136466     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136467       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
136468       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
136469     }
136470   }else{
136471     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136472       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
136473       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
136474     }
136475   }
136476 }
136477
136478 /*
136479 ** Return true if the area covered by p2 is a subset of the area covered
136480 ** by p1. False otherwise.
136481 */
136482 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
136483   int ii;
136484   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
136485   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
136486     RtreeCoord *a1 = &p1->aCoord[ii];
136487     RtreeCoord *a2 = &p2->aCoord[ii];
136488     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
136489      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
136490     ){
136491       return 0;
136492     }
136493   }
136494   return 1;
136495 }
136496
136497 /*
136498 ** Return the amount cell p would grow by if it were unioned with pCell.
136499 */
136500 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
136501   RtreeDValue area;
136502   RtreeCell cell;
136503   memcpy(&cell, p, sizeof(RtreeCell));
136504   area = cellArea(pRtree, &cell);
136505   cellUnion(pRtree, &cell, pCell);
136506   return (cellArea(pRtree, &cell)-area);
136507 }
136508
136509 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
136510 static RtreeDValue cellOverlap(
136511   Rtree *pRtree,
136512   RtreeCell *p,
136513   RtreeCell *aCell,
136514   int nCell,
136515   int iExclude
136516 ){
136517   int ii;
136518   RtreeDValue overlap = 0.0;
136519   for(ii=0; ii<nCell; ii++){
136520 #if VARIANT_RSTARTREE_CHOOSESUBTREE
136521     if( ii!=iExclude )
136522 #else
136523     assert( iExclude==-1 );
136524     UNUSED_PARAMETER(iExclude);
136525 #endif
136526     {
136527       int jj;
136528       RtreeDValue o = (RtreeDValue)1;
136529       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
136530         RtreeDValue x1, x2;
136531
136532         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
136533         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
136534
136535         if( x2<x1 ){
136536           o = 0.0;
136537           break;
136538         }else{
136539           o = o * (x2-x1);
136540         }
136541       }
136542       overlap += o;
136543     }
136544   }
136545   return overlap;
136546 }
136547 #endif
136548
136549 #if VARIANT_RSTARTREE_CHOOSESUBTREE
136550 static RtreeDValue cellOverlapEnlargement(
136551   Rtree *pRtree,
136552   RtreeCell *p,
136553   RtreeCell *pInsert,
136554   RtreeCell *aCell,
136555   int nCell,
136556   int iExclude
136557 ){
136558   RtreeDValue before, after;
136559   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
136560   cellUnion(pRtree, p, pInsert);
136561   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
136562   return (after-before);
136563 }
136564 #endif
136565
136566
136567 /*
136568 ** This function implements the ChooseLeaf algorithm from Gutman[84].
136569 ** ChooseSubTree in r*tree terminology.
136570 */
136571 static int ChooseLeaf(
136572   Rtree *pRtree,               /* Rtree table */
136573   RtreeCell *pCell,            /* Cell to insert into rtree */
136574   int iHeight,                 /* Height of sub-tree rooted at pCell */
136575   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
136576 ){
136577   int rc;
136578   int ii;
136579   RtreeNode *pNode;
136580   rc = nodeAcquire(pRtree, 1, 0, &pNode);
136581
136582   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
136583     int iCell;
136584     sqlite3_int64 iBest = 0;
136585
136586     RtreeDValue fMinGrowth = 0.0;
136587     RtreeDValue fMinArea = 0.0;
136588 #if VARIANT_RSTARTREE_CHOOSESUBTREE
136589     RtreeDValue fMinOverlap = 0.0;
136590     RtreeDValue overlap;
136591 #endif
136592
136593     int nCell = NCELL(pNode);
136594     RtreeCell cell;
136595     RtreeNode *pChild;
136596
136597     RtreeCell *aCell = 0;
136598
136599 #if VARIANT_RSTARTREE_CHOOSESUBTREE
136600     if( ii==(pRtree->iDepth-1) ){
136601       int jj;
136602       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
136603       if( !aCell ){
136604         rc = SQLITE_NOMEM;
136605         nodeRelease(pRtree, pNode);
136606         pNode = 0;
136607         continue;
136608       }
136609       for(jj=0; jj<nCell; jj++){
136610         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
136611       }
136612     }
136613 #endif
136614
136615     /* Select the child node which will be enlarged the least if pCell
136616     ** is inserted into it. Resolve ties by choosing the entry with
136617     ** the smallest area.
136618     */
136619     for(iCell=0; iCell<nCell; iCell++){
136620       int bBest = 0;
136621       RtreeDValue growth;
136622       RtreeDValue area;
136623       nodeGetCell(pRtree, pNode, iCell, &cell);
136624       growth = cellGrowth(pRtree, &cell, pCell);
136625       area = cellArea(pRtree, &cell);
136626
136627 #if VARIANT_RSTARTREE_CHOOSESUBTREE
136628       if( ii==(pRtree->iDepth-1) ){
136629         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
136630       }else{
136631         overlap = 0.0;
136632       }
136633       if( (iCell==0)
136634        || (overlap<fMinOverlap)
136635        || (overlap==fMinOverlap && growth<fMinGrowth)
136636        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
136637       ){
136638         bBest = 1;
136639         fMinOverlap = overlap;
136640       }
136641 #else
136642       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
136643         bBest = 1;
136644       }
136645 #endif
136646       if( bBest ){
136647         fMinGrowth = growth;
136648         fMinArea = area;
136649         iBest = cell.iRowid;
136650       }
136651     }
136652
136653     sqlite3_free(aCell);
136654     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
136655     nodeRelease(pRtree, pNode);
136656     pNode = pChild;
136657   }
136658
136659   *ppLeaf = pNode;
136660   return rc;
136661 }
136662
136663 /*
136664 ** A cell with the same content as pCell has just been inserted into
136665 ** the node pNode. This function updates the bounding box cells in
136666 ** all ancestor elements.
136667 */
136668 static int AdjustTree(
136669   Rtree *pRtree,                    /* Rtree table */
136670   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
136671   RtreeCell *pCell                  /* This cell was just inserted */
136672 ){
136673   RtreeNode *p = pNode;
136674   while( p->pParent ){
136675     RtreeNode *pParent = p->pParent;
136676     RtreeCell cell;
136677     int iCell;
136678
136679     if( nodeParentIndex(pRtree, p, &iCell) ){
136680       return SQLITE_CORRUPT_VTAB;
136681     }
136682
136683     nodeGetCell(pRtree, pParent, iCell, &cell);
136684     if( !cellContains(pRtree, &cell, pCell) ){
136685       cellUnion(pRtree, &cell, pCell);
136686       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
136687     }
136688
136689     p = pParent;
136690   }
136691   return SQLITE_OK;
136692 }
136693
136694 /*
136695 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
136696 */
136697 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
136698   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
136699   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
136700   sqlite3_step(pRtree->pWriteRowid);
136701   return sqlite3_reset(pRtree->pWriteRowid);
136702 }
136703
136704 /*
136705 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
136706 */
136707 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
136708   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
136709   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
136710   sqlite3_step(pRtree->pWriteParent);
136711   return sqlite3_reset(pRtree->pWriteParent);
136712 }
136713
136714 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
136715
136716 #if VARIANT_GUTTMAN_LINEAR_SPLIT
136717 /*
136718 ** Implementation of the linear variant of the PickNext() function from
136719 ** Guttman[84].
136720 */
136721 static RtreeCell *LinearPickNext(
136722   Rtree *pRtree,
136723   RtreeCell *aCell,
136724   int nCell,
136725   RtreeCell *pLeftBox,
136726   RtreeCell *pRightBox,
136727   int *aiUsed
136728 ){
136729   int ii;
136730   for(ii=0; aiUsed[ii]; ii++);
136731   aiUsed[ii] = 1;
136732   return &aCell[ii];
136733 }
136734
136735 /*
136736 ** Implementation of the linear variant of the PickSeeds() function from
136737 ** Guttman[84].
136738 */
136739 static void LinearPickSeeds(
136740   Rtree *pRtree,
136741   RtreeCell *aCell,
136742   int nCell,
136743   int *piLeftSeed,
136744   int *piRightSeed
136745 ){
136746   int i;
136747   int iLeftSeed = 0;
136748   int iRightSeed = 1;
136749   RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
136750
136751   /* Pick two "seed" cells from the array of cells. The algorithm used
136752   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
136753   ** indices of the two seed cells in the array are stored in local
136754   ** variables iLeftSeek and iRightSeed.
136755   */
136756   for(i=0; i<pRtree->nDim; i++){
136757     RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
136758     RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
136759     RtreeDValue x3 = x1;
136760     RtreeDValue x4 = x2;
136761     int jj;
136762
136763     int iCellLeft = 0;
136764     int iCellRight = 0;
136765
136766     for(jj=1; jj<nCell; jj++){
136767       RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
136768       RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
136769
136770       if( left<x1 ) x1 = left;
136771       if( right>x4 ) x4 = right;
136772       if( left>x3 ){
136773         x3 = left;
136774         iCellRight = jj;
136775       }
136776       if( right<x2 ){
136777         x2 = right;
136778         iCellLeft = jj;
136779       }
136780     }
136781
136782     if( x4!=x1 ){
136783       RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
136784       if( normalwidth>maxNormalInnerWidth ){
136785         iLeftSeed = iCellLeft;
136786         iRightSeed = iCellRight;
136787       }
136788     }
136789   }
136790
136791   *piLeftSeed = iLeftSeed;
136792   *piRightSeed = iRightSeed;
136793 }
136794 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
136795
136796 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
136797 /*
136798 ** Implementation of the quadratic variant of the PickNext() function from
136799 ** Guttman[84].
136800 */
136801 static RtreeCell *QuadraticPickNext(
136802   Rtree *pRtree,
136803   RtreeCell *aCell,
136804   int nCell,
136805   RtreeCell *pLeftBox,
136806   RtreeCell *pRightBox,
136807   int *aiUsed
136808 ){
136809   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
136810
136811   int iSelect = -1;
136812   RtreeDValue fDiff;
136813   int ii;
136814   for(ii=0; ii<nCell; ii++){
136815     if( aiUsed[ii]==0 ){
136816       RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
136817       RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
136818       RtreeDValue diff = FABS(right-left);
136819       if( iSelect<0 || diff>fDiff ){
136820         fDiff = diff;
136821         iSelect = ii;
136822       }
136823     }
136824   }
136825   aiUsed[iSelect] = 1;
136826   return &aCell[iSelect];
136827 }
136828
136829 /*
136830 ** Implementation of the quadratic variant of the PickSeeds() function from
136831 ** Guttman[84].
136832 */
136833 static void QuadraticPickSeeds(
136834   Rtree *pRtree,
136835   RtreeCell *aCell,
136836   int nCell,
136837   int *piLeftSeed,
136838   int *piRightSeed
136839 ){
136840   int ii;
136841   int jj;
136842
136843   int iLeftSeed = 0;
136844   int iRightSeed = 1;
136845   RtreeDValue fWaste = 0.0;
136846
136847   for(ii=0; ii<nCell; ii++){
136848     for(jj=ii+1; jj<nCell; jj++){
136849       RtreeDValue right = cellArea(pRtree, &aCell[jj]);
136850       RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
136851       RtreeDValue waste = growth - right;
136852
136853       if( waste>fWaste ){
136854         iLeftSeed = ii;
136855         iRightSeed = jj;
136856         fWaste = waste;
136857       }
136858     }
136859   }
136860
136861   *piLeftSeed = iLeftSeed;
136862   *piRightSeed = iRightSeed;
136863 }
136864 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
136865
136866 /*
136867 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
136868 ** nIdx. The aIdx array contains the set of integers from 0 to
136869 ** (nIdx-1) in no particular order. This function sorts the values
136870 ** in aIdx according to the indexed values in aDistance. For
136871 ** example, assuming the inputs:
136872 **
136873 **   aIdx      = { 0,   1,   2,   3 }
136874 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
136875 **
136876 ** this function sets the aIdx array to contain:
136877 **
136878 **   aIdx      = { 0,   1,   2,   3 }
136879 **
136880 ** The aSpare array is used as temporary working space by the
136881 ** sorting algorithm.
136882 */
136883 static void SortByDistance(
136884   int *aIdx,
136885   int nIdx,
136886   RtreeDValue *aDistance,
136887   int *aSpare
136888 ){
136889   if( nIdx>1 ){
136890     int iLeft = 0;
136891     int iRight = 0;
136892
136893     int nLeft = nIdx/2;
136894     int nRight = nIdx-nLeft;
136895     int *aLeft = aIdx;
136896     int *aRight = &aIdx[nLeft];
136897
136898     SortByDistance(aLeft, nLeft, aDistance, aSpare);
136899     SortByDistance(aRight, nRight, aDistance, aSpare);
136900
136901     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
136902     aLeft = aSpare;
136903
136904     while( iLeft<nLeft || iRight<nRight ){
136905       if( iLeft==nLeft ){
136906         aIdx[iLeft+iRight] = aRight[iRight];
136907         iRight++;
136908       }else if( iRight==nRight ){
136909         aIdx[iLeft+iRight] = aLeft[iLeft];
136910         iLeft++;
136911       }else{
136912         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
136913         RtreeDValue fRight = aDistance[aRight[iRight]];
136914         if( fLeft<fRight ){
136915           aIdx[iLeft+iRight] = aLeft[iLeft];
136916           iLeft++;
136917         }else{
136918           aIdx[iLeft+iRight] = aRight[iRight];
136919           iRight++;
136920         }
136921       }
136922     }
136923
136924 #if 0
136925     /* Check that the sort worked */
136926     {
136927       int jj;
136928       for(jj=1; jj<nIdx; jj++){
136929         RtreeDValue left = aDistance[aIdx[jj-1]];
136930         RtreeDValue right = aDistance[aIdx[jj]];
136931         assert( left<=right );
136932       }
136933     }
136934 #endif
136935   }
136936 }
136937
136938 /*
136939 ** Arguments aIdx, aCell and aSpare all point to arrays of size
136940 ** nIdx. The aIdx array contains the set of integers from 0 to
136941 ** (nIdx-1) in no particular order. This function sorts the values
136942 ** in aIdx according to dimension iDim of the cells in aCell. The
136943 ** minimum value of dimension iDim is considered first, the
136944 ** maximum used to break ties.
136945 **
136946 ** The aSpare array is used as temporary working space by the
136947 ** sorting algorithm.
136948 */
136949 static void SortByDimension(
136950   Rtree *pRtree,
136951   int *aIdx,
136952   int nIdx,
136953   int iDim,
136954   RtreeCell *aCell,
136955   int *aSpare
136956 ){
136957   if( nIdx>1 ){
136958
136959     int iLeft = 0;
136960     int iRight = 0;
136961
136962     int nLeft = nIdx/2;
136963     int nRight = nIdx-nLeft;
136964     int *aLeft = aIdx;
136965     int *aRight = &aIdx[nLeft];
136966
136967     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
136968     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
136969
136970     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
136971     aLeft = aSpare;
136972     while( iLeft<nLeft || iRight<nRight ){
136973       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
136974       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
136975       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
136976       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
136977       if( (iLeft!=nLeft) && ((iRight==nRight)
136978        || (xleft1<xright1)
136979        || (xleft1==xright1 && xleft2<xright2)
136980       )){
136981         aIdx[iLeft+iRight] = aLeft[iLeft];
136982         iLeft++;
136983       }else{
136984         aIdx[iLeft+iRight] = aRight[iRight];
136985         iRight++;
136986       }
136987     }
136988
136989 #if 0
136990     /* Check that the sort worked */
136991     {
136992       int jj;
136993       for(jj=1; jj<nIdx; jj++){
136994         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
136995         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
136996         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
136997         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
136998         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
136999       }
137000     }
137001 #endif
137002   }
137003 }
137004
137005 #if VARIANT_RSTARTREE_SPLIT
137006 /*
137007 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
137008 */
137009 static int splitNodeStartree(
137010   Rtree *pRtree,
137011   RtreeCell *aCell,
137012   int nCell,
137013   RtreeNode *pLeft,
137014   RtreeNode *pRight,
137015   RtreeCell *pBboxLeft,
137016   RtreeCell *pBboxRight
137017 ){
137018   int **aaSorted;
137019   int *aSpare;
137020   int ii;
137021
137022   int iBestDim = 0;
137023   int iBestSplit = 0;
137024   RtreeDValue fBestMargin = 0.0;
137025
137026   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
137027
137028   aaSorted = (int **)sqlite3_malloc(nByte);
137029   if( !aaSorted ){
137030     return SQLITE_NOMEM;
137031   }
137032
137033   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
137034   memset(aaSorted, 0, nByte);
137035   for(ii=0; ii<pRtree->nDim; ii++){
137036     int jj;
137037     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
137038     for(jj=0; jj<nCell; jj++){
137039       aaSorted[ii][jj] = jj;
137040     }
137041     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
137042   }
137043
137044   for(ii=0; ii<pRtree->nDim; ii++){
137045     RtreeDValue margin = 0.0;
137046     RtreeDValue fBestOverlap = 0.0;
137047     RtreeDValue fBestArea = 0.0;
137048     int iBestLeft = 0;
137049     int nLeft;
137050
137051     for(
137052       nLeft=RTREE_MINCELLS(pRtree);
137053       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
137054       nLeft++
137055     ){
137056       RtreeCell left;
137057       RtreeCell right;
137058       int kk;
137059       RtreeDValue overlap;
137060       RtreeDValue area;
137061
137062       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
137063       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
137064       for(kk=1; kk<(nCell-1); kk++){
137065         if( kk<nLeft ){
137066           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
137067         }else{
137068           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
137069         }
137070       }
137071       margin += cellMargin(pRtree, &left);
137072       margin += cellMargin(pRtree, &right);
137073       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
137074       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
137075       if( (nLeft==RTREE_MINCELLS(pRtree))
137076        || (overlap<fBestOverlap)
137077        || (overlap==fBestOverlap && area<fBestArea)
137078       ){
137079         iBestLeft = nLeft;
137080         fBestOverlap = overlap;
137081         fBestArea = area;
137082       }
137083     }
137084
137085     if( ii==0 || margin<fBestMargin ){
137086       iBestDim = ii;
137087       fBestMargin = margin;
137088       iBestSplit = iBestLeft;
137089     }
137090   }
137091
137092   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
137093   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
137094   for(ii=0; ii<nCell; ii++){
137095     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
137096     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
137097     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
137098     nodeInsertCell(pRtree, pTarget, pCell);
137099     cellUnion(pRtree, pBbox, pCell);
137100   }
137101
137102   sqlite3_free(aaSorted);
137103   return SQLITE_OK;
137104 }
137105 #endif
137106
137107 #if VARIANT_GUTTMAN_SPLIT
137108 /*
137109 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
137110 */
137111 static int splitNodeGuttman(
137112   Rtree *pRtree,
137113   RtreeCell *aCell,
137114   int nCell,
137115   RtreeNode *pLeft,
137116   RtreeNode *pRight,
137117   RtreeCell *pBboxLeft,
137118   RtreeCell *pBboxRight
137119 ){
137120   int iLeftSeed = 0;
137121   int iRightSeed = 1;
137122   int *aiUsed;
137123   int i;
137124
137125   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
137126   if( !aiUsed ){
137127     return SQLITE_NOMEM;
137128   }
137129   memset(aiUsed, 0, sizeof(int)*nCell);
137130
137131   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
137132
137133   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
137134   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
137135   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
137136   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
137137   aiUsed[iLeftSeed] = 1;
137138   aiUsed[iRightSeed] = 1;
137139
137140   for(i=nCell-2; i>0; i--){
137141     RtreeCell *pNext;
137142     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
137143     RtreeDValue diff =
137144       cellGrowth(pRtree, pBboxLeft, pNext) -
137145       cellGrowth(pRtree, pBboxRight, pNext)
137146     ;
137147     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
137148      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
137149     ){
137150       nodeInsertCell(pRtree, pRight, pNext);
137151       cellUnion(pRtree, pBboxRight, pNext);
137152     }else{
137153       nodeInsertCell(pRtree, pLeft, pNext);
137154       cellUnion(pRtree, pBboxLeft, pNext);
137155     }
137156   }
137157
137158   sqlite3_free(aiUsed);
137159   return SQLITE_OK;
137160 }
137161 #endif
137162
137163 static int updateMapping(
137164   Rtree *pRtree,
137165   i64 iRowid,
137166   RtreeNode *pNode,
137167   int iHeight
137168 ){
137169   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
137170   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
137171   if( iHeight>0 ){
137172     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
137173     if( pChild ){
137174       nodeRelease(pRtree, pChild->pParent);
137175       nodeReference(pNode);
137176       pChild->pParent = pNode;
137177     }
137178   }
137179   return xSetMapping(pRtree, iRowid, pNode->iNode);
137180 }
137181
137182 static int SplitNode(
137183   Rtree *pRtree,
137184   RtreeNode *pNode,
137185   RtreeCell *pCell,
137186   int iHeight
137187 ){
137188   int i;
137189   int newCellIsRight = 0;
137190
137191   int rc = SQLITE_OK;
137192   int nCell = NCELL(pNode);
137193   RtreeCell *aCell;
137194   int *aiUsed;
137195
137196   RtreeNode *pLeft = 0;
137197   RtreeNode *pRight = 0;
137198
137199   RtreeCell leftbbox;
137200   RtreeCell rightbbox;
137201
137202   /* Allocate an array and populate it with a copy of pCell and
137203   ** all cells from node pLeft. Then zero the original node.
137204   */
137205   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
137206   if( !aCell ){
137207     rc = SQLITE_NOMEM;
137208     goto splitnode_out;
137209   }
137210   aiUsed = (int *)&aCell[nCell+1];
137211   memset(aiUsed, 0, sizeof(int)*(nCell+1));
137212   for(i=0; i<nCell; i++){
137213     nodeGetCell(pRtree, pNode, i, &aCell[i]);
137214   }
137215   nodeZero(pRtree, pNode);
137216   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
137217   nCell++;
137218
137219   if( pNode->iNode==1 ){
137220     pRight = nodeNew(pRtree, pNode);
137221     pLeft = nodeNew(pRtree, pNode);
137222     pRtree->iDepth++;
137223     pNode->isDirty = 1;
137224     writeInt16(pNode->zData, pRtree->iDepth);
137225   }else{
137226     pLeft = pNode;
137227     pRight = nodeNew(pRtree, pLeft->pParent);
137228     nodeReference(pLeft);
137229   }
137230
137231   if( !pLeft || !pRight ){
137232     rc = SQLITE_NOMEM;
137233     goto splitnode_out;
137234   }
137235
137236   memset(pLeft->zData, 0, pRtree->iNodeSize);
137237   memset(pRight->zData, 0, pRtree->iNodeSize);
137238
137239   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
137240   if( rc!=SQLITE_OK ){
137241     goto splitnode_out;
137242   }
137243
137244   /* Ensure both child nodes have node numbers assigned to them by calling
137245   ** nodeWrite(). Node pRight always needs a node number, as it was created
137246   ** by nodeNew() above. But node pLeft sometimes already has a node number.
137247   ** In this case avoid the all to nodeWrite().
137248   */
137249   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
137250    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
137251   ){
137252     goto splitnode_out;
137253   }
137254
137255   rightbbox.iRowid = pRight->iNode;
137256   leftbbox.iRowid = pLeft->iNode;
137257
137258   if( pNode->iNode==1 ){
137259     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
137260     if( rc!=SQLITE_OK ){
137261       goto splitnode_out;
137262     }
137263   }else{
137264     RtreeNode *pParent = pLeft->pParent;
137265     int iCell;
137266     rc = nodeParentIndex(pRtree, pLeft, &iCell);
137267     if( rc==SQLITE_OK ){
137268       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
137269       rc = AdjustTree(pRtree, pParent, &leftbbox);
137270     }
137271     if( rc!=SQLITE_OK ){
137272       goto splitnode_out;
137273     }
137274   }
137275   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
137276     goto splitnode_out;
137277   }
137278
137279   for(i=0; i<NCELL(pRight); i++){
137280     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
137281     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
137282     if( iRowid==pCell->iRowid ){
137283       newCellIsRight = 1;
137284     }
137285     if( rc!=SQLITE_OK ){
137286       goto splitnode_out;
137287     }
137288   }
137289   if( pNode->iNode==1 ){
137290     for(i=0; i<NCELL(pLeft); i++){
137291       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
137292       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
137293       if( rc!=SQLITE_OK ){
137294         goto splitnode_out;
137295       }
137296     }
137297   }else if( newCellIsRight==0 ){
137298     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
137299   }
137300
137301   if( rc==SQLITE_OK ){
137302     rc = nodeRelease(pRtree, pRight);
137303     pRight = 0;
137304   }
137305   if( rc==SQLITE_OK ){
137306     rc = nodeRelease(pRtree, pLeft);
137307     pLeft = 0;
137308   }
137309
137310 splitnode_out:
137311   nodeRelease(pRtree, pRight);
137312   nodeRelease(pRtree, pLeft);
137313   sqlite3_free(aCell);
137314   return rc;
137315 }
137316
137317 /*
137318 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
137319 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
137320 ** the pLeaf->pParent chain all the way up to the root node.
137321 **
137322 ** This operation is required when a row is deleted (or updated - an update
137323 ** is implemented as a delete followed by an insert). SQLite provides the
137324 ** rowid of the row to delete, which can be used to find the leaf on which
137325 ** the entry resides (argument pLeaf). Once the leaf is located, this
137326 ** function is called to determine its ancestry.
137327 */
137328 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
137329   int rc = SQLITE_OK;
137330   RtreeNode *pChild = pLeaf;
137331   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
137332     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
137333     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
137334     rc = sqlite3_step(pRtree->pReadParent);
137335     if( rc==SQLITE_ROW ){
137336       RtreeNode *pTest;           /* Used to test for reference loops */
137337       i64 iNode;                  /* Node number of parent node */
137338
137339       /* Before setting pChild->pParent, test that we are not creating a
137340       ** loop of references (as we would if, say, pChild==pParent). We don't
137341       ** want to do this as it leads to a memory leak when trying to delete
137342       ** the referenced counted node structures.
137343       */
137344       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
137345       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
137346       if( !pTest ){
137347         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
137348       }
137349     }
137350     rc = sqlite3_reset(pRtree->pReadParent);
137351     if( rc==SQLITE_OK ) rc = rc2;
137352     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
137353     pChild = pChild->pParent;
137354   }
137355   return rc;
137356 }
137357
137358 static int deleteCell(Rtree *, RtreeNode *, int, int);
137359
137360 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
137361   int rc;
137362   int rc2;
137363   RtreeNode *pParent = 0;
137364   int iCell;
137365
137366   assert( pNode->nRef==1 );
137367
137368   /* Remove the entry in the parent cell. */
137369   rc = nodeParentIndex(pRtree, pNode, &iCell);
137370   if( rc==SQLITE_OK ){
137371     pParent = pNode->pParent;
137372     pNode->pParent = 0;
137373     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
137374   }
137375   rc2 = nodeRelease(pRtree, pParent);
137376   if( rc==SQLITE_OK ){
137377     rc = rc2;
137378   }
137379   if( rc!=SQLITE_OK ){
137380     return rc;
137381   }
137382
137383   /* Remove the xxx_node entry. */
137384   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
137385   sqlite3_step(pRtree->pDeleteNode);
137386   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
137387     return rc;
137388   }
137389
137390   /* Remove the xxx_parent entry. */
137391   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
137392   sqlite3_step(pRtree->pDeleteParent);
137393   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
137394     return rc;
137395   }
137396
137397   /* Remove the node from the in-memory hash table and link it into
137398   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
137399   */
137400   nodeHashDelete(pRtree, pNode);
137401   pNode->iNode = iHeight;
137402   pNode->pNext = pRtree->pDeleted;
137403   pNode->nRef++;
137404   pRtree->pDeleted = pNode;
137405
137406   return SQLITE_OK;
137407 }
137408
137409 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
137410   RtreeNode *pParent = pNode->pParent;
137411   int rc = SQLITE_OK;
137412   if( pParent ){
137413     int ii;
137414     int nCell = NCELL(pNode);
137415     RtreeCell box;                            /* Bounding box for pNode */
137416     nodeGetCell(pRtree, pNode, 0, &box);
137417     for(ii=1; ii<nCell; ii++){
137418       RtreeCell cell;
137419       nodeGetCell(pRtree, pNode, ii, &cell);
137420       cellUnion(pRtree, &box, &cell);
137421     }
137422     box.iRowid = pNode->iNode;
137423     rc = nodeParentIndex(pRtree, pNode, &ii);
137424     if( rc==SQLITE_OK ){
137425       nodeOverwriteCell(pRtree, pParent, &box, ii);
137426       rc = fixBoundingBox(pRtree, pParent);
137427     }
137428   }
137429   return rc;
137430 }
137431
137432 /*
137433 ** Delete the cell at index iCell of node pNode. After removing the
137434 ** cell, adjust the r-tree data structure if required.
137435 */
137436 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
137437   RtreeNode *pParent;
137438   int rc;
137439
137440   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
137441     return rc;
137442   }
137443
137444   /* Remove the cell from the node. This call just moves bytes around
137445   ** the in-memory node image, so it cannot fail.
137446   */
137447   nodeDeleteCell(pRtree, pNode, iCell);
137448
137449   /* If the node is not the tree root and now has less than the minimum
137450   ** number of cells, remove it from the tree. Otherwise, update the
137451   ** cell in the parent node so that it tightly contains the updated
137452   ** node.
137453   */
137454   pParent = pNode->pParent;
137455   assert( pParent || pNode->iNode==1 );
137456   if( pParent ){
137457     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
137458       rc = removeNode(pRtree, pNode, iHeight);
137459     }else{
137460       rc = fixBoundingBox(pRtree, pNode);
137461     }
137462   }
137463
137464   return rc;
137465 }
137466
137467 static int Reinsert(
137468   Rtree *pRtree,
137469   RtreeNode *pNode,
137470   RtreeCell *pCell,
137471   int iHeight
137472 ){
137473   int *aOrder;
137474   int *aSpare;
137475   RtreeCell *aCell;
137476   RtreeDValue *aDistance;
137477   int nCell;
137478   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
137479   int iDim;
137480   int ii;
137481   int rc = SQLITE_OK;
137482   int n;
137483
137484   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
137485
137486   nCell = NCELL(pNode)+1;
137487   n = (nCell+1)&(~1);
137488
137489   /* Allocate the buffers used by this operation. The allocation is
137490   ** relinquished before this function returns.
137491   */
137492   aCell = (RtreeCell *)sqlite3_malloc(n * (
137493     sizeof(RtreeCell)     +         /* aCell array */
137494     sizeof(int)           +         /* aOrder array */
137495     sizeof(int)           +         /* aSpare array */
137496     sizeof(RtreeDValue)             /* aDistance array */
137497   ));
137498   if( !aCell ){
137499     return SQLITE_NOMEM;
137500   }
137501   aOrder    = (int *)&aCell[n];
137502   aSpare    = (int *)&aOrder[n];
137503   aDistance = (RtreeDValue *)&aSpare[n];
137504
137505   for(ii=0; ii<nCell; ii++){
137506     if( ii==(nCell-1) ){
137507       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
137508     }else{
137509       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
137510     }
137511     aOrder[ii] = ii;
137512     for(iDim=0; iDim<pRtree->nDim; iDim++){
137513       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
137514       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
137515     }
137516   }
137517   for(iDim=0; iDim<pRtree->nDim; iDim++){
137518     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
137519   }
137520
137521   for(ii=0; ii<nCell; ii++){
137522     aDistance[ii] = 0.0;
137523     for(iDim=0; iDim<pRtree->nDim; iDim++){
137524       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
137525                                DCOORD(aCell[ii].aCoord[iDim*2]));
137526       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
137527     }
137528   }
137529
137530   SortByDistance(aOrder, nCell, aDistance, aSpare);
137531   nodeZero(pRtree, pNode);
137532
137533   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
137534     RtreeCell *p = &aCell[aOrder[ii]];
137535     nodeInsertCell(pRtree, pNode, p);
137536     if( p->iRowid==pCell->iRowid ){
137537       if( iHeight==0 ){
137538         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
137539       }else{
137540         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
137541       }
137542     }
137543   }
137544   if( rc==SQLITE_OK ){
137545     rc = fixBoundingBox(pRtree, pNode);
137546   }
137547   for(; rc==SQLITE_OK && ii<nCell; ii++){
137548     /* Find a node to store this cell in. pNode->iNode currently contains
137549     ** the height of the sub-tree headed by the cell.
137550     */
137551     RtreeNode *pInsert;
137552     RtreeCell *p = &aCell[aOrder[ii]];
137553     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
137554     if( rc==SQLITE_OK ){
137555       int rc2;
137556       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
137557       rc2 = nodeRelease(pRtree, pInsert);
137558       if( rc==SQLITE_OK ){
137559         rc = rc2;
137560       }
137561     }
137562   }
137563
137564   sqlite3_free(aCell);
137565   return rc;
137566 }
137567
137568 /*
137569 ** Insert cell pCell into node pNode. Node pNode is the head of a
137570 ** subtree iHeight high (leaf nodes have iHeight==0).
137571 */
137572 static int rtreeInsertCell(
137573   Rtree *pRtree,
137574   RtreeNode *pNode,
137575   RtreeCell *pCell,
137576   int iHeight
137577 ){
137578   int rc = SQLITE_OK;
137579   if( iHeight>0 ){
137580     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
137581     if( pChild ){
137582       nodeRelease(pRtree, pChild->pParent);
137583       nodeReference(pNode);
137584       pChild->pParent = pNode;
137585     }
137586   }
137587   if( nodeInsertCell(pRtree, pNode, pCell) ){
137588 #if VARIANT_RSTARTREE_REINSERT
137589     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
137590       rc = SplitNode(pRtree, pNode, pCell, iHeight);
137591     }else{
137592       pRtree->iReinsertHeight = iHeight;
137593       rc = Reinsert(pRtree, pNode, pCell, iHeight);
137594     }
137595 #else
137596     rc = SplitNode(pRtree, pNode, pCell, iHeight);
137597 #endif
137598   }else{
137599     rc = AdjustTree(pRtree, pNode, pCell);
137600     if( rc==SQLITE_OK ){
137601       if( iHeight==0 ){
137602         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
137603       }else{
137604         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
137605       }
137606     }
137607   }
137608   return rc;
137609 }
137610
137611 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
137612   int ii;
137613   int rc = SQLITE_OK;
137614   int nCell = NCELL(pNode);
137615
137616   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
137617     RtreeNode *pInsert;
137618     RtreeCell cell;
137619     nodeGetCell(pRtree, pNode, ii, &cell);
137620
137621     /* Find a node to store this cell in. pNode->iNode currently contains
137622     ** the height of the sub-tree headed by the cell.
137623     */
137624     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
137625     if( rc==SQLITE_OK ){
137626       int rc2;
137627       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
137628       rc2 = nodeRelease(pRtree, pInsert);
137629       if( rc==SQLITE_OK ){
137630         rc = rc2;
137631       }
137632     }
137633   }
137634   return rc;
137635 }
137636
137637 /*
137638 ** Select a currently unused rowid for a new r-tree record.
137639 */
137640 static int newRowid(Rtree *pRtree, i64 *piRowid){
137641   int rc;
137642   sqlite3_bind_null(pRtree->pWriteRowid, 1);
137643   sqlite3_bind_null(pRtree->pWriteRowid, 2);
137644   sqlite3_step(pRtree->pWriteRowid);
137645   rc = sqlite3_reset(pRtree->pWriteRowid);
137646   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
137647   return rc;
137648 }
137649
137650 /*
137651 ** Remove the entry with rowid=iDelete from the r-tree structure.
137652 */
137653 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
137654   int rc;                         /* Return code */
137655   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
137656   int iCell;                      /* Index of iDelete cell in pLeaf */
137657   RtreeNode *pRoot;               /* Root node of rtree structure */
137658
137659
137660   /* Obtain a reference to the root node to initialise Rtree.iDepth */
137661   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
137662
137663   /* Obtain a reference to the leaf node that contains the entry
137664   ** about to be deleted.
137665   */
137666   if( rc==SQLITE_OK ){
137667     rc = findLeafNode(pRtree, iDelete, &pLeaf);
137668   }
137669
137670   /* Delete the cell in question from the leaf node. */
137671   if( rc==SQLITE_OK ){
137672     int rc2;
137673     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
137674     if( rc==SQLITE_OK ){
137675       rc = deleteCell(pRtree, pLeaf, iCell, 0);
137676     }
137677     rc2 = nodeRelease(pRtree, pLeaf);
137678     if( rc==SQLITE_OK ){
137679       rc = rc2;
137680     }
137681   }
137682
137683   /* Delete the corresponding entry in the <rtree>_rowid table. */
137684   if( rc==SQLITE_OK ){
137685     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
137686     sqlite3_step(pRtree->pDeleteRowid);
137687     rc = sqlite3_reset(pRtree->pDeleteRowid);
137688   }
137689
137690   /* Check if the root node now has exactly one child. If so, remove
137691   ** it, schedule the contents of the child for reinsertion and
137692   ** reduce the tree height by one.
137693   **
137694   ** This is equivalent to copying the contents of the child into
137695   ** the root node (the operation that Gutman's paper says to perform
137696   ** in this scenario).
137697   */
137698   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
137699     int rc2;
137700     RtreeNode *pChild;
137701     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
137702     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
137703     if( rc==SQLITE_OK ){
137704       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
137705     }
137706     rc2 = nodeRelease(pRtree, pChild);
137707     if( rc==SQLITE_OK ) rc = rc2;
137708     if( rc==SQLITE_OK ){
137709       pRtree->iDepth--;
137710       writeInt16(pRoot->zData, pRtree->iDepth);
137711       pRoot->isDirty = 1;
137712     }
137713   }
137714
137715   /* Re-insert the contents of any underfull nodes removed from the tree. */
137716   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
137717     if( rc==SQLITE_OK ){
137718       rc = reinsertNodeContent(pRtree, pLeaf);
137719     }
137720     pRtree->pDeleted = pLeaf->pNext;
137721     sqlite3_free(pLeaf);
137722   }
137723
137724   /* Release the reference to the root node. */
137725   if( rc==SQLITE_OK ){
137726     rc = nodeRelease(pRtree, pRoot);
137727   }else{
137728     nodeRelease(pRtree, pRoot);
137729   }
137730
137731   return rc;
137732 }
137733
137734 /*
137735 ** Rounding constants for float->double conversion.
137736 */
137737 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
137738 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
137739
137740 #if !defined(SQLITE_RTREE_INT_ONLY)
137741 /*
137742 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
137743 ** while taking care to round toward negative or positive, respectively.
137744 */
137745 static RtreeValue rtreeValueDown(sqlite3_value *v){
137746   double d = sqlite3_value_double(v);
137747   float f = (float)d;
137748   if( f>d ){
137749     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
137750   }
137751   return f;
137752 }
137753 static RtreeValue rtreeValueUp(sqlite3_value *v){
137754   double d = sqlite3_value_double(v);
137755   float f = (float)d;
137756   if( f<d ){
137757     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
137758   }
137759   return f;
137760 }
137761 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
137762
137763
137764 /*
137765 ** The xUpdate method for rtree module virtual tables.
137766 */
137767 static int rtreeUpdate(
137768   sqlite3_vtab *pVtab,
137769   int nData,
137770   sqlite3_value **azData,
137771   sqlite_int64 *pRowid
137772 ){
137773   Rtree *pRtree = (Rtree *)pVtab;
137774   int rc = SQLITE_OK;
137775   RtreeCell cell;                 /* New cell to insert if nData>1 */
137776   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
137777
137778   rtreeReference(pRtree);
137779   assert(nData>=1);
137780
137781   /* Constraint handling. A write operation on an r-tree table may return
137782   ** SQLITE_CONSTRAINT for two reasons:
137783   **
137784   **   1. A duplicate rowid value, or
137785   **   2. The supplied data violates the "x2>=x1" constraint.
137786   **
137787   ** In the first case, if the conflict-handling mode is REPLACE, then
137788   ** the conflicting row can be removed before proceeding. In the second
137789   ** case, SQLITE_CONSTRAINT must be returned regardless of the
137790   ** conflict-handling mode specified by the user.
137791   */
137792   if( nData>1 ){
137793     int ii;
137794
137795     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
137796     assert( nData==(pRtree->nDim*2 + 3) );
137797 #ifndef SQLITE_RTREE_INT_ONLY
137798     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
137799       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137800         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
137801         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
137802         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
137803           rc = SQLITE_CONSTRAINT;
137804           goto constraint;
137805         }
137806       }
137807     }else
137808 #endif
137809     {
137810       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137811         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
137812         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
137813         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
137814           rc = SQLITE_CONSTRAINT;
137815           goto constraint;
137816         }
137817       }
137818     }
137819
137820     /* If a rowid value was supplied, check if it is already present in
137821     ** the table. If so, the constraint has failed. */
137822     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
137823       cell.iRowid = sqlite3_value_int64(azData[2]);
137824       if( sqlite3_value_type(azData[0])==SQLITE_NULL
137825        || sqlite3_value_int64(azData[0])!=cell.iRowid
137826       ){
137827         int steprc;
137828         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
137829         steprc = sqlite3_step(pRtree->pReadRowid);
137830         rc = sqlite3_reset(pRtree->pReadRowid);
137831         if( SQLITE_ROW==steprc ){
137832           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
137833             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
137834           }else{
137835             rc = SQLITE_CONSTRAINT;
137836             goto constraint;
137837           }
137838         }
137839       }
137840       bHaveRowid = 1;
137841     }
137842   }
137843
137844   /* If azData[0] is not an SQL NULL value, it is the rowid of a
137845   ** record to delete from the r-tree table. The following block does
137846   ** just that.
137847   */
137848   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
137849     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
137850   }
137851
137852   /* If the azData[] array contains more than one element, elements
137853   ** (azData[2]..azData[argc-1]) contain a new record to insert into
137854   ** the r-tree structure.
137855   */
137856   if( rc==SQLITE_OK && nData>1 ){
137857     /* Insert the new record into the r-tree */
137858     RtreeNode *pLeaf = 0;
137859
137860     /* Figure out the rowid of the new row. */
137861     if( bHaveRowid==0 ){
137862       rc = newRowid(pRtree, &cell.iRowid);
137863     }
137864     *pRowid = cell.iRowid;
137865
137866     if( rc==SQLITE_OK ){
137867       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
137868     }
137869     if( rc==SQLITE_OK ){
137870       int rc2;
137871       pRtree->iReinsertHeight = -1;
137872       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
137873       rc2 = nodeRelease(pRtree, pLeaf);
137874       if( rc==SQLITE_OK ){
137875         rc = rc2;
137876       }
137877     }
137878   }
137879
137880 constraint:
137881   rtreeRelease(pRtree);
137882   return rc;
137883 }
137884
137885 /*
137886 ** The xRename method for rtree module virtual tables.
137887 */
137888 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
137889   Rtree *pRtree = (Rtree *)pVtab;
137890   int rc = SQLITE_NOMEM;
137891   char *zSql = sqlite3_mprintf(
137892     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
137893     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
137894     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
137895     , pRtree->zDb, pRtree->zName, zNewName
137896     , pRtree->zDb, pRtree->zName, zNewName
137897     , pRtree->zDb, pRtree->zName, zNewName
137898   );
137899   if( zSql ){
137900     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
137901     sqlite3_free(zSql);
137902   }
137903   return rc;
137904 }
137905
137906 static sqlite3_module rtreeModule = {
137907   0,                          /* iVersion */
137908   rtreeCreate,                /* xCreate - create a table */
137909   rtreeConnect,               /* xConnect - connect to an existing table */
137910   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
137911   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
137912   rtreeDestroy,               /* xDestroy - Drop a table */
137913   rtreeOpen,                  /* xOpen - open a cursor */
137914   rtreeClose,                 /* xClose - close a cursor */
137915   rtreeFilter,                /* xFilter - configure scan constraints */
137916   rtreeNext,                  /* xNext - advance a cursor */
137917   rtreeEof,                   /* xEof */
137918   rtreeColumn,                /* xColumn - read data */
137919   rtreeRowid,                 /* xRowid - read data */
137920   rtreeUpdate,                /* xUpdate - write data */
137921   0,                          /* xBegin - begin transaction */
137922   0,                          /* xSync - sync transaction */
137923   0,                          /* xCommit - commit transaction */
137924   0,                          /* xRollback - rollback transaction */
137925   0,                          /* xFindFunction - function overloading */
137926   rtreeRename,                /* xRename - rename the table */
137927   0,                          /* xSavepoint */
137928   0,                          /* xRelease */
137929   0                           /* xRollbackTo */
137930 };
137931
137932 static int rtreeSqlInit(
137933   Rtree *pRtree,
137934   sqlite3 *db,
137935   const char *zDb,
137936   const char *zPrefix,
137937   int isCreate
137938 ){
137939   int rc = SQLITE_OK;
137940
137941   #define N_STATEMENT 9
137942   static const char *azSql[N_STATEMENT] = {
137943     /* Read and write the xxx_node table */
137944     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
137945     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
137946     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
137947
137948     /* Read and write the xxx_rowid table */
137949     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
137950     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
137951     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
137952
137953     /* Read and write the xxx_parent table */
137954     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
137955     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
137956     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
137957   };
137958   sqlite3_stmt **appStmt[N_STATEMENT];
137959   int i;
137960
137961   pRtree->db = db;
137962
137963   if( isCreate ){
137964     char *zCreate = sqlite3_mprintf(
137965 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
137966 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
137967 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
137968 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
137969       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
137970     );
137971     if( !zCreate ){
137972       return SQLITE_NOMEM;
137973     }
137974     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
137975     sqlite3_free(zCreate);
137976     if( rc!=SQLITE_OK ){
137977       return rc;
137978     }
137979   }
137980
137981   appStmt[0] = &pRtree->pReadNode;
137982   appStmt[1] = &pRtree->pWriteNode;
137983   appStmt[2] = &pRtree->pDeleteNode;
137984   appStmt[3] = &pRtree->pReadRowid;
137985   appStmt[4] = &pRtree->pWriteRowid;
137986   appStmt[5] = &pRtree->pDeleteRowid;
137987   appStmt[6] = &pRtree->pReadParent;
137988   appStmt[7] = &pRtree->pWriteParent;
137989   appStmt[8] = &pRtree->pDeleteParent;
137990
137991   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
137992     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
137993     if( zSql ){
137994       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
137995     }else{
137996       rc = SQLITE_NOMEM;
137997     }
137998     sqlite3_free(zSql);
137999   }
138000
138001   return rc;
138002 }
138003
138004 /*
138005 ** The second argument to this function contains the text of an SQL statement
138006 ** that returns a single integer value. The statement is compiled and executed
138007 ** using database connection db. If successful, the integer value returned
138008 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
138009 ** code is returned and the value of *piVal after returning is not defined.
138010 */
138011 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
138012   int rc = SQLITE_NOMEM;
138013   if( zSql ){
138014     sqlite3_stmt *pStmt = 0;
138015     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
138016     if( rc==SQLITE_OK ){
138017       if( SQLITE_ROW==sqlite3_step(pStmt) ){
138018         *piVal = sqlite3_column_int(pStmt, 0);
138019       }
138020       rc = sqlite3_finalize(pStmt);
138021     }
138022   }
138023   return rc;
138024 }
138025
138026 /*
138027 ** This function is called from within the xConnect() or xCreate() method to
138028 ** determine the node-size used by the rtree table being created or connected
138029 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
138030 ** Otherwise, an SQLite error code is returned.
138031 **
138032 ** If this function is being called as part of an xConnect(), then the rtree
138033 ** table already exists. In this case the node-size is determined by inspecting
138034 ** the root node of the tree.
138035 **
138036 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
138037 ** This ensures that each node is stored on a single database page. If the
138038 ** database page-size is so large that more than RTREE_MAXCELLS entries
138039 ** would fit in a single node, use a smaller node-size.
138040 */
138041 static int getNodeSize(
138042   sqlite3 *db,                    /* Database handle */
138043   Rtree *pRtree,                  /* Rtree handle */
138044   int isCreate                    /* True for xCreate, false for xConnect */
138045 ){
138046   int rc;
138047   char *zSql;
138048   if( isCreate ){
138049     int iPageSize = 0;
138050     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
138051     rc = getIntFromStmt(db, zSql, &iPageSize);
138052     if( rc==SQLITE_OK ){
138053       pRtree->iNodeSize = iPageSize-64;
138054       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
138055         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
138056       }
138057     }
138058   }else{
138059     zSql = sqlite3_mprintf(
138060         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
138061         pRtree->zDb, pRtree->zName
138062     );
138063     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
138064   }
138065
138066   sqlite3_free(zSql);
138067   return rc;
138068 }
138069
138070 /*
138071 ** This function is the implementation of both the xConnect and xCreate
138072 ** methods of the r-tree virtual table.
138073 **
138074 **   argv[0]   -> module name
138075 **   argv[1]   -> database name
138076 **   argv[2]   -> table name
138077 **   argv[...] -> column names...
138078 */
138079 static int rtreeInit(
138080   sqlite3 *db,                        /* Database connection */
138081   void *pAux,                         /* One of the RTREE_COORD_* constants */
138082   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
138083   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
138084   char **pzErr,                       /* OUT: Error message, if any */
138085   int isCreate                        /* True for xCreate, false for xConnect */
138086 ){
138087   int rc = SQLITE_OK;
138088   Rtree *pRtree;
138089   int nDb;              /* Length of string argv[1] */
138090   int nName;            /* Length of string argv[2] */
138091   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
138092
138093   const char *aErrMsg[] = {
138094     0,                                                    /* 0 */
138095     "Wrong number of columns for an rtree table",         /* 1 */
138096     "Too few columns for an rtree table",                 /* 2 */
138097     "Too many columns for an rtree table"                 /* 3 */
138098   };
138099
138100   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
138101   if( aErrMsg[iErr] ){
138102     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
138103     return SQLITE_ERROR;
138104   }
138105
138106   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
138107
138108   /* Allocate the sqlite3_vtab structure */
138109   nDb = (int)strlen(argv[1]);
138110   nName = (int)strlen(argv[2]);
138111   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
138112   if( !pRtree ){
138113     return SQLITE_NOMEM;
138114   }
138115   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
138116   pRtree->nBusy = 1;
138117   pRtree->base.pModule = &rtreeModule;
138118   pRtree->zDb = (char *)&pRtree[1];
138119   pRtree->zName = &pRtree->zDb[nDb+1];
138120   pRtree->nDim = (argc-4)/2;
138121   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
138122   pRtree->eCoordType = eCoordType;
138123   memcpy(pRtree->zDb, argv[1], nDb);
138124   memcpy(pRtree->zName, argv[2], nName);
138125
138126   /* Figure out the node size to use. */
138127   rc = getNodeSize(db, pRtree, isCreate);
138128
138129   /* Create/Connect to the underlying relational database schema. If
138130   ** that is successful, call sqlite3_declare_vtab() to configure
138131   ** the r-tree table schema.
138132   */
138133   if( rc==SQLITE_OK ){
138134     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
138135       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
138136     }else{
138137       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
138138       char *zTmp;
138139       int ii;
138140       for(ii=4; zSql && ii<argc; ii++){
138141         zTmp = zSql;
138142         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
138143         sqlite3_free(zTmp);
138144       }
138145       if( zSql ){
138146         zTmp = zSql;
138147         zSql = sqlite3_mprintf("%s);", zTmp);
138148         sqlite3_free(zTmp);
138149       }
138150       if( !zSql ){
138151         rc = SQLITE_NOMEM;
138152       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
138153         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
138154       }
138155       sqlite3_free(zSql);
138156     }
138157   }
138158
138159   if( rc==SQLITE_OK ){
138160     *ppVtab = (sqlite3_vtab *)pRtree;
138161   }else{
138162     rtreeRelease(pRtree);
138163   }
138164   return rc;
138165 }
138166
138167
138168 /*
138169 ** Implementation of a scalar function that decodes r-tree nodes to
138170 ** human readable strings. This can be used for debugging and analysis.
138171 **
138172 ** The scalar function takes two arguments, a blob of data containing
138173 ** an r-tree node, and the number of dimensions the r-tree indexes.
138174 ** For a two-dimensional r-tree structure called "rt", to deserialize
138175 ** all nodes, a statement like:
138176 **
138177 **   SELECT rtreenode(2, data) FROM rt_node;
138178 **
138179 ** The human readable string takes the form of a Tcl list with one
138180 ** entry for each cell in the r-tree node. Each entry is itself a
138181 ** list, containing the 8-byte rowid/pageno followed by the
138182 ** <num-dimension>*2 coordinates.
138183 */
138184 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
138185   char *zText = 0;
138186   RtreeNode node;
138187   Rtree tree;
138188   int ii;
138189
138190   UNUSED_PARAMETER(nArg);
138191   memset(&node, 0, sizeof(RtreeNode));
138192   memset(&tree, 0, sizeof(Rtree));
138193   tree.nDim = sqlite3_value_int(apArg[0]);
138194   tree.nBytesPerCell = 8 + 8 * tree.nDim;
138195   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
138196
138197   for(ii=0; ii<NCELL(&node); ii++){
138198     char zCell[512];
138199     int nCell = 0;
138200     RtreeCell cell;
138201     int jj;
138202
138203     nodeGetCell(&tree, &node, ii, &cell);
138204     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
138205     nCell = (int)strlen(zCell);
138206     for(jj=0; jj<tree.nDim*2; jj++){
138207 #ifndef SQLITE_RTREE_INT_ONLY
138208       sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
138209                        (double)cell.aCoord[jj].f);
138210 #else
138211       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
138212                        cell.aCoord[jj].i);
138213 #endif
138214       nCell = (int)strlen(zCell);
138215     }
138216
138217     if( zText ){
138218       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
138219       sqlite3_free(zText);
138220       zText = zTextNew;
138221     }else{
138222       zText = sqlite3_mprintf("{%s}", zCell);
138223     }
138224   }
138225
138226   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
138227 }
138228
138229 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
138230   UNUSED_PARAMETER(nArg);
138231   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
138232    || sqlite3_value_bytes(apArg[0])<2
138233   ){
138234     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
138235   }else{
138236     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
138237     sqlite3_result_int(ctx, readInt16(zBlob));
138238   }
138239 }
138240
138241 /*
138242 ** Register the r-tree module with database handle db. This creates the
138243 ** virtual table module "rtree" and the debugging/analysis scalar
138244 ** function "rtreenode".
138245 */
138246 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
138247   const int utf8 = SQLITE_UTF8;
138248   int rc;
138249
138250   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
138251   if( rc==SQLITE_OK ){
138252     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
138253   }
138254   if( rc==SQLITE_OK ){
138255 #ifdef SQLITE_RTREE_INT_ONLY
138256     void *c = (void *)RTREE_COORD_INT32;
138257 #else
138258     void *c = (void *)RTREE_COORD_REAL32;
138259 #endif
138260     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
138261   }
138262   if( rc==SQLITE_OK ){
138263     void *c = (void *)RTREE_COORD_INT32;
138264     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
138265   }
138266
138267   return rc;
138268 }
138269
138270 /*
138271 ** A version of sqlite3_free() that can be used as a callback. This is used
138272 ** in two places - as the destructor for the blob value returned by the
138273 ** invocation of a geometry function, and as the destructor for the geometry
138274 ** functions themselves.
138275 */
138276 static void doSqlite3Free(void *p){
138277   sqlite3_free(p);
138278 }
138279
138280 /*
138281 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
138282 ** scalar user function. This C function is the callback used for all such
138283 ** registered SQL functions.
138284 **
138285 ** The scalar user functions return a blob that is interpreted by r-tree
138286 ** table MATCH operators.
138287 */
138288 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
138289   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
138290   RtreeMatchArg *pBlob;
138291   int nBlob;
138292
138293   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
138294   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
138295   if( !pBlob ){
138296     sqlite3_result_error_nomem(ctx);
138297   }else{
138298     int i;
138299     pBlob->magic = RTREE_GEOMETRY_MAGIC;
138300     pBlob->xGeom = pGeomCtx->xGeom;
138301     pBlob->pContext = pGeomCtx->pContext;
138302     pBlob->nParam = nArg;
138303     for(i=0; i<nArg; i++){
138304 #ifdef SQLITE_RTREE_INT_ONLY
138305       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
138306 #else
138307       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
138308 #endif
138309     }
138310     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
138311   }
138312 }
138313
138314 /*
138315 ** Register a new geometry function for use with the r-tree MATCH operator.
138316 */
138317 SQLITE_API int sqlite3_rtree_geometry_callback(
138318   sqlite3 *db,
138319   const char *zGeom,
138320   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
138321   void *pContext
138322 ){
138323   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
138324
138325   /* Allocate and populate the context object. */
138326   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
138327   if( !pGeomCtx ) return SQLITE_NOMEM;
138328   pGeomCtx->xGeom = xGeom;
138329   pGeomCtx->pContext = pContext;
138330
138331   /* Create the new user-function. Register a destructor function to delete
138332   ** the context object when it is no longer required.  */
138333   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
138334       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
138335   );
138336 }
138337
138338 #if !SQLITE_CORE
138339 SQLITE_API int sqlite3_extension_init(
138340   sqlite3 *db,
138341   char **pzErrMsg,
138342   const sqlite3_api_routines *pApi
138343 ){
138344   SQLITE_EXTENSION_INIT2(pApi)
138345   return sqlite3RtreeInit(db);
138346 }
138347 #endif
138348
138349 #endif
138350
138351 /************** End of rtree.c ***********************************************/
138352 /************** Begin file icu.c *********************************************/
138353 /*
138354 ** 2007 May 6
138355 **
138356 ** The author disclaims copyright to this source code.  In place of
138357 ** a legal notice, here is a blessing:
138358 **
138359 **    May you do good and not evil.
138360 **    May you find forgiveness for yourself and forgive others.
138361 **    May you share freely, never taking more than you give.
138362 **
138363 *************************************************************************
138364 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
138365 **
138366 ** This file implements an integration between the ICU library
138367 ** ("International Components for Unicode", an open-source library
138368 ** for handling unicode data) and SQLite. The integration uses
138369 ** ICU to provide the following to SQLite:
138370 **
138371 **   * An implementation of the SQL regexp() function (and hence REGEXP
138372 **     operator) using the ICU uregex_XX() APIs.
138373 **
138374 **   * Implementations of the SQL scalar upper() and lower() functions
138375 **     for case mapping.
138376 **
138377 **   * Integration of ICU and SQLite collation seqences.
138378 **
138379 **   * An implementation of the LIKE operator that uses ICU to
138380 **     provide case-independent matching.
138381 */
138382
138383 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
138384
138385 /* Include ICU headers */
138386 #include <unicode/utypes.h>
138387 #include <unicode/uregex.h>
138388 #include <unicode/ustring.h>
138389 #include <unicode/ucol.h>
138390
138391 /* #include <assert.h> */
138392
138393 #ifndef SQLITE_CORE
138394   SQLITE_EXTENSION_INIT1
138395 #else
138396 #endif
138397
138398 /*
138399 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
138400 ** operator.
138401 */
138402 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
138403 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
138404 #endif
138405
138406 /*
138407 ** Version of sqlite3_free() that is always a function, never a macro.
138408 */
138409 static void xFree(void *p){
138410   sqlite3_free(p);
138411 }
138412
138413 /*
138414 ** Compare two UTF-8 strings for equality where the first string is
138415 ** a "LIKE" expression. Return true (1) if they are the same and
138416 ** false (0) if they are different.
138417 */
138418 static int icuLikeCompare(
138419   const uint8_t *zPattern,   /* LIKE pattern */
138420   const uint8_t *zString,    /* The UTF-8 string to compare against */
138421   const UChar32 uEsc         /* The escape character */
138422 ){
138423   static const int MATCH_ONE = (UChar32)'_';
138424   static const int MATCH_ALL = (UChar32)'%';
138425
138426   int iPattern = 0;       /* Current byte index in zPattern */
138427   int iString = 0;        /* Current byte index in zString */
138428
138429   int prevEscape = 0;     /* True if the previous character was uEsc */
138430
138431   while( zPattern[iPattern]!=0 ){
138432
138433     /* Read (and consume) the next character from the input pattern. */
138434     UChar32 uPattern;
138435     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
138436     assert(uPattern!=0);
138437
138438     /* There are now 4 possibilities:
138439     **
138440     **     1. uPattern is an unescaped match-all character "%",
138441     **     2. uPattern is an unescaped match-one character "_",
138442     **     3. uPattern is an unescaped escape character, or
138443     **     4. uPattern is to be handled as an ordinary character
138444     */
138445     if( !prevEscape && uPattern==MATCH_ALL ){
138446       /* Case 1. */
138447       uint8_t c;
138448
138449       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
138450       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
138451       ** test string.
138452       */
138453       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
138454         if( c==MATCH_ONE ){
138455           if( zString[iString]==0 ) return 0;
138456           U8_FWD_1_UNSAFE(zString, iString);
138457         }
138458         iPattern++;
138459       }
138460
138461       if( zPattern[iPattern]==0 ) return 1;
138462
138463       while( zString[iString] ){
138464         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
138465           return 1;
138466         }
138467         U8_FWD_1_UNSAFE(zString, iString);
138468       }
138469       return 0;
138470
138471     }else if( !prevEscape && uPattern==MATCH_ONE ){
138472       /* Case 2. */
138473       if( zString[iString]==0 ) return 0;
138474       U8_FWD_1_UNSAFE(zString, iString);
138475
138476     }else if( !prevEscape && uPattern==uEsc){
138477       /* Case 3. */
138478       prevEscape = 1;
138479
138480     }else{
138481       /* Case 4. */
138482       UChar32 uString;
138483       U8_NEXT_UNSAFE(zString, iString, uString);
138484       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
138485       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
138486       if( uString!=uPattern ){
138487         return 0;
138488       }
138489       prevEscape = 0;
138490     }
138491   }
138492
138493   return zString[iString]==0;
138494 }
138495
138496 /*
138497 ** Implementation of the like() SQL function.  This function implements
138498 ** the build-in LIKE operator.  The first argument to the function is the
138499 ** pattern and the second argument is the string.  So, the SQL statements:
138500 **
138501 **       A LIKE B
138502 **
138503 ** is implemented as like(B, A). If there is an escape character E,
138504 **
138505 **       A LIKE B ESCAPE E
138506 **
138507 ** is mapped to like(B, A, E).
138508 */
138509 static void icuLikeFunc(
138510   sqlite3_context *context,
138511   int argc,
138512   sqlite3_value **argv
138513 ){
138514   const unsigned char *zA = sqlite3_value_text(argv[0]);
138515   const unsigned char *zB = sqlite3_value_text(argv[1]);
138516   UChar32 uEsc = 0;
138517
138518   /* Limit the length of the LIKE or GLOB pattern to avoid problems
138519   ** of deep recursion and N*N behavior in patternCompare().
138520   */
138521   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
138522     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
138523     return;
138524   }
138525
138526
138527   if( argc==3 ){
138528     /* The escape character string must consist of a single UTF-8 character.
138529     ** Otherwise, return an error.
138530     */
138531     int nE= sqlite3_value_bytes(argv[2]);
138532     const unsigned char *zE = sqlite3_value_text(argv[2]);
138533     int i = 0;
138534     if( zE==0 ) return;
138535     U8_NEXT(zE, i, nE, uEsc);
138536     if( i!=nE){
138537       sqlite3_result_error(context,
138538           "ESCAPE expression must be a single character", -1);
138539       return;
138540     }
138541   }
138542
138543   if( zA && zB ){
138544     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
138545   }
138546 }
138547
138548 /*
138549 ** This function is called when an ICU function called from within
138550 ** the implementation of an SQL scalar function returns an error.
138551 **
138552 ** The scalar function context passed as the first argument is
138553 ** loaded with an error message based on the following two args.
138554 */
138555 static void icuFunctionError(
138556   sqlite3_context *pCtx,       /* SQLite scalar function context */
138557   const char *zName,           /* Name of ICU function that failed */
138558   UErrorCode e                 /* Error code returned by ICU function */
138559 ){
138560   char zBuf[128];
138561   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
138562   zBuf[127] = '\0';
138563   sqlite3_result_error(pCtx, zBuf, -1);
138564 }
138565
138566 /*
138567 ** Function to delete compiled regexp objects. Registered as
138568 ** a destructor function with sqlite3_set_auxdata().
138569 */
138570 static void icuRegexpDelete(void *p){
138571   URegularExpression *pExpr = (URegularExpression *)p;
138572   uregex_close(pExpr);
138573 }
138574
138575 /*
138576 ** Implementation of SQLite REGEXP operator. This scalar function takes
138577 ** two arguments. The first is a regular expression pattern to compile
138578 ** the second is a string to match against that pattern. If either
138579 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
138580 ** is 1 if the string matches the pattern, or 0 otherwise.
138581 **
138582 ** SQLite maps the regexp() function to the regexp() operator such
138583 ** that the following two are equivalent:
138584 **
138585 **     zString REGEXP zPattern
138586 **     regexp(zPattern, zString)
138587 **
138588 ** Uses the following ICU regexp APIs:
138589 **
138590 **     uregex_open()
138591 **     uregex_matches()
138592 **     uregex_close()
138593 */
138594 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
138595   UErrorCode status = U_ZERO_ERROR;
138596   URegularExpression *pExpr;
138597   UBool res;
138598   const UChar *zString = sqlite3_value_text16(apArg[1]);
138599
138600   (void)nArg;  /* Unused parameter */
138601
138602   /* If the left hand side of the regexp operator is NULL,
138603   ** then the result is also NULL.
138604   */
138605   if( !zString ){
138606     return;
138607   }
138608
138609   pExpr = sqlite3_get_auxdata(p, 0);
138610   if( !pExpr ){
138611     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
138612     if( !zPattern ){
138613       return;
138614     }
138615     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
138616
138617     if( U_SUCCESS(status) ){
138618       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
138619     }else{
138620       assert(!pExpr);
138621       icuFunctionError(p, "uregex_open", status);
138622       return;
138623     }
138624   }
138625
138626   /* Configure the text that the regular expression operates on. */
138627   uregex_setText(pExpr, zString, -1, &status);
138628   if( !U_SUCCESS(status) ){
138629     icuFunctionError(p, "uregex_setText", status);
138630     return;
138631   }
138632
138633   /* Attempt the match */
138634   res = uregex_matches(pExpr, 0, &status);
138635   if( !U_SUCCESS(status) ){
138636     icuFunctionError(p, "uregex_matches", status);
138637     return;
138638   }
138639
138640   /* Set the text that the regular expression operates on to a NULL
138641   ** pointer. This is not really necessary, but it is tidier than
138642   ** leaving the regular expression object configured with an invalid
138643   ** pointer after this function returns.
138644   */
138645   uregex_setText(pExpr, 0, 0, &status);
138646
138647   /* Return 1 or 0. */
138648   sqlite3_result_int(p, res ? 1 : 0);
138649 }
138650
138651 /*
138652 ** Implementations of scalar functions for case mapping - upper() and
138653 ** lower(). Function upper() converts its input to upper-case (ABC).
138654 ** Function lower() converts to lower-case (abc).
138655 **
138656 ** ICU provides two types of case mapping, "general" case mapping and
138657 ** "language specific". Refer to ICU documentation for the differences
138658 ** between the two.
138659 **
138660 ** To utilise "general" case mapping, the upper() or lower() scalar
138661 ** functions are invoked with one argument:
138662 **
138663 **     upper('ABC') -> 'abc'
138664 **     lower('abc') -> 'ABC'
138665 **
138666 ** To access ICU "language specific" case mapping, upper() or lower()
138667 ** should be invoked with two arguments. The second argument is the name
138668 ** of the locale to use. Passing an empty string ("") or SQL NULL value
138669 ** as the second argument is the same as invoking the 1 argument version
138670 ** of upper() or lower().
138671 **
138672 **     lower('I', 'en_us') -> 'i'
138673 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
138674 **
138675 ** http://www.icu-project.org/userguide/posix.html#case_mappings
138676 */
138677 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
138678   const UChar *zInput;
138679   UChar *zOutput;
138680   int nInput;
138681   int nOutput;
138682
138683   UErrorCode status = U_ZERO_ERROR;
138684   const char *zLocale = 0;
138685
138686   assert(nArg==1 || nArg==2);
138687   if( nArg==2 ){
138688     zLocale = (const char *)sqlite3_value_text(apArg[1]);
138689   }
138690
138691   zInput = sqlite3_value_text16(apArg[0]);
138692   if( !zInput ){
138693     return;
138694   }
138695   nInput = sqlite3_value_bytes16(apArg[0]);
138696
138697   nOutput = nInput * 2 + 2;
138698   zOutput = sqlite3_malloc(nOutput);
138699   if( !zOutput ){
138700     return;
138701   }
138702
138703   if( sqlite3_user_data(p) ){
138704     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
138705   }else{
138706     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
138707   }
138708
138709   if( !U_SUCCESS(status) ){
138710     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
138711     return;
138712   }
138713
138714   sqlite3_result_text16(p, zOutput, -1, xFree);
138715 }
138716
138717 /*
138718 ** Collation sequence destructor function. The pCtx argument points to
138719 ** a UCollator structure previously allocated using ucol_open().
138720 */
138721 static void icuCollationDel(void *pCtx){
138722   UCollator *p = (UCollator *)pCtx;
138723   ucol_close(p);
138724 }
138725
138726 /*
138727 ** Collation sequence comparison function. The pCtx argument points to
138728 ** a UCollator structure previously allocated using ucol_open().
138729 */
138730 static int icuCollationColl(
138731   void *pCtx,
138732   int nLeft,
138733   const void *zLeft,
138734   int nRight,
138735   const void *zRight
138736 ){
138737   UCollationResult res;
138738   UCollator *p = (UCollator *)pCtx;
138739   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
138740   switch( res ){
138741     case UCOL_LESS:    return -1;
138742     case UCOL_GREATER: return +1;
138743     case UCOL_EQUAL:   return 0;
138744   }
138745   assert(!"Unexpected return value from ucol_strcoll()");
138746   return 0;
138747 }
138748
138749 /*
138750 ** Implementation of the scalar function icu_load_collation().
138751 **
138752 ** This scalar function is used to add ICU collation based collation
138753 ** types to an SQLite database connection. It is intended to be called
138754 ** as follows:
138755 **
138756 **     SELECT icu_load_collation(<locale>, <collation-name>);
138757 **
138758 ** Where <locale> is a string containing an ICU locale identifier (i.e.
138759 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
138760 ** collation sequence to create.
138761 */
138762 static void icuLoadCollation(
138763   sqlite3_context *p,
138764   int nArg,
138765   sqlite3_value **apArg
138766 ){
138767   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
138768   UErrorCode status = U_ZERO_ERROR;
138769   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
138770   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
138771   UCollator *pUCollator;    /* ICU library collation object */
138772   int rc;                   /* Return code from sqlite3_create_collation_x() */
138773
138774   assert(nArg==2);
138775   zLocale = (const char *)sqlite3_value_text(apArg[0]);
138776   zName = (const char *)sqlite3_value_text(apArg[1]);
138777
138778   if( !zLocale || !zName ){
138779     return;
138780   }
138781
138782   pUCollator = ucol_open(zLocale, &status);
138783   if( !U_SUCCESS(status) ){
138784     icuFunctionError(p, "ucol_open", status);
138785     return;
138786   }
138787   assert(p);
138788
138789   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
138790       icuCollationColl, icuCollationDel
138791   );
138792   if( rc!=SQLITE_OK ){
138793     ucol_close(pUCollator);
138794     sqlite3_result_error(p, "Error registering collation function", -1);
138795   }
138796 }
138797
138798 /*
138799 ** Register the ICU extension functions with database db.
138800 */
138801 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
138802   struct IcuScalar {
138803     const char *zName;                        /* Function name */
138804     int nArg;                                 /* Number of arguments */
138805     int enc;                                  /* Optimal text encoding */
138806     void *pContext;                           /* sqlite3_user_data() context */
138807     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
138808   } scalars[] = {
138809     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
138810
138811     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
138812     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
138813     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
138814     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
138815
138816     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
138817     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
138818     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
138819     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
138820
138821     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
138822     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
138823
138824     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
138825   };
138826
138827   int rc = SQLITE_OK;
138828   int i;
138829
138830   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
138831     struct IcuScalar *p = &scalars[i];
138832     rc = sqlite3_create_function(
138833         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
138834     );
138835   }
138836
138837   return rc;
138838 }
138839
138840 #if !SQLITE_CORE
138841 SQLITE_API int sqlite3_extension_init(
138842   sqlite3 *db,
138843   char **pzErrMsg,
138844   const sqlite3_api_routines *pApi
138845 ){
138846   SQLITE_EXTENSION_INIT2(pApi)
138847   return sqlite3IcuInit(db);
138848 }
138849 #endif
138850
138851 #endif
138852
138853 /************** End of icu.c *************************************************/
138854 /************** Begin file fts3_icu.c ****************************************/
138855 /*
138856 ** 2007 June 22
138857 **
138858 ** The author disclaims copyright to this source code.  In place of
138859 ** a legal notice, here is a blessing:
138860 **
138861 **    May you do good and not evil.
138862 **    May you find forgiveness for yourself and forgive others.
138863 **    May you share freely, never taking more than you give.
138864 **
138865 *************************************************************************
138866 ** This file implements a tokenizer for fts3 based on the ICU library.
138867 */
138868 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138869 #ifdef SQLITE_ENABLE_ICU
138870
138871 /* #include <assert.h> */
138872 /* #include <string.h> */
138873
138874 #include <unicode/ubrk.h>
138875 /* #include <unicode/ucol.h> */
138876 /* #include <unicode/ustring.h> */
138877 #include <unicode/utf16.h>
138878
138879 typedef struct IcuTokenizer IcuTokenizer;
138880 typedef struct IcuCursor IcuCursor;
138881
138882 struct IcuTokenizer {
138883   sqlite3_tokenizer base;
138884   char *zLocale;
138885 };
138886
138887 struct IcuCursor {
138888   sqlite3_tokenizer_cursor base;
138889
138890   UBreakIterator *pIter;      /* ICU break-iterator object */
138891   int nChar;                  /* Number of UChar elements in pInput */
138892   UChar *aChar;               /* Copy of input using utf-16 encoding */
138893   int *aOffset;               /* Offsets of each character in utf-8 input */
138894
138895   int nBuffer;
138896   char *zBuffer;
138897
138898   int iToken;
138899 };
138900
138901 /*
138902 ** Create a new tokenizer instance.
138903 */
138904 static int icuCreate(
138905   int argc,                            /* Number of entries in argv[] */
138906   const char * const *argv,            /* Tokenizer creation arguments */
138907   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
138908 ){
138909   IcuTokenizer *p;
138910   int n = 0;
138911
138912   if( argc>0 ){
138913     n = strlen(argv[0])+1;
138914   }
138915   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
138916   if( !p ){
138917     return SQLITE_NOMEM;
138918   }
138919   memset(p, 0, sizeof(IcuTokenizer));
138920
138921   if( n ){
138922     p->zLocale = (char *)&p[1];
138923     memcpy(p->zLocale, argv[0], n);
138924   }
138925
138926   *ppTokenizer = (sqlite3_tokenizer *)p;
138927
138928   return SQLITE_OK;
138929 }
138930
138931 /*
138932 ** Destroy a tokenizer
138933 */
138934 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
138935   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
138936   sqlite3_free(p);
138937   return SQLITE_OK;
138938 }
138939
138940 /*
138941 ** Prepare to begin tokenizing a particular string.  The input
138942 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
138943 ** used to incrementally tokenize this string is returned in
138944 ** *ppCursor.
138945 */
138946 static int icuOpen(
138947   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
138948   const char *zInput,                    /* Input string */
138949   int nInput,                            /* Length of zInput in bytes */
138950   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
138951 ){
138952   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
138953   IcuCursor *pCsr;
138954
138955   const int32_t opt = U_FOLD_CASE_DEFAULT;
138956   UErrorCode status = U_ZERO_ERROR;
138957   int nChar;
138958
138959   UChar32 c;
138960   int iInput = 0;
138961   int iOut = 0;
138962
138963   *ppCursor = 0;
138964
138965   if( zInput==0 ){
138966     nInput = 0;
138967     zInput = "";
138968   }else if( nInput<0 ){
138969     nInput = strlen(zInput);
138970   }
138971   nChar = nInput+1;
138972   pCsr = (IcuCursor *)sqlite3_malloc(
138973       sizeof(IcuCursor) +                /* IcuCursor */
138974       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
138975       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
138976   );
138977   if( !pCsr ){
138978     return SQLITE_NOMEM;
138979   }
138980   memset(pCsr, 0, sizeof(IcuCursor));
138981   pCsr->aChar = (UChar *)&pCsr[1];
138982   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
138983
138984   pCsr->aOffset[iOut] = iInput;
138985   U8_NEXT(zInput, iInput, nInput, c);
138986   while( c>0 ){
138987     int isError = 0;
138988     c = u_foldCase(c, opt);
138989     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
138990     if( isError ){
138991       sqlite3_free(pCsr);
138992       return SQLITE_ERROR;
138993     }
138994     pCsr->aOffset[iOut] = iInput;
138995
138996     if( iInput<nInput ){
138997       U8_NEXT(zInput, iInput, nInput, c);
138998     }else{
138999       c = 0;
139000     }
139001   }
139002
139003   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
139004   if( !U_SUCCESS(status) ){
139005     sqlite3_free(pCsr);
139006     return SQLITE_ERROR;
139007   }
139008   pCsr->nChar = iOut;
139009
139010   ubrk_first(pCsr->pIter);
139011   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
139012   return SQLITE_OK;
139013 }
139014
139015 /*
139016 ** Close a tokenization cursor previously opened by a call to icuOpen().
139017 */
139018 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
139019   IcuCursor *pCsr = (IcuCursor *)pCursor;
139020   ubrk_close(pCsr->pIter);
139021   sqlite3_free(pCsr->zBuffer);
139022   sqlite3_free(pCsr);
139023   return SQLITE_OK;
139024 }
139025
139026 /*
139027 ** Extract the next token from a tokenization cursor.
139028 */
139029 static int icuNext(
139030   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
139031   const char **ppToken,               /* OUT: *ppToken is the token text */
139032   int *pnBytes,                       /* OUT: Number of bytes in token */
139033   int *piStartOffset,                 /* OUT: Starting offset of token */
139034   int *piEndOffset,                   /* OUT: Ending offset of token */
139035   int *piPosition                     /* OUT: Position integer of token */
139036 ){
139037   IcuCursor *pCsr = (IcuCursor *)pCursor;
139038
139039   int iStart = 0;
139040   int iEnd = 0;
139041   int nByte = 0;
139042
139043   while( iStart==iEnd ){
139044     UChar32 c;
139045
139046     iStart = ubrk_current(pCsr->pIter);
139047     iEnd = ubrk_next(pCsr->pIter);
139048     if( iEnd==UBRK_DONE ){
139049       return SQLITE_DONE;
139050     }
139051
139052     while( iStart<iEnd ){
139053       int iWhite = iStart;
139054       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
139055       if( u_isspace(c) ){
139056         iStart = iWhite;
139057       }else{
139058         break;
139059       }
139060     }
139061     assert(iStart<=iEnd);
139062   }
139063
139064   do {
139065     UErrorCode status = U_ZERO_ERROR;
139066     if( nByte ){
139067       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
139068       if( !zNew ){
139069         return SQLITE_NOMEM;
139070       }
139071       pCsr->zBuffer = zNew;
139072       pCsr->nBuffer = nByte;
139073     }
139074
139075     u_strToUTF8(
139076         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
139077         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
139078         &status                                  /* Output success/failure */
139079     );
139080   } while( nByte>pCsr->nBuffer );
139081
139082   *ppToken = pCsr->zBuffer;
139083   *pnBytes = nByte;
139084   *piStartOffset = pCsr->aOffset[iStart];
139085   *piEndOffset = pCsr->aOffset[iEnd];
139086   *piPosition = pCsr->iToken++;
139087
139088   return SQLITE_OK;
139089 }
139090
139091 /*
139092 ** The set of routines that implement the simple tokenizer
139093 */
139094 static const sqlite3_tokenizer_module icuTokenizerModule = {
139095   0,                           /* iVersion */
139096   icuCreate,                   /* xCreate  */
139097   icuDestroy,                  /* xCreate  */
139098   icuOpen,                     /* xOpen    */
139099   icuClose,                    /* xClose   */
139100   icuNext,                     /* xNext    */
139101 };
139102
139103 /*
139104 ** Set *ppModule to point at the implementation of the ICU tokenizer.
139105 */
139106 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
139107   sqlite3_tokenizer_module const**ppModule
139108 ){
139109   *ppModule = &icuTokenizerModule;
139110 }
139111
139112 #endif /* defined(SQLITE_ENABLE_ICU) */
139113 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
139114
139115 /************** End of fts3_icu.c ********************************************/